title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Check if a given matrix is sparse or not - GeeksforGeeks
25 May, 2021 A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4 6 0 0 Output : Yes There are 5 zeros. This count is more than half of matrix size. Input : 1 2 3 0 7 8 5 0 7 Output: No To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. C++ Java Python3 C# PHP Javascript // CPP code to check if a matrix is// sparse.#include <iostream>using namespace std; const int MAX = 100; bool isSparse(int array[][MAX], int m, int n){ int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2));} // Driver Functionint main(){ int array[][MAX] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) cout << "Yes"; else cout << "No";} // Java code to check// if a matrix is// sparse. import java.io.*; class GFG { static int MAX = 100; static boolean isSparse(int array[][], int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function public static void main(String args[]) { int array[][] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// Nikita Tiwari. # Python 3 code to check# if a matrix is# sparse. MAX = 100 def isSparse(array,m, n) : counter = 0 # Count number of zeros # in the matrix for i in range(0,m) : for j in range(0,n) : if (array[i][j] == 0) : counter = counter + 1 return (counter > ((m * n) // 2)) # Driver Functionarray = [ [ 1, 0, 3 ], [ 0, 0, 4 ], [ 6, 0, 0 ] ]m = 3n = 3 if (isSparse(array, m, n)) : print("Yes")else : print("No") # this code is contributed by# Nikita tiwari // C# code to check if a matrix is// sparse.using System; class GFG { static bool isSparse(int [,]array, int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i,j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function public static void Main() { int [,]array = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// PHP code to check if a matrix is// sparse. $MAX = 100; function isSparse( $array, $m, $n){ $counter = 0; // Count number of zeros // in the matrix for ($i = 0; $i < $m; ++$i) for ($j = 0; $j < $n; ++$j) if ($array[$i][$j] == 0) ++$counter; return ($counter > (($m * $n) / 2));} // Driver Code $array = array(array(1, 0, 3), array(0, 0, 4), array(6, 0, 0)); $m = 3; $n = 3; if (isSparse($array, $m, $n)) echo "Yes"; else echo "No"; // This code is contributed by anuj_67.?> <script> // Javascript code to check // if a matrix is // sparse. let MAX = 100; function isSparse(array, m, n) { let counter = 0; // Count number of zeros in the matrix for (let i = 0; i < m; ++i) for (let j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > parseInt((m * n) / 2), 10); } let array = [ [ 1, 0, 3 ], [ 0, 0, 4 ], [ 6, 0, 0 ] ]; let m = 3, n = 3; if (isSparse(array, m, n)) document.write("Yes"); else document.write("No"); </script> Output: Yes This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m suresh07 Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Maximum size rectangle binary sub-matrix with all 1s Min Cost Path | DP-6 Printing all solutions in N-Queen Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space The Celebrity Problem Python program to multiply two matrices Search in a row wise and column wise sorted matrix Efficiently compute sums of diagonals of a matrix Real-time application of Data Structures
[ { "code": null, "e": 26370, "s": 26342, "text": "\n25 May, 2021" }, { "code": null, "e": 26690, "s": 26370, "text": "A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix," }, { "code": null, "e": 26701, "s": 26690, "text": "Examples: " }, { "code": null, "e": 26876, "s": 26701, "text": "Input : 1 0 3\n 0 0 4\n 6 0 0\nOutput : Yes\nThere are 5 zeros. This count\nis more than half of matrix\nsize.\n\nInput : 1 2 3\n 0 7 8\n 5 0 7 \nOutput: No " }, { "code": null, "e": 27052, "s": 26876, "text": "To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. " }, { "code": null, "e": 27056, "s": 27052, "text": "C++" }, { "code": null, "e": 27061, "s": 27056, "text": "Java" }, { "code": null, "e": 27069, "s": 27061, "text": "Python3" }, { "code": null, "e": 27072, "s": 27069, "text": "C#" }, { "code": null, "e": 27076, "s": 27072, "text": "PHP" }, { "code": null, "e": 27087, "s": 27076, "text": "Javascript" }, { "code": "// CPP code to check if a matrix is// sparse.#include <iostream>using namespace std; const int MAX = 100; bool isSparse(int array[][MAX], int m, int n){ int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2));} // Driver Functionint main(){ int array[][MAX] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) cout << \"Yes\"; else cout << \"No\";}", "e": 27719, "s": 27087, "text": null }, { "code": "// Java code to check// if a matrix is// sparse. import java.io.*; class GFG { static int MAX = 100; static boolean isSparse(int array[][], int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function public static void main(String args[]) { int array[][] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// Nikita Tiwari.", "e": 28576, "s": 27719, "text": null }, { "code": "# Python 3 code to check# if a matrix is# sparse. MAX = 100 def isSparse(array,m, n) : counter = 0 # Count number of zeros # in the matrix for i in range(0,m) : for j in range(0,n) : if (array[i][j] == 0) : counter = counter + 1 return (counter > ((m * n) // 2)) # Driver Functionarray = [ [ 1, 0, 3 ], [ 0, 0, 4 ], [ 6, 0, 0 ] ]m = 3n = 3 if (isSparse(array, m, n)) : print(\"Yes\")else : print(\"No\") # this code is contributed by# Nikita tiwari", "e": 29123, "s": 28576, "text": null }, { "code": "// C# code to check if a matrix is// sparse.using System; class GFG { static bool isSparse(int [,]array, int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i,j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function public static void Main() { int [,]array = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 29949, "s": 29123, "text": null }, { "code": "<?php// PHP code to check if a matrix is// sparse. $MAX = 100; function isSparse( $array, $m, $n){ $counter = 0; // Count number of zeros // in the matrix for ($i = 0; $i < $m; ++$i) for ($j = 0; $j < $n; ++$j) if ($array[$i][$j] == 0) ++$counter; return ($counter > (($m * $n) / 2));} // Driver Code $array = array(array(1, 0, 3), array(0, 0, 4), array(6, 0, 0)); $m = 3; $n = 3; if (isSparse($array, $m, $n)) echo \"Yes\"; else echo \"No\"; // This code is contributed by anuj_67.?>", "e": 30550, "s": 29949, "text": null }, { "code": "<script> // Javascript code to check // if a matrix is // sparse. let MAX = 100; function isSparse(array, m, n) { let counter = 0; // Count number of zeros in the matrix for (let i = 0; i < m; ++i) for (let j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > parseInt((m * n) / 2), 10); } let array = [ [ 1, 0, 3 ], [ 0, 0, 4 ], [ 6, 0, 0 ] ]; let m = 3, n = 3; if (isSparse(array, m, n)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 31218, "s": 30550, "text": null }, { "code": null, "e": 31228, "s": 31218, "text": "Output: " }, { "code": null, "e": 31232, "s": 31228, "text": "Yes" }, { "code": null, "e": 31652, "s": 31232, "text": "This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31657, "s": 31652, "text": "vt_m" }, { "code": null, "e": 31666, "s": 31657, "text": "suresh07" }, { "code": null, "e": 31673, "s": 31666, "text": "Matrix" }, { "code": null, "e": 31680, "s": 31673, "text": "Matrix" }, { "code": null, "e": 31778, "s": 31680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31821, "s": 31778, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 31874, "s": 31821, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 31895, "s": 31874, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 31937, "s": 31895, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 32019, "s": 31937, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 32041, "s": 32019, "text": "The Celebrity Problem" }, { "code": null, "e": 32081, "s": 32041, "text": "Python program to multiply two matrices" }, { "code": null, "e": 32132, "s": 32081, "text": "Search in a row wise and column wise sorted matrix" }, { "code": null, "e": 32182, "s": 32132, "text": "Efficiently compute sums of diagonals of a matrix" } ]
Range LCM Queries - GeeksforGeeks
18 May, 2021 Given an array of integers, evaluate queries of the form LCM(l, r). There might be many queries, hence evaluate the queries efficiently. LCM (l, r) denotes the LCM of array elements that lie between the index l and r (inclusive of both indices) Mathematically, LCM(l, r) = LCM(arr[l], arr[l+1] , ......... , arr[r-1], arr[r]) Examples: Inputs : Array = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 44} Queries: LCM(2, 5), LCM(5, 10), LCM(0, 10) Outputs: 60 15708 78540 Explanation : In the first query LCM(5, 2, 10, 12) = 60, similarly in other queries. A naive solution would be to traverse the array for every query and calculate the answer by using, LCM(a, b) = (a*b) / GCD(a,b)However as the number of queries can be large, this solution would be impractical.An efficient solution would be to use segment tree. Recall that in this case, where no update is required, we can build the tree once and can use that repeatedly to answer the queries. Each node in the tree should store the LCM value for that particular segment and we can use the same formula as above to combine the segments. Hence we can answer each query efficiently!Below is a solution for the same. C++ Java Python3 C# Javascript // LCM of given range queries using Segment Tree#include <bits/stdc++.h>using namespace std; #define MAX 1000 // allocate space for treeint tree[4*MAX]; // declaring the array globallyint arr[MAX]; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} //utility function to find lcmint lcm(int a, int b){ return a*b/gcd(a,b);} // Function to build the segment tree// Node starts beginning index of current subtree.// start and end are indexes in arr[] which is globalvoid build(int node, int start, int end){ // If there is only one element in current subarray if (start==end) { tree[node] = arr[start]; return; } int mid = (start+end)/2; // build left and right segments build(2*node, start, mid); build(2*node+1, mid+1, end); // build the parent int left_lcm = tree[2*node]; int right_lcm = tree[2*node+1]; tree[node] = lcm(left_lcm, right_lcm);} // Function to make queries for array range )l, r).// Node is index of root of current segment in segment// tree (Note that indexes in segment tree begin with 1// for simplicity).// start and end are indexes of subarray covered by root// of current segment.int query(int node, int start, int end, int l, int r){ // Completely outside the segment, returning // 1 will not affect the lcm; if (end<l || start>r) return 1; // completely inside the segment if (l<=start && r>=end) return tree[node]; // partially inside int mid = (start+end)/2; int left_lcm = query(2*node, start, mid, l, r); int right_lcm = query(2*node+1, mid+1, end, l, r); return lcm(left_lcm, right_lcm);} //driver function to check the above programint main(){ //initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) cout << query(1, 0, 10, 2, 5) << endl; // Print LCM of (5, 10) cout << query(1, 0, 10, 5, 10) << endl; // Print LCM of (0, 10) cout << query(1, 0, 10, 0, 10) << endl; return 0;} // LCM of given range queries// using Segment Tree class GFG{ static final int MAX = 1000; // allocate space for tree static int tree[] = new int[4 * MAX]; // declaring the array globally static int arr[] = new int[MAX]; // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } // utility function to find lcm static int lcm(int a, int b) { return a * b / gcd(a, b); } // Function to build the segment tree // Node starts beginning index // of current subtree. start and end // are indexes in arr[] which is global static void build(int node, int start, int end) { // If there is only one element // in current subarray if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; // build left and right segments build(2 * node, start, mid); build(2 * node + 1, mid + 1, end); // build the parent int left_lcm = tree[2 * node]; int right_lcm = tree[2 * node + 1]; tree[node] = lcm(left_lcm, right_lcm); } // Function to make queries for // array range )l, r). Node is index // of root of current segment in segment // tree (Note that indexes in segment // tree begin with 1 for simplicity). // start and end are indexes of subarray // covered by root of current segment. static int query(int node, int start, int end, int l, int r) { // Completely outside the segment, returning // 1 will not affect the lcm; if (end < l || start > r) { return 1; } // completely inside the segment if (l <= start && r >= end) { return tree[node]; } // partially inside int mid = (start + end) / 2; int left_lcm = query(2 * node, start, mid, l, r); int right_lcm = query(2 * node + 1, mid + 1, end, l, r); return lcm(left_lcm, right_lcm); } // Driver code public static void main(String[] args) { //initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) System.out.println(query(1, 0, 10, 2, 5)); // Print LCM of (5, 10) System.out.println(query(1, 0, 10, 5, 10)); // Print LCM of (0, 10) System.out.println(query(1, 0, 10, 0, 10)); }} // This code is contributed by 29AjayKumar # LCM of given range queries using Segment TreeMAX = 1000 # allocate space for treetree = [0] * (4 * MAX) # declaring the array globallyarr = [0] * MAX # Function to return gcd of a and bdef gcd(a: int, b: int): if a == 0: return b return gcd(b % a, a) # utility function to find lcmdef lcm(a: int, b: int): return (a * b) // gcd(a, b) # Function to build the segment tree# Node starts beginning index of current subtree.# start and end are indexes in arr[] which is globaldef build(node: int, start: int, end: int): # If there is only one element # in current subarray if start == end: tree[node] = arr[start] return mid = (start + end) // 2 # build left and right segments build(2 * node, start, mid) build(2 * node + 1, mid + 1, end) # build the parent left_lcm = tree[2 * node] right_lcm = tree[2 * node + 1] tree[node] = lcm(left_lcm, right_lcm) # Function to make queries for array range )l, r).# Node is index of root of current segment in segment# tree (Note that indexes in segment tree begin with 1# for simplicity).# start and end are indexes of subarray covered by root# of current segment.def query(node: int, start: int, end: int, l: int, r: int): # Completely outside the segment, # returning 1 will not affect the lcm; if end < l or start > r: return 1 # completely inside the segment if l <= start and r >= end: return tree[node] # partially inside mid = (start + end) // 2 left_lcm = query(2 * node, start, mid, l, r) right_lcm = query(2 * node + 1, mid + 1, end, l, r) return lcm(left_lcm, right_lcm) # Driver Codeif __name__ == "__main__": # initialize the array arr[0] = 5 arr[1] = 7 arr[2] = 5 arr[3] = 2 arr[4] = 10 arr[5] = 12 arr[6] = 11 arr[7] = 17 arr[8] = 14 arr[9] = 1 arr[10] = 44 # build the segment tree build(1, 0, 10) # Now we can answer each query efficiently # Print LCM of (2, 5) print(query(1, 0, 10, 2, 5)) # Print LCM of (5, 10) print(query(1, 0, 10, 5, 10)) # Print LCM of (0, 10) print(query(1, 0, 10, 0, 10)) # This code is contributed by# sanjeev2552 // LCM of given range queries// using Segment Treeusing System;using System.Collections.Generic; class GFG{ static readonly int MAX = 1000; // allocate space for tree static int []tree = new int[4 * MAX]; // declaring the array globally static int []arr = new int[MAX]; // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } // utility function to find lcm static int lcm(int a, int b) { return a * b / gcd(a, b); } // Function to build the segment tree // Node starts beginning index // of current subtree. start and end // are indexes in []arr which is global static void build(int node, int start, int end) { // If there is only one element // in current subarray if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; // build left and right segments build(2 * node, start, mid); build(2 * node + 1, mid + 1, end); // build the parent int left_lcm = tree[2 * node]; int right_lcm = tree[2 * node + 1]; tree[node] = lcm(left_lcm, right_lcm); } // Function to make queries for // array range )l, r). Node is index // of root of current segment in segment // tree (Note that indexes in segment // tree begin with 1 for simplicity). // start and end are indexes of subarray // covered by root of current segment. static int query(int node, int start, int end, int l, int r) { // Completely outside the segment, // returning 1 will not affect the lcm; if (end < l || start > r) { return 1; } // completely inside the segment if (l <= start && r >= end) { return tree[node]; } // partially inside int mid = (start + end) / 2; int left_lcm = query(2 * node, start, mid, l, r); int right_lcm = query(2 * node + 1, mid + 1, end, l, r); return lcm(left_lcm, right_lcm); } // Driver code public static void Main(String[] args) { // initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) Console.WriteLine(query(1, 0, 10, 2, 5)); // Print LCM of (5, 10) Console.WriteLine(query(1, 0, 10, 5, 10)); // Print LCM of (0, 10) Console.WriteLine(query(1, 0, 10, 0, 10)); }} // This code is contributed by Rajput-Ji <script>// LCM of given range queries using Segment Treeconst MAX = 1000 // allocate space for treevar tree = new Array(4*MAX); // declaring the array globallyvar arr = new Array(MAX); // Function to return gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b%a, a);} //utility function to find lcmfunction lcm(a, b){ return Math.floor(a*b/gcd(a,b));} // Function to build the segment tree// Node starts beginning index of current subtree.// start and end are indexes in arr[] which is globalfunction build(node, start, end){ // If there is only one element in current subarray if (start==end) { tree[node] = arr[start]; return; } let mid = Math.floor((start+end)/2); // build left and right segments build(2*node, start, mid); build(2*node+1, mid+1, end); // build the parent let left_lcm = tree[2*node]; let right_lcm = tree[2*node+1]; tree[node] = lcm(left_lcm, right_lcm);} // Function to make queries for array range )l, r).// Node is index of root of current segment in segment// tree (Note that indexes in segment tree begin with 1// for simplicity).// start and end are indexes of subarray covered by root// of current segment.function query(node, start, end, l, r){ // Completely outside the segment, returning // 1 will not affect the lcm; if (end<l || start>r) return 1; // completely inside the segment if (l<=start && r>=end) return tree[node]; // partially inside let mid = Math.floor((start+end)/2); let left_lcm = query(2*node, start, mid, l, r); let right_lcm = query(2*node+1, mid+1, end, l, r); return lcm(left_lcm, right_lcm);} //driver function to check the above program //initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) document.write(query(1, 0, 10, 2, 5) +"<br>"); // Print LCM of (5, 10) document.write(query(1, 0, 10, 5, 10) + "<br>"); // Print LCM of (0, 10) document.write(query(1, 0, 10, 0, 10) + "<br>"); // This code is contributed by Manoj.</script> Output: 60 15708 78540 This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar sanjeev2552 Rajput-Ji mank1083 array-range-queries Segment-Tree Advanced Data Structure Tree Tree Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) AVL Tree | Set 2 (Deletion) Ordered Set and GNU C++ PBDS Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 26451, "s": 26423, "text": "\n18 May, 2021" }, { "code": null, "e": 26590, "s": 26451, "text": "Given an array of integers, evaluate queries of the form LCM(l, r). There might be many queries, hence evaluate the queries efficiently. " }, { "code": null, "e": 26839, "s": 26590, "text": "LCM (l, r) denotes the LCM of array elements\n that lie between the index l and r\n (inclusive of both indices) \n\nMathematically, \nLCM(l, r) = LCM(arr[l], arr[l+1] , ......... ,\n arr[r-1], arr[r])" }, { "code": null, "e": 26851, "s": 26839, "text": "Examples: " }, { "code": null, "e": 27084, "s": 26851, "text": "Inputs : Array = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1, 44}\n Queries: LCM(2, 5), LCM(5, 10), LCM(0, 10)\nOutputs: 60 15708 78540\nExplanation : In the first query LCM(5, 2, 10, 12) = 60, \n similarly in other queries." }, { "code": null, "e": 27702, "s": 27086, "text": "A naive solution would be to traverse the array for every query and calculate the answer by using, LCM(a, b) = (a*b) / GCD(a,b)However as the number of queries can be large, this solution would be impractical.An efficient solution would be to use segment tree. Recall that in this case, where no update is required, we can build the tree once and can use that repeatedly to answer the queries. Each node in the tree should store the LCM value for that particular segment and we can use the same formula as above to combine the segments. Hence we can answer each query efficiently!Below is a solution for the same. " }, { "code": null, "e": 27706, "s": 27702, "text": "C++" }, { "code": null, "e": 27711, "s": 27706, "text": "Java" }, { "code": null, "e": 27719, "s": 27711, "text": "Python3" }, { "code": null, "e": 27722, "s": 27719, "text": "C#" }, { "code": null, "e": 27733, "s": 27722, "text": "Javascript" }, { "code": "// LCM of given range queries using Segment Tree#include <bits/stdc++.h>using namespace std; #define MAX 1000 // allocate space for treeint tree[4*MAX]; // declaring the array globallyint arr[MAX]; // Function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} //utility function to find lcmint lcm(int a, int b){ return a*b/gcd(a,b);} // Function to build the segment tree// Node starts beginning index of current subtree.// start and end are indexes in arr[] which is globalvoid build(int node, int start, int end){ // If there is only one element in current subarray if (start==end) { tree[node] = arr[start]; return; } int mid = (start+end)/2; // build left and right segments build(2*node, start, mid); build(2*node+1, mid+1, end); // build the parent int left_lcm = tree[2*node]; int right_lcm = tree[2*node+1]; tree[node] = lcm(left_lcm, right_lcm);} // Function to make queries for array range )l, r).// Node is index of root of current segment in segment// tree (Note that indexes in segment tree begin with 1// for simplicity).// start and end are indexes of subarray covered by root// of current segment.int query(int node, int start, int end, int l, int r){ // Completely outside the segment, returning // 1 will not affect the lcm; if (end<l || start>r) return 1; // completely inside the segment if (l<=start && r>=end) return tree[node]; // partially inside int mid = (start+end)/2; int left_lcm = query(2*node, start, mid, l, r); int right_lcm = query(2*node+1, mid+1, end, l, r); return lcm(left_lcm, right_lcm);} //driver function to check the above programint main(){ //initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) cout << query(1, 0, 10, 2, 5) << endl; // Print LCM of (5, 10) cout << query(1, 0, 10, 5, 10) << endl; // Print LCM of (0, 10) cout << query(1, 0, 10, 0, 10) << endl; return 0;}", "e": 29997, "s": 27733, "text": null }, { "code": "// LCM of given range queries// using Segment Tree class GFG{ static final int MAX = 1000; // allocate space for tree static int tree[] = new int[4 * MAX]; // declaring the array globally static int arr[] = new int[MAX]; // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } // utility function to find lcm static int lcm(int a, int b) { return a * b / gcd(a, b); } // Function to build the segment tree // Node starts beginning index // of current subtree. start and end // are indexes in arr[] which is global static void build(int node, int start, int end) { // If there is only one element // in current subarray if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; // build left and right segments build(2 * node, start, mid); build(2 * node + 1, mid + 1, end); // build the parent int left_lcm = tree[2 * node]; int right_lcm = tree[2 * node + 1]; tree[node] = lcm(left_lcm, right_lcm); } // Function to make queries for // array range )l, r). Node is index // of root of current segment in segment // tree (Note that indexes in segment // tree begin with 1 for simplicity). // start and end are indexes of subarray // covered by root of current segment. static int query(int node, int start, int end, int l, int r) { // Completely outside the segment, returning // 1 will not affect the lcm; if (end < l || start > r) { return 1; } // completely inside the segment if (l <= start && r >= end) { return tree[node]; } // partially inside int mid = (start + end) / 2; int left_lcm = query(2 * node, start, mid, l, r); int right_lcm = query(2 * node + 1, mid + 1, end, l, r); return lcm(left_lcm, right_lcm); } // Driver code public static void main(String[] args) { //initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) System.out.println(query(1, 0, 10, 2, 5)); // Print LCM of (5, 10) System.out.println(query(1, 0, 10, 5, 10)); // Print LCM of (0, 10) System.out.println(query(1, 0, 10, 0, 10)); }} // This code is contributed by 29AjayKumar", "e": 32835, "s": 29997, "text": null }, { "code": "# LCM of given range queries using Segment TreeMAX = 1000 # allocate space for treetree = [0] * (4 * MAX) # declaring the array globallyarr = [0] * MAX # Function to return gcd of a and bdef gcd(a: int, b: int): if a == 0: return b return gcd(b % a, a) # utility function to find lcmdef lcm(a: int, b: int): return (a * b) // gcd(a, b) # Function to build the segment tree# Node starts beginning index of current subtree.# start and end are indexes in arr[] which is globaldef build(node: int, start: int, end: int): # If there is only one element # in current subarray if start == end: tree[node] = arr[start] return mid = (start + end) // 2 # build left and right segments build(2 * node, start, mid) build(2 * node + 1, mid + 1, end) # build the parent left_lcm = tree[2 * node] right_lcm = tree[2 * node + 1] tree[node] = lcm(left_lcm, right_lcm) # Function to make queries for array range )l, r).# Node is index of root of current segment in segment# tree (Note that indexes in segment tree begin with 1# for simplicity).# start and end are indexes of subarray covered by root# of current segment.def query(node: int, start: int, end: int, l: int, r: int): # Completely outside the segment, # returning 1 will not affect the lcm; if end < l or start > r: return 1 # completely inside the segment if l <= start and r >= end: return tree[node] # partially inside mid = (start + end) // 2 left_lcm = query(2 * node, start, mid, l, r) right_lcm = query(2 * node + 1, mid + 1, end, l, r) return lcm(left_lcm, right_lcm) # Driver Codeif __name__ == \"__main__\": # initialize the array arr[0] = 5 arr[1] = 7 arr[2] = 5 arr[3] = 2 arr[4] = 10 arr[5] = 12 arr[6] = 11 arr[7] = 17 arr[8] = 14 arr[9] = 1 arr[10] = 44 # build the segment tree build(1, 0, 10) # Now we can answer each query efficiently # Print LCM of (2, 5) print(query(1, 0, 10, 2, 5)) # Print LCM of (5, 10) print(query(1, 0, 10, 5, 10)) # Print LCM of (0, 10) print(query(1, 0, 10, 0, 10)) # This code is contributed by# sanjeev2552", "e": 35045, "s": 32835, "text": null }, { "code": "// LCM of given range queries// using Segment Treeusing System;using System.Collections.Generic; class GFG{ static readonly int MAX = 1000; // allocate space for tree static int []tree = new int[4 * MAX]; // declaring the array globally static int []arr = new int[MAX]; // Function to return gcd of a and b static int gcd(int a, int b) { if (a == 0) { return b; } return gcd(b % a, a); } // utility function to find lcm static int lcm(int a, int b) { return a * b / gcd(a, b); } // Function to build the segment tree // Node starts beginning index // of current subtree. start and end // are indexes in []arr which is global static void build(int node, int start, int end) { // If there is only one element // in current subarray if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; // build left and right segments build(2 * node, start, mid); build(2 * node + 1, mid + 1, end); // build the parent int left_lcm = tree[2 * node]; int right_lcm = tree[2 * node + 1]; tree[node] = lcm(left_lcm, right_lcm); } // Function to make queries for // array range )l, r). Node is index // of root of current segment in segment // tree (Note that indexes in segment // tree begin with 1 for simplicity). // start and end are indexes of subarray // covered by root of current segment. static int query(int node, int start, int end, int l, int r) { // Completely outside the segment, // returning 1 will not affect the lcm; if (end < l || start > r) { return 1; } // completely inside the segment if (l <= start && r >= end) { return tree[node]; } // partially inside int mid = (start + end) / 2; int left_lcm = query(2 * node, start, mid, l, r); int right_lcm = query(2 * node + 1, mid + 1, end, l, r); return lcm(left_lcm, right_lcm); } // Driver code public static void Main(String[] args) { // initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) Console.WriteLine(query(1, 0, 10, 2, 5)); // Print LCM of (5, 10) Console.WriteLine(query(1, 0, 10, 5, 10)); // Print LCM of (0, 10) Console.WriteLine(query(1, 0, 10, 0, 10)); }} // This code is contributed by Rajput-Ji", "e": 37965, "s": 35045, "text": null }, { "code": "<script>// LCM of given range queries using Segment Treeconst MAX = 1000 // allocate space for treevar tree = new Array(4*MAX); // declaring the array globallyvar arr = new Array(MAX); // Function to return gcd of a and bfunction gcd(a, b){ if (a == 0) return b; return gcd(b%a, a);} //utility function to find lcmfunction lcm(a, b){ return Math.floor(a*b/gcd(a,b));} // Function to build the segment tree// Node starts beginning index of current subtree.// start and end are indexes in arr[] which is globalfunction build(node, start, end){ // If there is only one element in current subarray if (start==end) { tree[node] = arr[start]; return; } let mid = Math.floor((start+end)/2); // build left and right segments build(2*node, start, mid); build(2*node+1, mid+1, end); // build the parent let left_lcm = tree[2*node]; let right_lcm = tree[2*node+1]; tree[node] = lcm(left_lcm, right_lcm);} // Function to make queries for array range )l, r).// Node is index of root of current segment in segment// tree (Note that indexes in segment tree begin with 1// for simplicity).// start and end are indexes of subarray covered by root// of current segment.function query(node, start, end, l, r){ // Completely outside the segment, returning // 1 will not affect the lcm; if (end<l || start>r) return 1; // completely inside the segment if (l<=start && r>=end) return tree[node]; // partially inside let mid = Math.floor((start+end)/2); let left_lcm = query(2*node, start, mid, l, r); let right_lcm = query(2*node+1, mid+1, end, l, r); return lcm(left_lcm, right_lcm);} //driver function to check the above program //initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) document.write(query(1, 0, 10, 2, 5) +\"<br>\"); // Print LCM of (5, 10) document.write(query(1, 0, 10, 5, 10) + \"<br>\"); // Print LCM of (0, 10) document.write(query(1, 0, 10, 0, 10) + \"<br>\"); // This code is contributed by Manoj.</script>", "e": 40270, "s": 37965, "text": null }, { "code": null, "e": 40280, "s": 40270, "text": "Output: " }, { "code": null, "e": 40295, "s": 40280, "text": "60\n15708\n78540" }, { "code": null, "e": 40718, "s": 40295, "text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40730, "s": 40718, "text": "29AjayKumar" }, { "code": null, "e": 40742, "s": 40730, "text": "sanjeev2552" }, { "code": null, "e": 40752, "s": 40742, "text": "Rajput-Ji" }, { "code": null, "e": 40761, "s": 40752, "text": "mank1083" }, { "code": null, "e": 40781, "s": 40761, "text": "array-range-queries" }, { "code": null, "e": 40794, "s": 40781, "text": "Segment-Tree" }, { "code": null, "e": 40818, "s": 40794, "text": "Advanced Data Structure" }, { "code": null, "e": 40823, "s": 40818, "text": "Tree" }, { "code": null, "e": 40828, "s": 40823, "text": "Tree" }, { "code": null, "e": 40841, "s": 40828, "text": "Segment-Tree" }, { "code": null, "e": 40939, "s": 40841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40973, "s": 40939, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 41013, "s": 40973, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 41055, "s": 41013, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 41083, "s": 41055, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 41112, "s": 41083, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 41162, "s": 41112, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 41197, "s": 41162, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 41231, "s": 41197, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 41274, "s": 41231, "text": "Binary Tree | Set 3 (Types of Binary Tree)" } ]
How Base64 encoding and decoding is done in node.js ? - GeeksforGeeks
25 Jun, 2020 Base64 encoding and decoding can be done in Node.js using the Buffer object. Encoding the original string to base64: The Buffer class in Node.js can be used to convert a string to a series of bytes. This can be done using the Buffer.from() method that accepts the string to be converted and the current encoding of the string. This encoding can be specified as “utf8”. The converted bytes can then be returned as a base64 using the toString() method. This method accepts a parameter that specifies the encoding needed during conversion. In this case, “base64” is specified as the encoding to be used. Thus, this method converts any string to the base64 format. Syntax: // Create buffer object, specifying utf8 as encoding let bufferObj = Buffer.from(originalString, "utf8"); // Encode the Buffer as a base64 string let base64String = bufferObj.toString("base64"); Example: // The original utf8 stringlet originalString = "GeeksforGeeks"; // Create buffer object, specifying utf8 as encodinglet bufferObj = Buffer.from(originalString, "utf8"); // Encode the Buffer as a base64 stringlet base64String = bufferObj.toString("base64"); console.log("The encoded base64 string is:", base64String); Output: The encoded base64 string is: R2Vla3Nmb3JHZWVrcw== Decoding base64 to original string: The Buffer can also be used to convert the base64 string back to utf8 encoding. The Buffer.from() method is again used to convert the base64 string back to bytes, however, this time specifying the current encoding as “base64”. The converted bytes can then be returned as the original utf8 string using the toString() method. In this case, “utf8” is specified as the encoding to be used. Thus, this method converts the base64 to its original utf9 format. Syntax: // Create a buffer from the string let bufferObj = Buffer.from(base64string, "base64"); // Encode the Buffer as a utf8 string let decodedString = bufferObj.toString("utf8"); Example: // The base64 encoded input stringlet base64string = "R2Vla3Nmb3JHZWVrcw=="; // Create a buffer from the stringlet bufferObj = Buffer.from(base64string, "base64"); // Encode the Buffer as a utf8 stringlet decodedString = bufferObj.toString("utf8"); console.log("The decoded string:", decodedString); Output: The decoded string: GeeksforGeeks Node.js-Misc Picked Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Mongoose | findByIdAndUpdate() Function Express.js res.render() Function Express.js res.redirect() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26521, "s": 26493, "text": "\n25 Jun, 2020" }, { "code": null, "e": 26598, "s": 26521, "text": "Base64 encoding and decoding can be done in Node.js using the Buffer object." }, { "code": null, "e": 26890, "s": 26598, "text": "Encoding the original string to base64: The Buffer class in Node.js can be used to convert a string to a series of bytes. This can be done using the Buffer.from() method that accepts the string to be converted and the current encoding of the string. This encoding can be specified as “utf8”." }, { "code": null, "e": 27182, "s": 26890, "text": "The converted bytes can then be returned as a base64 using the toString() method. This method accepts a parameter that specifies the encoding needed during conversion. In this case, “base64” is specified as the encoding to be used. Thus, this method converts any string to the base64 format." }, { "code": null, "e": 27190, "s": 27182, "text": "Syntax:" }, { "code": null, "e": 27387, "s": 27190, "text": "// Create buffer object, specifying utf8 as encoding\nlet bufferObj = Buffer.from(originalString, \"utf8\");\n\n// Encode the Buffer as a base64 string\nlet base64String = bufferObj.toString(\"base64\");\n" }, { "code": null, "e": 27396, "s": 27387, "text": "Example:" }, { "code": "// The original utf8 stringlet originalString = \"GeeksforGeeks\"; // Create buffer object, specifying utf8 as encodinglet bufferObj = Buffer.from(originalString, \"utf8\"); // Encode the Buffer as a base64 stringlet base64String = bufferObj.toString(\"base64\"); console.log(\"The encoded base64 string is:\", base64String);", "e": 27717, "s": 27396, "text": null }, { "code": null, "e": 27725, "s": 27717, "text": "Output:" }, { "code": null, "e": 27776, "s": 27725, "text": "The encoded base64 string is: R2Vla3Nmb3JHZWVrcw==" }, { "code": null, "e": 28039, "s": 27776, "text": "Decoding base64 to original string: The Buffer can also be used to convert the base64 string back to utf8 encoding. The Buffer.from() method is again used to convert the base64 string back to bytes, however, this time specifying the current encoding as “base64”." }, { "code": null, "e": 28266, "s": 28039, "text": "The converted bytes can then be returned as the original utf8 string using the toString() method. In this case, “utf8” is specified as the encoding to be used. Thus, this method converts the base64 to its original utf9 format." }, { "code": null, "e": 28274, "s": 28266, "text": "Syntax:" }, { "code": null, "e": 28449, "s": 28274, "text": "// Create a buffer from the string\nlet bufferObj = Buffer.from(base64string, \"base64\");\n\n// Encode the Buffer as a utf8 string\nlet decodedString = bufferObj.toString(\"utf8\");" }, { "code": null, "e": 28458, "s": 28449, "text": "Example:" }, { "code": "// The base64 encoded input stringlet base64string = \"R2Vla3Nmb3JHZWVrcw==\"; // Create a buffer from the stringlet bufferObj = Buffer.from(base64string, \"base64\"); // Encode the Buffer as a utf8 stringlet decodedString = bufferObj.toString(\"utf8\"); console.log(\"The decoded string:\", decodedString);", "e": 28761, "s": 28458, "text": null }, { "code": null, "e": 28769, "s": 28761, "text": "Output:" }, { "code": null, "e": 28803, "s": 28769, "text": "The decoded string: GeeksforGeeks" }, { "code": null, "e": 28816, "s": 28803, "text": "Node.js-Misc" }, { "code": null, "e": 28823, "s": 28816, "text": "Picked" }, { "code": null, "e": 28831, "s": 28823, "text": "Node.js" }, { "code": null, "e": 28848, "s": 28831, "text": "Web Technologies" }, { "code": null, "e": 28875, "s": 28848, "text": "Web technologies Questions" }, { "code": null, "e": 28973, "s": 28875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29027, "s": 28973, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 29064, "s": 29027, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29104, "s": 29064, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 29137, "s": 29104, "text": "Express.js res.render() Function" }, { "code": null, "e": 29172, "s": 29137, "text": "Express.js res.redirect() Function" }, { "code": null, "e": 29212, "s": 29172, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29257, "s": 29212, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29300, "s": 29257, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29362, "s": 29300, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to Import a CSV File into R ? - GeeksforGeeks
23 May, 2021 A CSV file is used to store contents in a tabular-like format, which is organized in the form of rows and columns. The column values in each row are separated by a delimiter string. The CSV files can be loaded into the working space and worked using both in-built methods and external package imports. Method 1: Using read.csv() method The read.csv() method in base R is used to load a .csv file into the present script and work with it. The contents of the csv can be stored into the variable and further manipulated. Multiple files can also be accessed in different variables. The output is returned to the form of a data frame, where row numbers are assigned integers beginning with 1. Syntax: read.csv(path, header = TRUE, sep = “,”) Arguments : path : The path of the file to be imported header : By default : TRUE . Indicator of whether to import column headings. sep = “,” : The separator for the values in each row. Code: R # specifying the pathpath <- "/Users/mallikagupta/Desktop/gfg.csv" # reading contents of csv filecontent <- read.csv(path)# contents of the csv fileprint (content) Output: ID Name Post Age 1 5 H CA 67 2 6 K SDE 39 3 7 Z Admin 28 In case, the header is set to FALSE, the column names are ignored, and default variables names are displayed for each column beginning from V1. R path <- "/Users/mallikagupta/Desktop/gfg.csv" # reading contents of csv filecontent <- read.csv(path, header = FALSE) # contents of the csv fileprint (content) Output: V1 V2 V3 V4 1 5 H CA 67 2 6 K SDE 39 3 7 Z Admin 28 Method 2: Using read_csv() method The “readr” package in R is used to read large flat files into the working space with increase speed and efficiency. install.packages("readr") The read_csv() method reads a csv file reading one line at a time. The data using this method is read in the form of a tibble, of the same dimensions as of the table stored in the .csv file. Only ten rows of the tibble are displayed on the screen and rest are available after expanding, which increases the readability of the large files. This method is more efficient since it returns more information about the column types. It also displays progress tracker for the percentage of file read into the system currently if the progress argument is enabled, therefore being more robust. This method is also faster in comparison to the base R read.csv() method. Syntax: read_csv (file-path , col_names , n_max , col_types , progress ) Arguments : file-path : The path of the file to be imported col_names : By default, it is TRUE. If FALSE, the column names are ignored. n_max : The maximum number of rows to read. col_types : If any column succumbs to NULL, then the col_types can be specified in a compact string format. progress : A progress meter to analyse the percentage of file read into the system Code: R library("readr") # specifying the pathpath <- "/Users/mallikagupta/Desktop/gfg.csv" # reading contents of csv filecontent <- read_csv(path, col_names = TRUE) # contents of the csv fileprint (content) Output: Picked R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R Plot mean and standard deviation using ggplot2 in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 May, 2021" }, { "code": null, "e": 26790, "s": 26487, "text": "A CSV file is used to store contents in a tabular-like format, which is organized in the form of rows and columns. The column values in each row are separated by a delimiter string. The CSV files can be loaded into the working space and worked using both in-built methods and external package imports. " }, { "code": null, "e": 26824, "s": 26790, "text": "Method 1: Using read.csv() method" }, { "code": null, "e": 27178, "s": 26824, "text": "The read.csv() method in base R is used to load a .csv file into the present script and work with it. The contents of the csv can be stored into the variable and further manipulated. Multiple files can also be accessed in different variables. The output is returned to the form of a data frame, where row numbers are assigned integers beginning with 1. " }, { "code": null, "e": 27227, "s": 27178, "text": "Syntax: read.csv(path, header = TRUE, sep = “,”)" }, { "code": null, "e": 27240, "s": 27227, "text": "Arguments : " }, { "code": null, "e": 27283, "s": 27240, "text": "path : The path of the file to be imported" }, { "code": null, "e": 27360, "s": 27283, "text": "header : By default : TRUE . Indicator of whether to import column headings." }, { "code": null, "e": 27415, "s": 27360, "text": "sep = “,” : The separator for the values in each row." }, { "code": null, "e": 27421, "s": 27415, "text": "Code:" }, { "code": null, "e": 27423, "s": 27421, "text": "R" }, { "code": "# specifying the pathpath <- \"/Users/mallikagupta/Desktop/gfg.csv\" # reading contents of csv filecontent <- read.csv(path)# contents of the csv fileprint (content)", "e": 27588, "s": 27423, "text": null }, { "code": null, "e": 27596, "s": 27588, "text": "Output:" }, { "code": null, "e": 27687, "s": 27596, "text": " ID Name Post Age \n1 5 H CA 67 \n2 6 K SDE 39 \n3 7 Z Admin 28" }, { "code": null, "e": 27832, "s": 27687, "text": "In case, the header is set to FALSE, the column names are ignored, and default variables names are displayed for each column beginning from V1. " }, { "code": null, "e": 27834, "s": 27832, "text": "R" }, { "code": "path <- \"/Users/mallikagupta/Desktop/gfg.csv\" # reading contents of csv filecontent <- read.csv(path, header = FALSE) # contents of the csv fileprint (content)", "e": 27996, "s": 27834, "text": null }, { "code": null, "e": 28004, "s": 27996, "text": "Output:" }, { "code": null, "e": 28092, "s": 28004, "text": " V1 V2 V3 V4\n1 5 H CA 67\n2 6 K SDE 39\n3 7 Z Admin 28" }, { "code": null, "e": 28126, "s": 28092, "text": "Method 2: Using read_csv() method" }, { "code": null, "e": 28244, "s": 28126, "text": "The “readr” package in R is used to read large flat files into the working space with increase speed and efficiency. " }, { "code": null, "e": 28270, "s": 28244, "text": "install.packages(\"readr\")" }, { "code": null, "e": 28930, "s": 28270, "text": "The read_csv() method reads a csv file reading one line at a time. The data using this method is read in the form of a tibble, of the same dimensions as of the table stored in the .csv file. Only ten rows of the tibble are displayed on the screen and rest are available after expanding, which increases the readability of the large files. This method is more efficient since it returns more information about the column types. It also displays progress tracker for the percentage of file read into the system currently if the progress argument is enabled, therefore being more robust. This method is also faster in comparison to the base R read.csv() method. " }, { "code": null, "e": 29003, "s": 28930, "text": "Syntax: read_csv (file-path , col_names , n_max , col_types , progress )" }, { "code": null, "e": 29016, "s": 29003, "text": "Arguments : " }, { "code": null, "e": 29064, "s": 29016, "text": "file-path : The path of the file to be imported" }, { "code": null, "e": 29140, "s": 29064, "text": "col_names : By default, it is TRUE. If FALSE, the column names are ignored." }, { "code": null, "e": 29184, "s": 29140, "text": "n_max : The maximum number of rows to read." }, { "code": null, "e": 29292, "s": 29184, "text": "col_types : If any column succumbs to NULL, then the col_types can be specified in a compact string format." }, { "code": null, "e": 29375, "s": 29292, "text": "progress : A progress meter to analyse the percentage of file read into the system" }, { "code": null, "e": 29381, "s": 29375, "text": "Code:" }, { "code": null, "e": 29383, "s": 29381, "text": "R" }, { "code": "library(\"readr\") # specifying the pathpath <- \"/Users/mallikagupta/Desktop/gfg.csv\" # reading contents of csv filecontent <- read_csv(path, col_names = TRUE) # contents of the csv fileprint (content)", "e": 29586, "s": 29383, "text": null }, { "code": null, "e": 29594, "s": 29586, "text": "Output:" }, { "code": null, "e": 29601, "s": 29594, "text": "Picked" }, { "code": null, "e": 29607, "s": 29601, "text": "R-CSV" }, { "code": null, "e": 29618, "s": 29607, "text": "R Language" }, { "code": null, "e": 29716, "s": 29618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29768, "s": 29716, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29803, "s": 29768, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29841, "s": 29803, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29899, "s": 29841, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29942, "s": 29899, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29991, "s": 29942, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30028, "s": 29991, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30045, "s": 30028, "text": "R - if statement" }, { "code": null, "e": 30071, "s": 30045, "text": "Time Series Analysis in R" } ]
How to get an element by its href attribute ? - GeeksforGeeks
20 Sep, 2019 The task is to select the <a> element by its href attribute. Few of the techniques are discussed below. Here we are going to use JQuery to solve the problem.Approach 1: Use JQuery selector $(‘a[href=link_to_site]’). Example 1: This example using the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> Get an element by its href attribute. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 id = "h1" style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <a href = "https://www.geeksforgeeks.org">GeeksforGeeks </a> <br> <br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to select the element by HREF attribute."; function gfg_Run() { el_down.innerHTML = $('a[href="https://www.geeksforgeeks.org"]').text(); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Use JQuery selector $(‘a[href*=part_of_link]’). it will select the element if any part of the attribute matches with value. Example 2: This example using the approach discussed above. <!DOCTYPE HTML> <html> <head> <title> Get an element by its href attribute. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 id = "h1" style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <a href = "https://www.geeksforgeeks.org"> GeeksforGeeks </a> <br> <br> <button onclick = "gfg_Run()"> Click here </button> <p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to select the element by HREF attribute."; function gfg_Run() { el_down.innerHTML = $('a[href*="geeks.org"]').text(); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26399, "s": 26371, "text": "\n20 Sep, 2019" }, { "code": null, "e": 26568, "s": 26399, "text": "The task is to select the <a> element by its href attribute. Few of the techniques are discussed below. Here we are going to use JQuery to solve the problem.Approach 1:" }, { "code": null, "e": 26615, "s": 26568, "text": "Use JQuery selector $(‘a[href=link_to_site]’)." }, { "code": null, "e": 26675, "s": 26615, "text": "Example 1: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Get an element by its href attribute. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 id = \"h1\" style = \"color:green;\" > GeeksforGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <a href = \"https://www.geeksforgeeks.org\">GeeksforGeeks </a> <br> <br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to select the element by HREF attribute.\"; function gfg_Run() { el_down.innerHTML = $('a[href=\"https://www.geeksforgeeks.org\"]').text(); } </script> </body> </html>", "e": 27866, "s": 26675, "text": null }, { "code": null, "e": 27874, "s": 27866, "text": "Output:" }, { "code": null, "e": 27905, "s": 27874, "text": "Before clicking on the button:" }, { "code": null, "e": 27935, "s": 27905, "text": "After clicking on the button:" }, { "code": null, "e": 27947, "s": 27935, "text": "Approach 2:" }, { "code": null, "e": 28071, "s": 27947, "text": "Use JQuery selector $(‘a[href*=part_of_link]’). it will select the element if any part of the attribute matches with value." }, { "code": null, "e": 28131, "s": 28071, "text": "Example 2: This example using the approach discussed above." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Get an element by its href attribute. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 id = \"h1\" style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <a href = \"https://www.geeksforgeeks.org\"> GeeksforGeeks </a> <br> <br> <button onclick = \"gfg_Run()\"> Click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to select the element by HREF attribute.\"; function gfg_Run() { el_down.innerHTML = $('a[href*=\"geeks.org\"]').text(); } </script> </body> </html>", "e": 29285, "s": 28131, "text": null }, { "code": null, "e": 29293, "s": 29285, "text": "Output:" }, { "code": null, "e": 29324, "s": 29293, "text": "Before clicking on the button:" }, { "code": null, "e": 29354, "s": 29324, "text": "After clicking on the button:" }, { "code": null, "e": 29370, "s": 29354, "text": "JavaScript-Misc" }, { "code": null, "e": 29381, "s": 29370, "text": "JavaScript" }, { "code": null, "e": 29398, "s": 29381, "text": "Web Technologies" }, { "code": null, "e": 29425, "s": 29398, "text": "Web technologies Questions" }, { "code": null, "e": 29523, "s": 29425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29563, "s": 29523, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29608, "s": 29563, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29669, "s": 29608, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29741, "s": 29669, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29787, "s": 29741, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29827, "s": 29787, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29860, "s": 29827, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29905, "s": 29860, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29948, "s": 29905, "text": "How to fetch data from an API in ReactJS ?" } ]
How to make a vertical wavy text line using HTML and CSS ? - GeeksforGeeks
09 Sep, 2020 In this article, a wavy animated text is implemented using HTML and CSS. It is one of the simplest CSS effects. For a beginner, it is one of the best examples to learn the concept of CSS pseudo-elements. Approach: The basic idea of getting wavy texts is performed by using the combination of some CSS attributes. The main “body” part is created by using <span> tag inside <body> tag. CSS code is used to create wavy texts of the “body” part of the HTML structure. HTML code: The following code snippet demonstrates the design of the text used for wavy effect by using HTML tags in the web page. <div class="wavy"> <span style="--i:1">G</span> <span style="--i:2">E</span> <span style="--i:3">E</span> <span style="--i:4">K</span> <span style="--i:5">S</span> <span style="--i:6"> </span> <span style="--i:7">F</span> <span style="--i:8">O</span> <span style="--i:9">R</span> <span style="--i:10"> </span> <span style="--i:11">G</span> <span style="--i:12">E</span> <span style="--i:13">E</span> <span style="--i:14">K</span> <span style="--i:15">S</span> <span style="--i:16">.</span> <span style="--i:17">.</span> <span style="--i:18">.</span> <span style="--i:19">.</span> <span style="--i:20">.</span></div> Final code: This example displaying the complete code to make a vertical wavy text line using HTML and CSS. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <style type="text/css"> body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: rgb(6, 75, 21); } .wavy { position: relative; } .wavy span { position: relative; display: inline-block; color: #fff; font-size: 2em; text-transform: uppercase; animation: animate 2s ease-in-out infinite; animation-delay: calc(0.1s * var(--i)); } @keyframes animate { 0% { transform: translateY(0px); } 20% { transform: translateY(-20px); } 40%, 100% { transform: translateY(0px); } } </style></head> <body> <div class="wavy"> <span style="--i:1">G</span> <span style="--i:2">E</span> <span style="--i:3">E</span> <span style="--i:4">K</span> <span style="--i:5">S</span> <span style="--i:6"> </span> <span style="--i:7">F</span> <span style="--i:8">O</span> <span style="--i:9">R</span> <span style="--i:10"> </span> <span style="--i:11">G</span> <span style="--i:12">E</span> <span style="--i:13">E</span> <span style="--i:14">K</span> <span style="--i:15">S</span> <span style="--i:16">.</span> <span style="--i:17">.</span> <span style="--i:18">.</span> <span style="--i:19">.</span> <span style="--i:20">.</span> </div></body> </html> Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26645, "s": 26617, "text": "\n09 Sep, 2020" }, { "code": null, "e": 26849, "s": 26645, "text": "In this article, a wavy animated text is implemented using HTML and CSS. It is one of the simplest CSS effects. For a beginner, it is one of the best examples to learn the concept of CSS pseudo-elements." }, { "code": null, "e": 27109, "s": 26849, "text": "Approach: The basic idea of getting wavy texts is performed by using the combination of some CSS attributes. The main “body” part is created by using <span> tag inside <body> tag. CSS code is used to create wavy texts of the “body” part of the HTML structure." }, { "code": null, "e": 27240, "s": 27109, "text": "HTML code: The following code snippet demonstrates the design of the text used for wavy effect by using HTML tags in the web page." }, { "code": "<div class=\"wavy\"> <span style=\"--i:1\">G</span> <span style=\"--i:2\">E</span> <span style=\"--i:3\">E</span> <span style=\"--i:4\">K</span> <span style=\"--i:5\">S</span> <span style=\"--i:6\"> </span> <span style=\"--i:7\">F</span> <span style=\"--i:8\">O</span> <span style=\"--i:9\">R</span> <span style=\"--i:10\"> </span> <span style=\"--i:11\">G</span> <span style=\"--i:12\">E</span> <span style=\"--i:13\">E</span> <span style=\"--i:14\">K</span> <span style=\"--i:15\">S</span> <span style=\"--i:16\">.</span> <span style=\"--i:17\">.</span> <span style=\"--i:18\">.</span> <span style=\"--i:19\">.</span> <span style=\"--i:20\">.</span></div>", "e": 27916, "s": 27240, "text": null }, { "code": null, "e": 28024, "s": 27916, "text": "Final code: This example displaying the complete code to make a vertical wavy text line using HTML and CSS." }, { "code": null, "e": 28029, "s": 28024, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <style type=\"text/css\"> body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: rgb(6, 75, 21); } .wavy { position: relative; } .wavy span { position: relative; display: inline-block; color: #fff; font-size: 2em; text-transform: uppercase; animation: animate 2s ease-in-out infinite; animation-delay: calc(0.1s * var(--i)); } @keyframes animate { 0% { transform: translateY(0px); } 20% { transform: translateY(-20px); } 40%, 100% { transform: translateY(0px); } } </style></head> <body> <div class=\"wavy\"> <span style=\"--i:1\">G</span> <span style=\"--i:2\">E</span> <span style=\"--i:3\">E</span> <span style=\"--i:4\">K</span> <span style=\"--i:5\">S</span> <span style=\"--i:6\"> </span> <span style=\"--i:7\">F</span> <span style=\"--i:8\">O</span> <span style=\"--i:9\">R</span> <span style=\"--i:10\"> </span> <span style=\"--i:11\">G</span> <span style=\"--i:12\">E</span> <span style=\"--i:13\">E</span> <span style=\"--i:14\">K</span> <span style=\"--i:15\">S</span> <span style=\"--i:16\">.</span> <span style=\"--i:17\">.</span> <span style=\"--i:18\">.</span> <span style=\"--i:19\">.</span> <span style=\"--i:20\">.</span> </div></body> </html>", "e": 29738, "s": 28029, "text": null }, { "code": null, "e": 29875, "s": 29738, "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": 29884, "s": 29875, "text": "CSS-Misc" }, { "code": null, "e": 29894, "s": 29884, "text": "HTML-Misc" }, { "code": null, "e": 29898, "s": 29894, "text": "CSS" }, { "code": null, "e": 29903, "s": 29898, "text": "HTML" }, { "code": null, "e": 29920, "s": 29903, "text": "Web Technologies" }, { "code": null, "e": 29947, "s": 29920, "text": "Web technologies Questions" }, { "code": null, "e": 29952, "s": 29947, "text": "HTML" }, { "code": null, "e": 30050, "s": 29952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30089, "s": 30050, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30126, "s": 30089, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30155, "s": 30126, "text": "Form validation using jQuery" }, { "code": null, "e": 30197, "s": 30155, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 30232, "s": 30197, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 30292, "s": 30232, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30345, "s": 30292, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30406, "s": 30345, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30430, "s": 30406, "text": "REST API (Introduction)" } ]
Python program to convert Set into Tuple and Tuple into Set - GeeksforGeeks
26 Nov, 2020 Let’s see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value. set(): set method is to convert other type values to set this method is also accepted other type values as an argument and return a set type value. type(): type method helps the programmer to check the data type of value. This method accepts a value as an argument and it returns type of the value. Example: Input: {'a', 'b', 'c', 'd', 'e'} Output: ('a', 'c', 'b', 'e', 'd') Explanation: converting Set to tuple Input: ('x', 'y', 'z') Output: {'z', 'x', 'y'} Explanation: Converting tuple to set Example 1: convert set into tuple. Python # program to convert set to tuple# create sets = {'a', 'b', 'c', 'd', 'e'} # print setprint(type(s), " ", s) # call tuple() method # this method convert set to tuplet = tuple(s) # print tupleprint(type(t), " ", t) Output: <class 'set'> {'a', 'c', 'b', 'e', 'd'} <class 'tuple'> ('a', 'c', 'b', 'e', 'd') Example 2: tuple into the set. Python #program to convert tuple into set # create tuplet = ('x', 'y', 'z') # print tupleprint(type(t), " ", t) # call set() methods = set(t) # print setprint(type(s), " ", s) Output: <class 'tuple'> ('x', 'y', 'z') <class 'set'> {'z', 'x', 'y'} Python set-programs Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25423, "s": 25395, "text": "\n26 Nov, 2020" }, { "code": null, "e": 25568, "s": 25423, "text": "Let’s see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type()." }, { "code": null, "e": 25708, "s": 25568, "text": "tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value." }, { "code": null, "e": 25856, "s": 25708, "text": "set(): set method is to convert other type values to set this method is also accepted other type values as an argument and return a set type value." }, { "code": null, "e": 26007, "s": 25856, "text": "type(): type method helps the programmer to check the data type of value. This method accepts a value as an argument and it returns type of the value." }, { "code": null, "e": 26016, "s": 26007, "text": "Example:" }, { "code": null, "e": 26206, "s": 26016, "text": "Input: {'a', 'b', 'c', 'd', 'e'}\nOutput: ('a', 'c', 'b', 'e', 'd')\nExplanation: converting Set to tuple\n\nInput: ('x', 'y', 'z')\nOutput: {'z', 'x', 'y'}\nExplanation: Converting tuple to set\n" }, { "code": null, "e": 26241, "s": 26206, "text": "Example 1: convert set into tuple." }, { "code": null, "e": 26248, "s": 26241, "text": "Python" }, { "code": "# program to convert set to tuple# create sets = {'a', 'b', 'c', 'd', 'e'} # print setprint(type(s), \" \", s) # call tuple() method # this method convert set to tuplet = tuple(s) # print tupleprint(type(t), \" \", t)", "e": 26467, "s": 26248, "text": null }, { "code": null, "e": 26475, "s": 26467, "text": "Output:" }, { "code": null, "e": 26562, "s": 26475, "text": "<class 'set'> {'a', 'c', 'b', 'e', 'd'}\n<class 'tuple'> ('a', 'c', 'b', 'e', 'd')\n" }, { "code": null, "e": 26593, "s": 26562, "text": "Example 2: tuple into the set." }, { "code": null, "e": 26600, "s": 26593, "text": "Python" }, { "code": "#program to convert tuple into set # create tuplet = ('x', 'y', 'z') # print tupleprint(type(t), \" \", t) # call set() methods = set(t) # print setprint(type(s), \" \", s)", "e": 26775, "s": 26600, "text": null }, { "code": null, "e": 26783, "s": 26775, "text": "Output:" }, { "code": null, "e": 26852, "s": 26783, "text": "<class 'tuple'> ('x', 'y', 'z')\n<class 'set'> {'z', 'x', 'y'}\n" }, { "code": null, "e": 26872, "s": 26852, "text": "Python set-programs" }, { "code": null, "e": 26894, "s": 26872, "text": "Python tuple-programs" }, { "code": null, "e": 26901, "s": 26894, "text": "Python" }, { "code": null, "e": 26917, "s": 26901, "text": "Python Programs" }, { "code": null, "e": 27015, "s": 26917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27050, "s": 27015, "text": "Read a file line by line in Python" }, { "code": null, "e": 27082, "s": 27050, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27104, "s": 27082, "text": "Enumerate() in Python" }, { "code": null, "e": 27146, "s": 27104, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27176, "s": 27146, "text": "Iterate over a list in Python" }, { "code": null, "e": 27219, "s": 27176, "text": "Python program to convert a list to string" }, { "code": null, "e": 27241, "s": 27219, "text": "Defaultdict in Python" }, { "code": null, "e": 27280, "s": 27241, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27326, "s": 27280, "text": "Python | Split string into list of characters" } ]
Java Program to Find the Volume and Surface Area of Sphere
26 Nov, 2020 A sphere is a geometrical object in 3D space that is the surface of a ball. The sphere is defined mathematically as the set of points that are all at the same distance of radius from a given point in a 3D space. Example: Input: radius = 5 Output: Surface Area ≈ 314.16 Volume ≈ 523.6 Input : radius = 3 Output: Surface Area ≈ 113.1 Volume ≈ 113.1 Surface area of a sphere = 4*3.14*(r*r) Volume of a sphere = (4/3)*3.14*(r*r*r) Algorithm Initializing value of r as 5.0, surface area as 0.0,volume as 0.0Calculating surface area and volume of a sphere using the below formulasSurface area=4*3.14(r*r)Volume=(4/3)3.14(r*r*r)Display surface area and volume Initializing value of r as 5.0, surface area as 0.0,volume as 0.0 Calculating surface area and volume of a sphere using the below formulas Surface area=4*3.14(r*r) Volume=(4/3)3.14(r*r*r) Display surface area and volume Implementation: Java // Java Program to Find the Volume and Surface Area of// Sphereclass surfaceareaandvolume { public static void main(String[] args) { double r = 5.0, surfacearea = 0.0, volume = 0.0; surfacearea = 4 * 3.14 * (r * r); volume = ((double)4 / 3) * 3.14 * (r * r * r); System.out.println("surfacearea of sphere =" + surfacearea); System.out.println("volume of sphere =" + volume); }} surfacearea of sphere =314.0 volume of sphere =523.3333333333334 Time Complexity: O(1) Space Complexity: O(1) Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 240, "s": 28, "text": "A sphere is a geometrical object in 3D space that is the surface of a ball. The sphere is defined mathematically as the set of points that are all at the same distance of radius from a given point in a 3D space." }, { "code": null, "e": 249, "s": 240, "text": "Example:" }, { "code": null, "e": 411, "s": 249, "text": "Input: radius = 5\nOutput: Surface Area ≈ 314.16\n Volume ≈ 523.6\n\nInput : radius = 3\nOutput: Surface Area ≈ 113.1\n Volume ≈ 113.1" }, { "code": null, "e": 452, "s": 411, "text": "Surface area of a sphere = 4*3.14*(r*r)" }, { "code": null, "e": 492, "s": 452, "text": "Volume of a sphere = (4/3)*3.14*(r*r*r)" }, { "code": null, "e": 502, "s": 492, "text": "Algorithm" }, { "code": null, "e": 718, "s": 502, "text": "Initializing value of r as 5.0, surface area as 0.0,volume as 0.0Calculating surface area and volume of a sphere using the below formulasSurface area=4*3.14(r*r)Volume=(4/3)3.14(r*r*r)Display surface area and volume" }, { "code": null, "e": 784, "s": 718, "text": "Initializing value of r as 5.0, surface area as 0.0,volume as 0.0" }, { "code": null, "e": 857, "s": 784, "text": "Calculating surface area and volume of a sphere using the below formulas" }, { "code": null, "e": 882, "s": 857, "text": "Surface area=4*3.14(r*r)" }, { "code": null, "e": 906, "s": 882, "text": "Volume=(4/3)3.14(r*r*r)" }, { "code": null, "e": 938, "s": 906, "text": "Display surface area and volume" }, { "code": null, "e": 954, "s": 938, "text": "Implementation:" }, { "code": null, "e": 959, "s": 954, "text": "Java" }, { "code": "// Java Program to Find the Volume and Surface Area of// Sphereclass surfaceareaandvolume { public static void main(String[] args) { double r = 5.0, surfacearea = 0.0, volume = 0.0; surfacearea = 4 * 3.14 * (r * r); volume = ((double)4 / 3) * 3.14 * (r * r * r); System.out.println(\"surfacearea of sphere =\" + surfacearea); System.out.println(\"volume of sphere =\" + volume); }}", "e": 1423, "s": 959, "text": null }, { "code": null, "e": 1488, "s": 1423, "text": "surfacearea of sphere =314.0\nvolume of sphere =523.3333333333334" }, { "code": null, "e": 1510, "s": 1488, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1533, "s": 1510, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1540, "s": 1533, "text": "Picked" }, { "code": null, "e": 1564, "s": 1540, "text": "Technical Scripter 2020" }, { "code": null, "e": 1569, "s": 1564, "text": "Java" }, { "code": null, "e": 1583, "s": 1569, "text": "Java Programs" }, { "code": null, "e": 1602, "s": 1583, "text": "Technical Scripter" }, { "code": null, "e": 1607, "s": 1602, "text": "Java" } ]
LINQ | Element Operator | ElementAt
24 May, 2019 The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the principal is the only result that comes from the collection. The LINQ Standard Query Operator supports 8 types of element operators: ElementAtElementAtOrDefaultFirstFirstOrDefaultLastLastOrDefaultSingleSingleOrDefault ElementAt ElementAtOrDefault First FirstOrDefault Last LastOrDefault Single SingleOrDefault The ElementAt operator is used to return an element from the particular index from the given collection or sequence. Here the specified index is zero-based index. Suppose an array contains 3 elements, i.e, 1, 2, 3 and we want to print the value at index 1, so we use an ElementAt method because it will return the element present at index 1, i.e, 2. Important Points: It does not support query syntax in C# and VB.Net languages. It support method syntax in both C# and VB.Net languages. It present in both the Queryable and Enumerable class. If the given index is out of range, then this method will throw an ArgumentOutOfRangeException. Example 1: // C# program to illustrate the// use of ElementAt operatorusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source string[] sequence = {"Dog", "Cat", "Cow", "Goat", "Parrot"}; // Display the sequences Console.WriteLine("Sequence is: "); foreach(var s in sequence) { Console.WriteLine(s); } // Get element at index 3 // Using ElementAt function var result = sequence.ElementAt(3); Console.WriteLine("Element is: {0}", result); }} Sequence is: Dog Cat Cow Goat Parrot Element is: Goat Example 2: // C# program to find the // ID of the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000}, }; // Query to find the ID of // the employee at index 1 // Using ElementAt method var res = emp.Select(e => e.emp_id).ElementAt(1); Console.WriteLine("Employee ID: {0}", res); }} Employee ID: 210 CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2019" }, { "code": null, "e": 382, "s": 28, "text": "The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the principal is the only result that comes from the collection." }, { "code": null, "e": 454, "s": 382, "text": "The LINQ Standard Query Operator supports 8 types of element operators:" }, { "code": null, "e": 539, "s": 454, "text": "ElementAtElementAtOrDefaultFirstFirstOrDefaultLastLastOrDefaultSingleSingleOrDefault" }, { "code": null, "e": 549, "s": 539, "text": "ElementAt" }, { "code": null, "e": 568, "s": 549, "text": "ElementAtOrDefault" }, { "code": null, "e": 574, "s": 568, "text": "First" }, { "code": null, "e": 589, "s": 574, "text": "FirstOrDefault" }, { "code": null, "e": 594, "s": 589, "text": "Last" }, { "code": null, "e": 608, "s": 594, "text": "LastOrDefault" }, { "code": null, "e": 615, "s": 608, "text": "Single" }, { "code": null, "e": 631, "s": 615, "text": "SingleOrDefault" }, { "code": null, "e": 981, "s": 631, "text": "The ElementAt operator is used to return an element from the particular index from the given collection or sequence. Here the specified index is zero-based index. Suppose an array contains 3 elements, i.e, 1, 2, 3 and we want to print the value at index 1, so we use an ElementAt method because it will return the element present at index 1, i.e, 2." }, { "code": null, "e": 999, "s": 981, "text": "Important Points:" }, { "code": null, "e": 1060, "s": 999, "text": "It does not support query syntax in C# and VB.Net languages." }, { "code": null, "e": 1118, "s": 1060, "text": "It support method syntax in both C# and VB.Net languages." }, { "code": null, "e": 1173, "s": 1118, "text": "It present in both the Queryable and Enumerable class." }, { "code": null, "e": 1269, "s": 1173, "text": "If the given index is out of range, then this method will throw an ArgumentOutOfRangeException." }, { "code": null, "e": 1280, "s": 1269, "text": "Example 1:" }, { "code": "// C# program to illustrate the// use of ElementAt operatorusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source string[] sequence = {\"Dog\", \"Cat\", \"Cow\", \"Goat\", \"Parrot\"}; // Display the sequences Console.WriteLine(\"Sequence is: \"); foreach(var s in sequence) { Console.WriteLine(s); } // Get element at index 3 // Using ElementAt function var result = sequence.ElementAt(3); Console.WriteLine(\"Element is: {0}\", result); }}", "e": 1898, "s": 1280, "text": null }, { "code": null, "e": 1954, "s": 1898, "text": "Sequence is: \nDog\nCat\nCow\nGoat\nParrot\nElement is: Goat\n" }, { "code": null, "e": 1965, "s": 1954, "text": "Example 2:" }, { "code": "// C# program to find the // ID of the employeeusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000}, }; // Query to find the ID of // the employee at index 1 // Using ElementAt method var res = emp.Select(e => e.emp_id).ElementAt(1); Console.WriteLine(\"Employee ID: {0}\", res); }}", "e": 3817, "s": 1965, "text": null }, { "code": null, "e": 3835, "s": 3817, "text": "Employee ID: 210\n" }, { "code": null, "e": 3847, "s": 3835, "text": "CSharp LINQ" }, { "code": null, "e": 3850, "s": 3847, "text": "C#" } ]
Python – Send email to a list of emails from a spreadsheet
10 May, 2020 Nowadays working with Google forms is quite popular. It is used to mass gather information easily. Email addresses are one of the most common piece of information asked. It is stored in a spreadsheet. In this article we shall see how to send an email to all the email addresses present in a spreadsheet. Prerequisite knowledge: Loading Excel spreadsheet as pandas DataFrameSend mail from your Gmail account using Python Loading Excel spreadsheet as pandas DataFrame Send mail from your Gmail account using Python Procedure: Step 1: Read the spreadsheet using the pandas library. The structure of the spreadsheet used here is : Step 2: Extablish connection with your gmail account using smtplib library. Step 3: Extract the names and email addresses from the spreadsheet. Step 4: Run a loop and for every record send an email. Step 5: Close the smtp server. The Python implementation is: # Python code to send email to a list of# emails from a spreadsheet # import the required librariesimport pandas as pdimport smtplib # change these as per useyour_email = "XYZ@gmail.com"your_password = "XYZ" # establishing connection with gmailserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)server.ehlo()server.login(your_email, your_password) # reading the spreadsheetemail_list = pd.read_excel('C:/Users/user/Desktop/gfg.xlsx') # getting the names and the emailsnames = email_list['NAME']emails = email_list['EMAIL'] # iterate through the recordsfor i in range(len(emails)): # for every record get the name and the email addresses name = names[i] email = emails[i] # the message to be emailed message = "Hello " + name # sending the email server.sendmail(your_email, [email], message) # close the smtp serverserver.close() Python file-handling-programs Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2020" }, { "code": null, "e": 356, "s": 52, "text": "Nowadays working with Google forms is quite popular. It is used to mass gather information easily. Email addresses are one of the most common piece of information asked. It is stored in a spreadsheet. In this article we shall see how to send an email to all the email addresses present in a spreadsheet." }, { "code": null, "e": 380, "s": 356, "text": "Prerequisite knowledge:" }, { "code": null, "e": 472, "s": 380, "text": "Loading Excel spreadsheet as pandas DataFrameSend mail from your Gmail account using Python" }, { "code": null, "e": 518, "s": 472, "text": "Loading Excel spreadsheet as pandas DataFrame" }, { "code": null, "e": 565, "s": 518, "text": "Send mail from your Gmail account using Python" }, { "code": null, "e": 576, "s": 565, "text": "Procedure:" }, { "code": null, "e": 679, "s": 576, "text": "Step 1: Read the spreadsheet using the pandas library. The structure of the spreadsheet used here is :" }, { "code": null, "e": 755, "s": 679, "text": "Step 2: Extablish connection with your gmail account using smtplib library." }, { "code": null, "e": 823, "s": 755, "text": "Step 3: Extract the names and email addresses from the spreadsheet." }, { "code": null, "e": 878, "s": 823, "text": "Step 4: Run a loop and for every record send an email." }, { "code": null, "e": 909, "s": 878, "text": "Step 5: Close the smtp server." }, { "code": null, "e": 939, "s": 909, "text": "The Python implementation is:" }, { "code": "# Python code to send email to a list of# emails from a spreadsheet # import the required librariesimport pandas as pdimport smtplib # change these as per useyour_email = \"XYZ@gmail.com\"your_password = \"XYZ\" # establishing connection with gmailserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)server.ehlo()server.login(your_email, your_password) # reading the spreadsheetemail_list = pd.read_excel('C:/Users/user/Desktop/gfg.xlsx') # getting the names and the emailsnames = email_list['NAME']emails = email_list['EMAIL'] # iterate through the recordsfor i in range(len(emails)): # for every record get the name and the email addresses name = names[i] email = emails[i] # the message to be emailed message = \"Hello \" + name # sending the email server.sendmail(your_email, [email], message) # close the smtp serverserver.close()", "e": 1799, "s": 939, "text": null }, { "code": null, "e": 1829, "s": 1799, "text": "Python file-handling-programs" }, { "code": null, "e": 1845, "s": 1829, "text": "Python Programs" } ]
Data Structures | Linked List | Question 7
28 Jun, 2021 typedef struct node { int value; struct node *next;}Node; Node *move_to_front(Node *head) { Node *p, *q; if ((head == NULL: || (head->next == NULL)) return head; q = NULL; p = head; while (p-> next !=NULL) { q = p; p = p->next; } _______________________________ return head;} (A) q = NULL; p->next = head; head = p;(B) q->next = NULL; head = p; p->next = head;(C) head = p; p->next = q; q->next = NULL;(D) q->next = NULL; p->next = head; head = p;Answer: (D)Explanation: See question 1 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-24/Quiz of this Question Data Structures Data Structures-Linked List Linked Lists Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": "typedef struct node { int value; struct node *next;}Node; Node *move_to_front(Node *head) { Node *p, *q; if ((head == NULL: || (head->next == NULL)) return head; q = NULL; p = head; while (p-> next !=NULL) { q = p; p = p->next; } _______________________________ return head;}", "e": 353, "s": 54, "text": null }, { "code": null, "e": 656, "s": 353, "text": "(A) q = NULL; p->next = head; head = p;(B) q->next = NULL; head = p; p->next = head;(C) head = p; p->next = q; q->next = NULL;(D) q->next = NULL; p->next = head; head = p;Answer: (D)Explanation: See question 1 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-24/Quiz of this Question" }, { "code": null, "e": 672, "s": 656, "text": "Data Structures" }, { "code": null, "e": 700, "s": 672, "text": "Data Structures-Linked List" }, { "code": null, "e": 713, "s": 700, "text": "Linked Lists" }, { "code": null, "e": 729, "s": 713, "text": "Data Structures" }, { "code": null, "e": 745, "s": 729, "text": "Data Structures" } ]
Python | a += b is not always a = a + b
23 Nov, 2021 In python a += b doesn’t always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables. So first, you need to know what happens behinds the scene. Creating New Variable: Python3 a = 10print(" id of a : ", id(10) ," Value : ", a ) Output : id of a : 11094592 Value : 10 Here in the above example, value 10 gets stored in memory and its reference gets assigned to a. Modifying The Variable: Python3 a = 10 # Assigning value to variable creats new objectprint(" id of a : ", id(a) ," Value : ", a ) a = a + 10 # Modifying value of variable creats new objectprint(" id of a : ", id(a) ," Value : ", a ) a += 10 # Modifying value of variable creats new objectprint(" id of a : ", id(a) ," Value : ", a ) Output : id of a : 11094592 Value : 10 id of a : 11094912 Value : 20 id of a : 11095232 Value : 30 As whenever we create or modify int, float, char, string they create new objects and assign their newly created reference to their respective variables. But the same behavior is not seen in the list Python3 a = [0, 1] # stores this array in memory and assign its reference to aprint("id of a: ",id(a) , "Value : ", a ) a = a + [2, 3] # this will also behave same store data in memory and assign ref. to variableprint("id of a: ",id(a) , "Value : ", a ) a += [4, 5]print("id of a: ",id(a) , "Value : ", a ) #But now this will now create new ref. instead this will modify the current object so# all the other variable pointing to a will also gets changes Output: id of a: 140266311673864 Value : [0, 1] id of a: 140266311673608 Value : [0, 1, 2, 3] id of a: 140266311673608 Value : [0, 1, 2, 3, 4, 5] At this point you can see the reason why a = a + b some times different from a += b. Consider these examples for list manipulation: Example 1: Python3 list1 = [5, 4, 3, 2, 1]list2 = list1list1 += [1, 2, 3, 4] # modifying value in current reference print(list1)print(list2) # as on line 4 it modify the value without creating new object # variable list2 which is pointing to list1 gets changes Output: [5, 4, 3, 2, 1, 1, 2, 3, 4] [5, 4, 3, 2, 1, 1, 2, 3, 4] Example 2 Python3 list1 = [5, 4, 3, 2, 1]list2 = list1list1 = list1 + [1, 2, 3, 4] # Contents of list1 are same as above# program, but contents of list2 are# different.print(list1)print(list2) Output: [5, 4, 3, 2, 1, 1, 2, 3, 4] [5, 4, 3, 2, 1] expression list1 += [1, 2, 3, 4] modifies the list in-place, which means it extends the list such that “list1” and “list2” still have the reference to the same list. expression list1 = list1 + [1, 2, 3, 4] creates a new list and changes “list1” reference to that new list and “list2” still refer to the old list. aayushibhatia2 parthtagalpallewar123 python-list Python-Operators Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Nov, 2021" }, { "code": null, "e": 296, "s": 52, "text": "In python a += b doesn’t always behave the same way as a = a + b, the same operands may give different results under different conditions. But to understand why they show different behaviors you have to deep dive into the working of variables." }, { "code": null, "e": 356, "s": 296, "text": "So first, you need to know what happens behinds the scene. " }, { "code": null, "e": 379, "s": 356, "text": "Creating New Variable:" }, { "code": null, "e": 387, "s": 379, "text": "Python3" }, { "code": "a = 10print(\" id of a : \", id(10) ,\" Value : \", a )", "e": 440, "s": 387, "text": null }, { "code": null, "e": 449, "s": 440, "text": "Output :" }, { "code": null, "e": 482, "s": 449, "text": "id of a : 11094592 Value : 10" }, { "code": null, "e": 579, "s": 482, "text": "Here in the above example, value 10 gets stored in memory and its reference gets assigned to a. " }, { "code": null, "e": 603, "s": 579, "text": "Modifying The Variable:" }, { "code": null, "e": 611, "s": 603, "text": "Python3" }, { "code": "a = 10 # Assigning value to variable creats new objectprint(\" id of a : \", id(a) ,\" Value : \", a ) a = a + 10 # Modifying value of variable creats new objectprint(\" id of a : \", id(a) ,\" Value : \", a ) a += 10 # Modifying value of variable creats new objectprint(\" id of a : \", id(a) ,\" Value : \", a )", "e": 919, "s": 611, "text": null }, { "code": null, "e": 929, "s": 919, "text": "Output : " }, { "code": null, "e": 1028, "s": 929, "text": "id of a : 11094592 Value : 10\nid of a : 11094912 Value : 20\nid of a : 11095232 Value : 30" }, { "code": null, "e": 1181, "s": 1028, "text": "As whenever we create or modify int, float, char, string they create new objects and assign their newly created reference to their respective variables." }, { "code": null, "e": 1227, "s": 1181, "text": "But the same behavior is not seen in the list" }, { "code": null, "e": 1235, "s": 1227, "text": "Python3" }, { "code": "a = [0, 1] # stores this array in memory and assign its reference to aprint(\"id of a: \",id(a) , \"Value : \", a ) a = a + [2, 3] # this will also behave same store data in memory and assign ref. to variableprint(\"id of a: \",id(a) , \"Value : \", a ) a += [4, 5]print(\"id of a: \",id(a) , \"Value : \", a ) #But now this will now create new ref. instead this will modify the current object so# all the other variable pointing to a will also gets changes", "e": 1681, "s": 1235, "text": null }, { "code": null, "e": 1691, "s": 1681, "text": " Output: " }, { "code": null, "e": 1837, "s": 1691, "text": "id of a: 140266311673864 Value : [0, 1]\nid of a: 140266311673608 Value : [0, 1, 2, 3]\nid of a: 140266311673608 Value : [0, 1, 2, 3, 4, 5] " }, { "code": null, "e": 1922, "s": 1837, "text": "At this point you can see the reason why a = a + b some times different from a += b." }, { "code": null, "e": 1981, "s": 1922, "text": "Consider these examples for list manipulation: Example 1: " }, { "code": null, "e": 1989, "s": 1981, "text": "Python3" }, { "code": "list1 = [5, 4, 3, 2, 1]list2 = list1list1 += [1, 2, 3, 4] # modifying value in current reference print(list1)print(list2) # as on line 4 it modify the value without creating new object # variable list2 which is pointing to list1 gets changes", "e": 2243, "s": 1989, "text": null }, { "code": null, "e": 2252, "s": 2243, "text": "Output: " }, { "code": null, "e": 2308, "s": 2252, "text": "[5, 4, 3, 2, 1, 1, 2, 3, 4]\n[5, 4, 3, 2, 1, 1, 2, 3, 4]" }, { "code": null, "e": 2319, "s": 2308, "text": "Example 2 " }, { "code": null, "e": 2327, "s": 2319, "text": "Python3" }, { "code": "list1 = [5, 4, 3, 2, 1]list2 = list1list1 = list1 + [1, 2, 3, 4] # Contents of list1 are same as above# program, but contents of list2 are# different.print(list1)print(list2)", "e": 2502, "s": 2327, "text": null }, { "code": null, "e": 2511, "s": 2502, "text": "Output: " }, { "code": null, "e": 2555, "s": 2511, "text": "[5, 4, 3, 2, 1, 1, 2, 3, 4]\n[5, 4, 3, 2, 1]" }, { "code": null, "e": 2723, "s": 2557, "text": "expression list1 += [1, 2, 3, 4] modifies the list in-place, which means it extends the list such that “list1” and “list2” still have the reference to the same list." }, { "code": null, "e": 2870, "s": 2723, "text": "expression list1 = list1 + [1, 2, 3, 4] creates a new list and changes “list1” reference to that new list and “list2” still refer to the old list." }, { "code": null, "e": 2885, "s": 2870, "text": "aayushibhatia2" }, { "code": null, "e": 2907, "s": 2885, "text": "parthtagalpallewar123" }, { "code": null, "e": 2919, "s": 2907, "text": "python-list" }, { "code": null, "e": 2936, "s": 2919, "text": "Python-Operators" }, { "code": null, "e": 2943, "s": 2936, "text": "Python" }, { "code": null, "e": 2955, "s": 2943, "text": "python-list" } ]
How to plot Timeseries based charts using Pandas?
30 Jul, 2021 A series of data points collected over the course of a time period, and that are time-indexed is known as Time Series data. These observations are recorded at successive equally spaced points in time. For Example, the ECG Signal, EEG Signal, Stock Market, Weather Data, etc., all are time-indexed and recorded over a period of time. Analyzing these data, and predicting future observations has a wider scope of research. In this article, we will see how to implement EDA — Exploratory Data Analysis using Pandas Library in Python. We will try to infer the nature of the data over a specific period of time by plotting various graphs with matplotlib.pyplot, seaborn, statsmodels, and more packages. For easy understanding of the plots and other functions, we will be creating a sample dataset with 16 rows and 5 columns which includes Date, A, B, C, D, and E columns. Python3 import pandas as pd # Sample data which will be used# to create the dataframesample_timeseries_data = { 'Date': ['2020-01-25', '2020-02-25', '2020-03-25', '2020-04-25', '2020-05-25', '2020-06-25', '2020-07-25', '2020-08-25', '2020-09-25', '2020-10-25', '2020-11-25', '2020-12-25', '2021-01-25', '2021-02-25', '2021-03-25', '2021-04-25'], 'A': [102, 114, 703, 547, 641, 669, 897, 994, 1002, 974, 899, 954, 1105, 1189, 1100, 934], 'B': [1029, 1178, 723, 558, 649, 669, 899, 1000, 1012, 984, 918, 959, 1125, 1199, 1109, 954], 'C': [634, 422,152, 23, 294, 1452, 891, 990, 924, 960, 874, 548, 174, 49, 655, 914], 'D': [1296, 7074, 3853, 4151, 2061, 1478, 2061, 3853, 6379, 2751, 1064, 6263, 2210, 6566, 3918, 1121], 'E': [10, 17, 98, 96, 85, 89, 90, 92, 86, 84, 78, 73, 71, 65, 70, 60]} # Creating a dataframe using pandas# module with Date, A, B, C, D and E# as columns.dataframe = pd.DataFrame( sample_timeseries_data,columns=[ 'Date', 'A', 'B', 'C', 'D', 'E']) # Changing the datatype of Date, from# Object to datetime64dataframe["Date"] = dataframe["Date"].astype("datetime64") # Setting the Date as indexdataframe = dataframe.set_index("Date")dataframe Output: Sample Time Series data frame Line charts are used to represent the relation between two data X and Y on a different axis. Syntax: plt.plot(x) Example 1: This plot shows the variation of Column A values from Jan 2020 till April 2020. Note that the values have a positive trend overall, but there are ups and downs over the course. Python3 import matplotlib.pyplot as plt # Using a inbuilt style to change# the look and feel of the plotplt.style.use("fivethirtyeight") # setting figure size to 12, 10plt.figure(figsize=(12, 10)) # Labelling the axes and setting# a titleplt.xlabel("Date")plt.ylabel("Values")plt.title("Sample Time Series Plot") # plotting the "A" column aloneplt.plot(dataframe["A"]) Output: Sample Time Series Plot Example 2: Plotting with all variables. Python3 plt.style.use("fivethirtyeight")dataframe.plot(subplots=True, figsize=(12, 15)) Output: Plotting all Time-series data columns A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories. Syntax: plt.bar(x, height, width, bottom, align) This bar plot represents the variation of the ‘A’ column values. This can be used to compare the future and the fast values. Python3 import matplotlib.pyplot as plt # Using a inbuilt style to change# the look and feel of the plotplt.style.use("fivethirtyeight") # setting figure size to 12, 10plt.figure(figsize=(15, 10)) # Labelling the axes and setting a# titleplt.xlabel("Date")plt.ylabel("Values")plt.title("Bar Plot of 'A'") # plotting the "A" column aloneplt.bar(dataframe.index, dataframe["A"], width=5) Output: Bar Plot for ‘A’ column The mean of an n-sized window sliding from the beginning to the end of the data frame is known as Rolling Mean. If the window doesn’t have n observations, then NaN is returned. Syntax: pandas.DataFrame.rolling(n).mean() Example: Python3 dataframe.rolling(window = 5).mean() Output: The rolling mean of dataframe Here, we will plot the time series with a rolling means plot: Python3 import matplotlib.pyplot as plt # Using a inbuilt style to change# the look and feel of the plotplt.style.use("fivethirtyeight") # setting figure size to 12, 10plt.figure(figsize=(12, 10)) # Labelling the axes and setting# a titleplt.xlabel("Date")plt.ylabel("Values")plt.title("Values of 'A' and Rolling Mean (2) Plot") # plotting the "A" column and "A" column# of Rolling Dataframe (window_size = 20)plt.plot(dataframe["A"])plt.plot(dataframe.rolling( window=2, min_periods=1).mean()["A"]) Output: Rolling mean plot Explanation: The Blue Plot Line represents the original ‘A’ column values while the Red Plot Line represents the Rolling mean of ‘A’ column values of window size = 2 Through this plot, we infer that the rolling mean of a time-series data returns values with fewer fluctuations. The trend of the plot is retained but unwanted ups and downs which are of less significance are discarded. For plotting the decomposition of time-series data, box plot analysis, etc., it is a good practice to use a rolling mean data frame so that the fluctuations don’t affect the analysis, especially in forecasting the trend. It shows the observations and these four elements in the same plot: Trend Component: It shows the pattern of the data that spans across the various seasonal periods. It represents the variation of ‘A’ values over the period of 2 years with no fluctuations. Seasonal Component: This plot shows the ups and downs of the ‘A’ values i.e. the recurring normal variations. Residual Component: This is the leftover component after decomposing the ‘A’ values data into Trend and Seasonal Component. Observed Component: This trend and a seasonal component can be used to study the data for various purposes. Example: Python3 import statsmodels.api as smfrom pylab import rcParamsimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # Separating the Date Component into# Year and Monthdataframe['Date'] = dataframe.indexdataframe['Year'] = dataframe['Date'].dt.yeardataframe['Month'] = dataframe['Date'].dt.month # using inbuilt styleplt.style.use("fivethirtyeight") # Creating a dataframe with "Date" and "A"# columns only. This dataframe is date indexeddecomposition_dataframe = dataframe[['Date', 'A']].copy()decomposition_dataframe.set_index('Date', inplace=True)decomposition_dataframe.index = pd.to_datetime(decomposition_dataframe.index) # using sm.tsa library, we are plotting the# seasonal decomposition of the "A" column# Multiplicative Model : Y[t] = T[t] * S[t] * R[t]decomposition = sm.tsa.seasonal_decompose(decomposition_dataframe, model='multiplicative', freq=5)decomp = decomposition.plot()decomp.suptitle('"A" Value Decomposition') # changing the runtime configuration parameters to# have a desired plot of desired size, etcrcParams['figure.figsize'] = 12, 10rcParams['axes.labelsize'] = 12rcParams['ytick.labelsize'] = 12rcParams['xtick.labelsize'] = 12 Output: ‘A’ value decomposition It is a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelation for data values at varying time lags. It shows the properties of a type of data known as a time series. These plots are available in most general-purpose statistical software programs. It can be plotted using the pandas.plotting.autocorrelation_plot(). Syntax: pandas.plotting.autocorrelation_plot(series, ax=None, **kwargs) Parameters: series: This parameter is the Time series to be used to plot. ax: This parameter is a matplotlib axes object. Its default value is None. Returns: This function returns an object of class matplotlip.axis.Axes Considering the trend, seasonality, cyclic and residual, this plot shows the current value of the time-series data is related to the previous values. We can see that a significant proportion of the line shows an effective correlation with time, and we can use such correlation plots to study the internal dependence of time-series data. Code: Python3 from pandas.plotting import autocorrelation_plot autocorrelation_plot(dataframe['A']) Output: Autocorrelation plot Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detecting the outlier in data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes a sample data using 25th, 50th and 75th percentiles. Syntax: seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None, **kwargs) Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form. color: Color for all of the elements. Returns: It returns the Axes object with the plot drawn onto it. Here, through these plots, we will be able to obtain an intuition of the ‘A’ value ranges of each year (Year-wise Box Plot) as well as each month (Month-wise Box Plot). Also, through the Month-wise Box Plot, we can observe that the value range is slightly higher in Jan and Feb, compared to other months. Python3 # Splitting the plot into (1,2) subplots# and initializing them using fig and ax# variablesfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 6)) # Using Seaborn Library for Box Plotsns.boxplot(dataframe['Year'], dataframe["A"], ax=ax[0]) # Defining the title and axes namesax[0].set_title('Year-wise Box Plot for A', fontsize=20, loc='center')ax[0].set_xlabel('Year')ax[0].set_ylabel('"A" values') # Using Seaborn Library for Box Plotsns.boxplot(dataframe['Month'], dataframe["A"], ax=ax[1]) # Defining the title and axes namesax[1].set_title('Month-wise Box Plot for A', fontsize=20, loc='center')ax[1].set_xlabel('Month')ax[1].set_ylabel('"A" values') # rotate the ticks and right align themfig.autofmt_xdate() Output: box plot analysis of ‘A’ column values This plot the achieved by dividing the current value of the ‘A’ column by the shifted value of the ‘A’ column. Default Shift is by one value. This plot is used to analyze the value stability on a daily basis. Python3 dataframe['Change'] = dataframe.A.div(dataframe.A.shift())dataframe['Change'].plot(figsize=(15, 10), xlabel = "Date", ylabel = "Value Difference", title = "Shift Plot") Output: shift plot of the ‘A’ values We can interpret the trend of the “A” column values across the years sampled over 12 months, variation of values across different years, etc. We can also infer how the values have changed from the average value. This heatmap is a really useful visualization. This Heatmap shows the variation of temperature across Years as well as Months, differentiated using a Colormap. Python3 import calendarimport seaborn as snsimport pandas as pd dataframe['Date'] = dataframe.index # Splitting the Date into Year and Monthdataframe['Year'] = dataframe['Date'].dt.yeardataframe['Month'] = dataframe['Date'].dt.month # Creating a Pivot Table with "A"# column values and is Month indexed.table_df = pd.pivot_table(dataframe, values=["A"], index=["Month"], columns=["Year"], fill_value=0, margins=True) # Naming the index, can be generated# using calendar.month_abbr[i]mon_name = [['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep','Oct', 'Nov', 'Dec', 'All']] # Indexing using Month Namestable_df = table_df.set_index(mon_name) # Creating a heatmap using sns with Red,# Yellow & Green Colormap.ax = sns.heatmap(table_df, cmap='RdYlGn_r', robust=True, fmt='.2f', annot=True, linewidths=.6, annot_kws={'size':10}, cbar_kws={'shrink':.5, 'label':'"A" values'}) # Setting the Tick Labels, Title and x & Y labelsax.set_yticklabels(ax.get_yticklabels())ax.set_xticklabels(ax.get_xticklabels())plt.title('"A" Value Analysis', pad=14)plt.xlabel('Year')plt.ylabel('Months') Output: heatmap table for “A” column Heatmap Plot for the “A” column values manikarora059 Picked Python pandas-plotting Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jul, 2021" }, { "code": null, "e": 476, "s": 54, "text": "A series of data points collected over the course of a time period, and that are time-indexed is known as Time Series data. These observations are recorded at successive equally spaced points in time. For Example, the ECG Signal, EEG Signal, Stock Market, Weather Data, etc., all are time-indexed and recorded over a period of time. Analyzing these data, and predicting future observations has a wider scope of research. " }, { "code": null, "e": 753, "s": 476, "text": "In this article, we will see how to implement EDA — Exploratory Data Analysis using Pandas Library in Python. We will try to infer the nature of the data over a specific period of time by plotting various graphs with matplotlib.pyplot, seaborn, statsmodels, and more packages." }, { "code": null, "e": 922, "s": 753, "text": "For easy understanding of the plots and other functions, we will be creating a sample dataset with 16 rows and 5 columns which includes Date, A, B, C, D, and E columns." }, { "code": null, "e": 930, "s": 922, "text": "Python3" }, { "code": "import pandas as pd # Sample data which will be used# to create the dataframesample_timeseries_data = { 'Date': ['2020-01-25', '2020-02-25', '2020-03-25', '2020-04-25', '2020-05-25', '2020-06-25', '2020-07-25', '2020-08-25', '2020-09-25', '2020-10-25', '2020-11-25', '2020-12-25', '2021-01-25', '2021-02-25', '2021-03-25', '2021-04-25'], 'A': [102, 114, 703, 547, 641, 669, 897, 994, 1002, 974, 899, 954, 1105, 1189, 1100, 934], 'B': [1029, 1178, 723, 558, 649, 669, 899, 1000, 1012, 984, 918, 959, 1125, 1199, 1109, 954], 'C': [634, 422,152, 23, 294, 1452, 891, 990, 924, 960, 874, 548, 174, 49, 655, 914], 'D': [1296, 7074, 3853, 4151, 2061, 1478, 2061, 3853, 6379, 2751, 1064, 6263, 2210, 6566, 3918, 1121], 'E': [10, 17, 98, 96, 85, 89, 90, 92, 86, 84, 78, 73, 71, 65, 70, 60]} # Creating a dataframe using pandas# module with Date, A, B, C, D and E# as columns.dataframe = pd.DataFrame( sample_timeseries_data,columns=[ 'Date', 'A', 'B', 'C', 'D', 'E']) # Changing the datatype of Date, from# Object to datetime64dataframe[\"Date\"] = dataframe[\"Date\"].astype(\"datetime64\") # Setting the Date as indexdataframe = dataframe.set_index(\"Date\")dataframe", "e": 2334, "s": 930, "text": null }, { "code": null, "e": 2343, "s": 2334, "text": "Output: " }, { "code": null, "e": 2373, "s": 2343, "text": "Sample Time Series data frame" }, { "code": null, "e": 2467, "s": 2373, "text": "Line charts are used to represent the relation between two data X and Y on a different axis. " }, { "code": null, "e": 2487, "s": 2467, "text": "Syntax: plt.plot(x)" }, { "code": null, "e": 2676, "s": 2487, "text": "Example 1: This plot shows the variation of Column A values from Jan 2020 till April 2020. Note that the values have a positive trend overall, but there are ups and downs over the course. " }, { "code": null, "e": 2684, "s": 2676, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Using a inbuilt style to change# the look and feel of the plotplt.style.use(\"fivethirtyeight\") # setting figure size to 12, 10plt.figure(figsize=(12, 10)) # Labelling the axes and setting# a titleplt.xlabel(\"Date\")plt.ylabel(\"Values\")plt.title(\"Sample Time Series Plot\") # plotting the \"A\" column aloneplt.plot(dataframe[\"A\"])", "e": 3045, "s": 2684, "text": null }, { "code": null, "e": 3053, "s": 3045, "text": "Output:" }, { "code": null, "e": 3077, "s": 3053, "text": "Sample Time Series Plot" }, { "code": null, "e": 3117, "s": 3077, "text": "Example 2: Plotting with all variables." }, { "code": null, "e": 3125, "s": 3117, "text": "Python3" }, { "code": "plt.style.use(\"fivethirtyeight\")dataframe.plot(subplots=True, figsize=(12, 15))", "e": 3205, "s": 3125, "text": null }, { "code": null, "e": 3214, "s": 3205, "text": "Output: " }, { "code": null, "e": 3252, "s": 3214, "text": "Plotting all Time-series data columns" }, { "code": null, "e": 3723, "s": 3252, "text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories. " }, { "code": null, "e": 3772, "s": 3723, "text": "Syntax: plt.bar(x, height, width, bottom, align)" }, { "code": null, "e": 3898, "s": 3772, "text": "This bar plot represents the variation of the ‘A’ column values. This can be used to compare the future and the fast values. " }, { "code": null, "e": 3906, "s": 3898, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Using a inbuilt style to change# the look and feel of the plotplt.style.use(\"fivethirtyeight\") # setting figure size to 12, 10plt.figure(figsize=(15, 10)) # Labelling the axes and setting a# titleplt.xlabel(\"Date\")plt.ylabel(\"Values\")plt.title(\"Bar Plot of 'A'\") # plotting the \"A\" column aloneplt.bar(dataframe.index, dataframe[\"A\"], width=5)", "e": 4284, "s": 3906, "text": null }, { "code": null, "e": 4292, "s": 4284, "text": "Output:" }, { "code": null, "e": 4316, "s": 4292, "text": "Bar Plot for ‘A’ column" }, { "code": null, "e": 4493, "s": 4316, "text": "The mean of an n-sized window sliding from the beginning to the end of the data frame is known as Rolling Mean. If the window doesn’t have n observations, then NaN is returned." }, { "code": null, "e": 4536, "s": 4493, "text": "Syntax: pandas.DataFrame.rolling(n).mean()" }, { "code": null, "e": 4545, "s": 4536, "text": "Example:" }, { "code": null, "e": 4553, "s": 4545, "text": "Python3" }, { "code": "dataframe.rolling(window = 5).mean()", "e": 4590, "s": 4553, "text": null }, { "code": null, "e": 4599, "s": 4590, "text": "Output: " }, { "code": null, "e": 4629, "s": 4599, "text": "The rolling mean of dataframe" }, { "code": null, "e": 4692, "s": 4629, "text": "Here, we will plot the time series with a rolling means plot: " }, { "code": null, "e": 4700, "s": 4692, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Using a inbuilt style to change# the look and feel of the plotplt.style.use(\"fivethirtyeight\") # setting figure size to 12, 10plt.figure(figsize=(12, 10)) # Labelling the axes and setting# a titleplt.xlabel(\"Date\")plt.ylabel(\"Values\")plt.title(\"Values of 'A' and Rolling Mean (2) Plot\") # plotting the \"A\" column and \"A\" column# of Rolling Dataframe (window_size = 20)plt.plot(dataframe[\"A\"])plt.plot(dataframe.rolling( window=2, min_periods=1).mean()[\"A\"])", "e": 5194, "s": 4700, "text": null }, { "code": null, "e": 5202, "s": 5194, "text": "Output:" }, { "code": null, "e": 5220, "s": 5202, "text": "Rolling mean plot" }, { "code": null, "e": 5233, "s": 5220, "text": "Explanation:" }, { "code": null, "e": 5386, "s": 5233, "text": "The Blue Plot Line represents the original ‘A’ column values while the Red Plot Line represents the Rolling mean of ‘A’ column values of window size = 2" }, { "code": null, "e": 5605, "s": 5386, "text": "Through this plot, we infer that the rolling mean of a time-series data returns values with fewer fluctuations. The trend of the plot is retained but unwanted ups and downs which are of less significance are discarded." }, { "code": null, "e": 5826, "s": 5605, "text": "For plotting the decomposition of time-series data, box plot analysis, etc., it is a good practice to use a rolling mean data frame so that the fluctuations don’t affect the analysis, especially in forecasting the trend." }, { "code": null, "e": 5894, "s": 5826, "text": "It shows the observations and these four elements in the same plot:" }, { "code": null, "e": 6083, "s": 5894, "text": "Trend Component: It shows the pattern of the data that spans across the various seasonal periods. It represents the variation of ‘A’ values over the period of 2 years with no fluctuations." }, { "code": null, "e": 6193, "s": 6083, "text": "Seasonal Component: This plot shows the ups and downs of the ‘A’ values i.e. the recurring normal variations." }, { "code": null, "e": 6317, "s": 6193, "text": "Residual Component: This is the leftover component after decomposing the ‘A’ values data into Trend and Seasonal Component." }, { "code": null, "e": 6425, "s": 6317, "text": "Observed Component: This trend and a seasonal component can be used to study the data for various purposes." }, { "code": null, "e": 6434, "s": 6425, "text": "Example:" }, { "code": null, "e": 6442, "s": 6434, "text": "Python3" }, { "code": "import statsmodels.api as smfrom pylab import rcParamsimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns # Separating the Date Component into# Year and Monthdataframe['Date'] = dataframe.indexdataframe['Year'] = dataframe['Date'].dt.yeardataframe['Month'] = dataframe['Date'].dt.month # using inbuilt styleplt.style.use(\"fivethirtyeight\") # Creating a dataframe with \"Date\" and \"A\"# columns only. This dataframe is date indexeddecomposition_dataframe = dataframe[['Date', 'A']].copy()decomposition_dataframe.set_index('Date', inplace=True)decomposition_dataframe.index = pd.to_datetime(decomposition_dataframe.index) # using sm.tsa library, we are plotting the# seasonal decomposition of the \"A\" column# Multiplicative Model : Y[t] = T[t] * S[t] * R[t]decomposition = sm.tsa.seasonal_decompose(decomposition_dataframe, model='multiplicative', freq=5)decomp = decomposition.plot()decomp.suptitle('\"A\" Value Decomposition') # changing the runtime configuration parameters to# have a desired plot of desired size, etcrcParams['figure.figsize'] = 12, 10rcParams['axes.labelsize'] = 12rcParams['ytick.labelsize'] = 12rcParams['xtick.labelsize'] = 12", "e": 7649, "s": 6442, "text": null }, { "code": null, "e": 7657, "s": 7649, "text": "Output:" }, { "code": null, "e": 7681, "s": 7657, "text": "‘A’ value decomposition" }, { "code": null, "e": 8060, "s": 7681, "text": "It is a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelation for data values at varying time lags. It shows the properties of a type of data known as a time series. These plots are available in most general-purpose statistical software programs. It can be plotted using the pandas.plotting.autocorrelation_plot()." }, { "code": null, "e": 8132, "s": 8060, "text": "Syntax: pandas.plotting.autocorrelation_plot(series, ax=None, **kwargs)" }, { "code": null, "e": 8144, "s": 8132, "text": "Parameters:" }, { "code": null, "e": 8206, "s": 8144, "text": "series: This parameter is the Time series to be used to plot." }, { "code": null, "e": 8281, "s": 8206, "text": "ax: This parameter is a matplotlib axes object. Its default value is None." }, { "code": null, "e": 8352, "s": 8281, "text": "Returns: This function returns an object of class matplotlip.axis.Axes" }, { "code": null, "e": 8689, "s": 8352, "text": "Considering the trend, seasonality, cyclic and residual, this plot shows the current value of the time-series data is related to the previous values. We can see that a significant proportion of the line shows an effective correlation with time, and we can use such correlation plots to study the internal dependence of time-series data." }, { "code": null, "e": 8695, "s": 8689, "text": "Code:" }, { "code": null, "e": 8703, "s": 8695, "text": "Python3" }, { "code": "from pandas.plotting import autocorrelation_plot autocorrelation_plot(dataframe['A'])", "e": 8789, "s": 8703, "text": null }, { "code": null, "e": 8798, "s": 8789, "text": "Output: " }, { "code": null, "e": 8819, "s": 8798, "text": "Autocorrelation plot" }, { "code": null, "e": 9183, "s": 8819, "text": "Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detecting the outlier in data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes a sample data using 25th, 50th and 75th percentiles. " }, { "code": null, "e": 9409, "s": 9183, "text": "Syntax: seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, ax=None, **kwargs)" }, { "code": null, "e": 9591, "s": 9409, "text": "Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. If x and y are absent, this is interpreted as wide-form. color: Color for all of the elements." }, { "code": null, "e": 9657, "s": 9591, "text": "Returns: It returns the Axes object with the plot drawn onto it. " }, { "code": null, "e": 9962, "s": 9657, "text": "Here, through these plots, we will be able to obtain an intuition of the ‘A’ value ranges of each year (Year-wise Box Plot) as well as each month (Month-wise Box Plot). Also, through the Month-wise Box Plot, we can observe that the value range is slightly higher in Jan and Feb, compared to other months." }, { "code": null, "e": 9970, "s": 9962, "text": "Python3" }, { "code": "# Splitting the plot into (1,2) subplots# and initializing them using fig and ax# variablesfig, ax = plt.subplots(nrows=1, ncols=2, figsize=(15, 6)) # Using Seaborn Library for Box Plotsns.boxplot(dataframe['Year'], dataframe[\"A\"], ax=ax[0]) # Defining the title and axes namesax[0].set_title('Year-wise Box Plot for A', fontsize=20, loc='center')ax[0].set_xlabel('Year')ax[0].set_ylabel('\"A\" values') # Using Seaborn Library for Box Plotsns.boxplot(dataframe['Month'], dataframe[\"A\"], ax=ax[1]) # Defining the title and axes namesax[1].set_title('Month-wise Box Plot for A', fontsize=20, loc='center')ax[1].set_xlabel('Month')ax[1].set_ylabel('\"A\" values') # rotate the ticks and right align themfig.autofmt_xdate()", "e": 10761, "s": 9970, "text": null }, { "code": null, "e": 10769, "s": 10761, "text": "Output:" }, { "code": null, "e": 10808, "s": 10769, "text": "box plot analysis of ‘A’ column values" }, { "code": null, "e": 11017, "s": 10808, "text": "This plot the achieved by dividing the current value of the ‘A’ column by the shifted value of the ‘A’ column. Default Shift is by one value. This plot is used to analyze the value stability on a daily basis." }, { "code": null, "e": 11025, "s": 11017, "text": "Python3" }, { "code": "dataframe['Change'] = dataframe.A.div(dataframe.A.shift())dataframe['Change'].plot(figsize=(15, 10), xlabel = \"Date\", ylabel = \"Value Difference\", title = \"Shift Plot\")", "e": 11266, "s": 11025, "text": null }, { "code": null, "e": 11275, "s": 11266, "text": "Output: " }, { "code": null, "e": 11304, "s": 11275, "text": "shift plot of the ‘A’ values" }, { "code": null, "e": 11677, "s": 11304, "text": "We can interpret the trend of the “A” column values across the years sampled over 12 months, variation of values across different years, etc. We can also infer how the values have changed from the average value. This heatmap is a really useful visualization. This Heatmap shows the variation of temperature across Years as well as Months, differentiated using a Colormap. " }, { "code": null, "e": 11685, "s": 11677, "text": "Python3" }, { "code": "import calendarimport seaborn as snsimport pandas as pd dataframe['Date'] = dataframe.index # Splitting the Date into Year and Monthdataframe['Year'] = dataframe['Date'].dt.yeardataframe['Month'] = dataframe['Date'].dt.month # Creating a Pivot Table with \"A\"# column values and is Month indexed.table_df = pd.pivot_table(dataframe, values=[\"A\"], index=[\"Month\"], columns=[\"Year\"], fill_value=0, margins=True) # Naming the index, can be generated# using calendar.month_abbr[i]mon_name = [['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep','Oct', 'Nov', 'Dec', 'All']] # Indexing using Month Namestable_df = table_df.set_index(mon_name) # Creating a heatmap using sns with Red,# Yellow & Green Colormap.ax = sns.heatmap(table_df, cmap='RdYlGn_r', robust=True, fmt='.2f', annot=True, linewidths=.6, annot_kws={'size':10}, cbar_kws={'shrink':.5, 'label':'\"A\" values'}) # Setting the Tick Labels, Title and x & Y labelsax.set_yticklabels(ax.get_yticklabels())ax.set_xticklabels(ax.get_xticklabels())plt.title('\"A\" Value Analysis', pad=14)plt.xlabel('Year')plt.ylabel('Months')", "e": 13041, "s": 11685, "text": null }, { "code": null, "e": 13049, "s": 13041, "text": "Output:" }, { "code": null, "e": 13078, "s": 13049, "text": "heatmap table for “A” column" }, { "code": null, "e": 13117, "s": 13078, "text": "Heatmap Plot for the “A” column values" }, { "code": null, "e": 13133, "s": 13119, "text": "manikarora059" }, { "code": null, "e": 13140, "s": 13133, "text": "Picked" }, { "code": null, "e": 13163, "s": 13140, "text": "Python pandas-plotting" }, { "code": null, "e": 13170, "s": 13163, "text": "Python" } ]
PYGLET – On Mouse Scroll Event
30 Jul, 2021 In this article we will see how we can trigger on mouse scroll event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen).This event get called when the mouse wheel was scrolled. Note that most mice have only a vertical scroll wheel, so scroll_x is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both scroll_x and scroll_y movement. We can create a window with the help of command given below : pyglet.window.Window(width, height, title) Below is the syntax of the on mouse scroll event, this method get called when this event is triggered : @window.event def on_mouse_scroll(x, y, scroll_x, scroll_y): print("Mouse scrolled") Below is the implementation : Python3 # importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = "GeeksforGeeks" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 36, x = window.width//2, y = window.height//2, anchor_x ='center', anchor_y ='center') new_label = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 10, x = 25, y = 25) # on draw event@window.eventdef on_draw(): # clearing the window window.clear() # drawing the label on the window label.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key "C" get press if symbol == pyglet.window.key.C: print("Key C is pressed") # on mouse scroll event@window.eventdef on_mouse_scroll(x, y, scroll_x, scroll_y): # printing some message print("Mouse scrolled") # image for iconimg = image = pyglet.resource.image("logo.png") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run() Output : Mouse scrolled Mouse scrolled Mouse scrolled Mouse scrolled Mouse scrolled Mouse scrolled Mouse scrolled Mouse scrolled Mouse scrolled varshagumber28 Python-gui Python-Pyglet Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2021" }, { "code": null, "e": 687, "s": 28, "text": "In this article we will see how we can trigger on mouse scroll event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen).This event get called when the mouse wheel was scrolled. Note that most mice have only a vertical scroll wheel, so scroll_x is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both scroll_x and scroll_y movement." }, { "code": null, "e": 750, "s": 687, "text": "We can create a window with the help of command given below : " }, { "code": null, "e": 793, "s": 750, "text": "pyglet.window.Window(width, height, title)" }, { "code": null, "e": 897, "s": 793, "text": "Below is the syntax of the on mouse scroll event, this method get called when this event is triggered :" }, { "code": null, "e": 993, "s": 897, "text": "@window.event \ndef on_mouse_scroll(x, y, scroll_x, scroll_y):\n print(\"Mouse scrolled\")" }, { "code": null, "e": 1023, "s": 993, "text": "Below is the implementation :" }, { "code": null, "e": 1031, "s": 1023, "text": "Python3" }, { "code": "# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = \"GeeksforGeeks\" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 36, x = window.width//2, y = window.height//2, anchor_x ='center', anchor_y ='center') new_label = pyglet.text.Label(text, font_name ='Times New Roman', font_size = 10, x = 25, y = 25) # on draw event@window.eventdef on_draw(): # clearing the window window.clear() # drawing the label on the window label.draw() # key press event @window.eventdef on_key_press(symbol, modifier): # key \"C\" get press if symbol == pyglet.window.key.C: print(\"Key C is pressed\") # on mouse scroll event@window.eventdef on_mouse_scroll(x, y, scroll_x, scroll_y): # printing some message print(\"Mouse scrolled\") # image for iconimg = image = pyglet.resource.image(\"logo.png\") # setting image as iconwindow.set_icon(img) # start running the applicationpyglet.app.run()", "e": 2483, "s": 1031, "text": null }, { "code": null, "e": 2494, "s": 2483, "text": "Output : " }, { "code": null, "e": 2629, "s": 2494, "text": "Mouse scrolled\nMouse scrolled\nMouse scrolled\nMouse scrolled\nMouse scrolled\nMouse scrolled\nMouse scrolled\nMouse scrolled\nMouse scrolled" }, { "code": null, "e": 2646, "s": 2631, "text": "varshagumber28" }, { "code": null, "e": 2657, "s": 2646, "text": "Python-gui" }, { "code": null, "e": 2671, "s": 2657, "text": "Python-Pyglet" }, { "code": null, "e": 2678, "s": 2671, "text": "Python" } ]
How to pass JavaScript variables to PHP ?
31 Jul, 2021 JavaScript is the client side and PHP is the server side script language. The way to pass a JavaScript variable to PHP is through a request. Method 1: This example uses form element and GET/POST method to pass JavaScript variables to PHP. The form of contents can be accessed through the GET and POST actions in PHP. When the form is submitted, the client sends the form data in the form of a URL such as: https://example.com?name=value This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Client Side: <!DOCTYPE html><html> <head> <title> Passing JavaScript variables to PHP </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <form method="get" name="form" action="destination.php"> <input type="text" placeholder="Enter Data" name="data"> <input type="submit" value="Submit"> </form></body> </html> Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. <?php$result = $_GET['data'];echo $result;?> Output: Method 2: Using Cookies to store information:Client Side: Use Cookie to store the information, which is then requested in the PHP page. A cookie named gfg is created in the code below and the value GeeksforGeeks is stored. While creating a cookie, an expire time should also be specified, which is 10 days for this case. <script> // Creating a cookie after the document is ready$(document).ready(function () { createCookie("gfg", "GeeksforGeeks", "10");}); // Function to create the cookiefunction createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";} </script> Server Side(PHP): On the server side, we request for the cookie by specifying the name gfg and extract the data to display it on the screen. <?php echo $_COOKIE["gfg"];?> Output: 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. 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. Picked JavaScript PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ?
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Jul, 2021" }, { "code": null, "e": 193, "s": 52, "text": "JavaScript is the client side and PHP is the server side script language. The way to pass a JavaScript variable to PHP is through a request." }, { "code": null, "e": 458, "s": 193, "text": "Method 1: This example uses form element and GET/POST method to pass JavaScript variables to PHP. The form of contents can be accessed through the GET and POST actions in PHP. When the form is submitted, the client sends the form data in the form of a URL such as:" }, { "code": null, "e": 489, "s": 458, "text": "https://example.com?name=value" }, { "code": null, "e": 598, "s": 489, "text": "This type of URL is only visible if we use the GET action, the POST action hides the information in the URL." }, { "code": null, "e": 611, "s": 598, "text": "Client Side:" }, { "code": "<!DOCTYPE html><html> <head> <title> Passing JavaScript variables to PHP </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <form method=\"get\" name=\"form\" action=\"destination.php\"> <input type=\"text\" placeholder=\"Enter Data\" name=\"data\"> <input type=\"submit\" value=\"Submit\"> </form></body> </html>", "e": 986, "s": 611, "text": null }, { "code": null, "e": 1103, "s": 986, "text": "Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result." }, { "code": "<?php$result = $_GET['data'];echo $result;?>", "e": 1148, "s": 1103, "text": null }, { "code": null, "e": 1156, "s": 1148, "text": "Output:" }, { "code": null, "e": 1477, "s": 1156, "text": "Method 2: Using Cookies to store information:Client Side: Use Cookie to store the information, which is then requested in the PHP page. A cookie named gfg is created in the code below and the value GeeksforGeeks is stored. While creating a cookie, an expire time should also be specified, which is 10 days for this case." }, { "code": "<script> // Creating a cookie after the document is ready$(document).ready(function () { createCookie(\"gfg\", \"GeeksforGeeks\", \"10\");}); // Function to create the cookiefunction createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = \"; expires=\" + date.toGMTString(); } else { expires = \"\"; } document.cookie = escape(name) + \"=\" + escape(value) + expires + \"; path=/\";} </script>", "e": 2028, "s": 1477, "text": null }, { "code": null, "e": 2169, "s": 2028, "text": "Server Side(PHP): On the server side, we request for the cookie by specifying the name gfg and extract the data to display it on the screen." }, { "code": "<?php echo $_COOKIE[\"gfg\"];?>", "e": 2202, "s": 2169, "text": null }, { "code": null, "e": 2210, "s": 2202, "text": "Output:" }, { "code": null, "e": 2429, "s": 2210, "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": 2598, "s": 2429, "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": 2605, "s": 2598, "text": "Picked" }, { "code": null, "e": 2616, "s": 2605, "text": "JavaScript" }, { "code": null, "e": 2620, "s": 2616, "text": "PHP" }, { "code": null, "e": 2633, "s": 2620, "text": "PHP Programs" }, { "code": null, "e": 2650, "s": 2633, "text": "Web Technologies" }, { "code": null, "e": 2677, "s": 2650, "text": "Web technologies Questions" }, { "code": null, "e": 2681, "s": 2677, "text": "PHP" }, { "code": null, "e": 2779, "s": 2681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2840, "s": 2779, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2912, "s": 2840, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2952, "s": 2912, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2994, "s": 2952, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3035, "s": 2994, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3080, "s": 3035, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3104, "s": 3080, "text": "PHP in_array() Function" }, { "code": null, "e": 3156, "s": 3104, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3206, "s": 3156, "text": "How to Insert Form Data into Database using PHP ?" } ]
Minimum replacements in a string to make adjacent characters unequal
29 Apr, 2021 Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples: Input: Str = “caaab” Output: 1 Explanation: Change the second a to any other character, let’s change it to b. So the string becomes “cabab”. and no two adjacent characters are equal. So minimum number of operations is 1.Input: Str = “xxxxxxx” Output: 3 Explanation: Replace ‘x’ at index 1, 3 and 5 to ‘a’, ‘b’, and ‘c’ respectively. Approach: The idea is similar to implement sliding window technique. In this, we need to find the non-overlapping substrings that have all the characters the same. Then the minimum operations will be the sum of the floor of half the length of each substring. There is no need to change a character directly. Instead, consider all substring started from any index having only one character.Now consider any substring of length l such that all the characters of that substring are equal then change floor ( l / 2) characters of this substring to some other character.So just iterate over all the characters of the string from any character ch find out the maximal length of the substring such that all the characters in that substring are equal to the character ch.Find the length l of this substring and add floor ( l / 2) to the ans.After that start from the character just next to the end of the above substring. There is no need to change a character directly. Instead, consider all substring started from any index having only one character. Now consider any substring of length l such that all the characters of that substring are equal then change floor ( l / 2) characters of this substring to some other character. So just iterate over all the characters of the string from any character ch find out the maximal length of the substring such that all the characters in that substring are equal to the character ch. Find the length l of this substring and add floor ( l / 2) to the ans. After that start from the character just next to the end of the above substring. C++14 Java Python3 C# Javascript // C++ program to find minimum// replacements in a string to// make adjacent characters unequal #include <bits/stdc++.h>using namespace std; // Function which counts the minimum// number of required operationsvoid count_minimum(string s){ // n stores the length of the string s int n = s.length(); // ans will store the required ans int ans = 0; // i is the current index in the string int i = 0; while (i < n) { int j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (s[j] == s[i] && j < n) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it int diff = j - i; // We need atleast diff/2 operations // for this substring ans += diff / 2; i = j; } cout << ans << endl;} // Driver codeint main(){ string str = "caaab"; count_minimum(str); return 0;} // Java program to find minimum// replacements in a string to// make adjacent characters unequalimport java.util.*; class GFG{ // Function which counts the minimum// number of required operationsstatic void count_minimum(String s){ // n stores the length of the string s int n = s.length(); // ans will store the required ans int ans = 0; // i is the current index in the string int i = 0; while (i < n) { int j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (j < n && s.charAt(j) == s.charAt(i)) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it int diff = j - i; // We need atleast diff/2 operations // for this substring ans += diff / 2; i = j; } System.out.println(ans);} // Driver codepublic static void main(String[] args){ String str = "caaab"; count_minimum(str);}} // This code is contributed by offbeat # Python3 program to find minimum# replacements in a string to# make adjacent characters unequal # Function which counts the minimum# number of required operationsdef count_minimum(s): # n stores the length of the string s n = len(s) # ans will store the required ans ans = 0 # i is the current index in the string i = 0 while i < n: j = i # Move j until characters s[i] & s[j] # are equal or the end of the # string is reached while j < n and (s[j] == s[i]): j += 1 # diff stores the length of the # substring such that all the # characters are equal in it diff = j - i # We need atleast diff/2 operations # for this substring ans += diff // 2 i = j print(ans) # Driver codeif __name__=="__main__": str = "caaab" count_minimum(str) # This code is contributed by rutvik_56 // C# program to find minimum// replacements in a string to// make adjacent characters unequalusing System; class GFG{ // Function which counts the minimum// number of required operationsstatic void count_minimum(string s){ // n stores the length of the string s int n = s.Length; // ans will store the required ans int ans = 0; // i is the current index in the string int i = 0; while (i < n) { int j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (j < n && s[j] == s[i]) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it int diff = j - i; // We need atleast diff/2 operations // for this substring ans += diff / 2; i = j; } Console.WriteLine(ans);} // Driver codestatic void Main(){ string str = "caaab"; count_minimum(str);}} // This code is contributed by divyeshrabadiya07 <script> // JavaScript program to find minimum // replacements in a string to // make adjacent characters unequal // Function which counts the minimum // number of required operations function count_minimum(s) { // n stores the length of the string s var n = s.length; // ans will store the required ans var ans = 0; // i is the current index in the string var i = 0; while (i < n) { var j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (s[j] === s[i] && j < n) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it var diff = j - i; // We need atleast diff/2 operations // for this substring ans += parseInt(diff / 2); i = j; } document.write(ans + "<br>"); } // Driver code var str = "caaab"; count_minimum(str); </script> 1 Time Complexity: O (N) Auxiliary Space: O (1) offbeat divyeshrabadiya07 rutvik_56 rdtank sliding-window substring Strings sliding-window Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2021" }, { "code": null, "e": 287, "s": 54, "text": "Given a lowercase character string str of size N. In one operation any character can be changed into some other character. The task is to find the minimum number of operations such that no two adjacent characters are equal.Examples:" }, { "code": null, "e": 620, "s": 287, "text": "Input: Str = “caaab” Output: 1 Explanation: Change the second a to any other character, let’s change it to b. So the string becomes “cabab”. and no two adjacent characters are equal. So minimum number of operations is 1.Input: Str = “xxxxxxx” Output: 3 Explanation: Replace ‘x’ at index 1, 3 and 5 to ‘a’, ‘b’, and ‘c’ respectively." }, { "code": null, "e": 880, "s": 620, "text": "Approach: The idea is similar to implement sliding window technique. In this, we need to find the non-overlapping substrings that have all the characters the same. Then the minimum operations will be the sum of the floor of half the length of each substring." }, { "code": null, "e": 1535, "s": 880, "text": "There is no need to change a character directly. Instead, consider all substring started from any index having only one character.Now consider any substring of length l such that all the characters of that substring are equal then change floor ( l / 2) characters of this substring to some other character.So just iterate over all the characters of the string from any character ch find out the maximal length of the substring such that all the characters in that substring are equal to the character ch.Find the length l of this substring and add floor ( l / 2) to the ans.After that start from the character just next to the end of the above substring." }, { "code": null, "e": 1666, "s": 1535, "text": "There is no need to change a character directly. Instead, consider all substring started from any index having only one character." }, { "code": null, "e": 1843, "s": 1666, "text": "Now consider any substring of length l such that all the characters of that substring are equal then change floor ( l / 2) characters of this substring to some other character." }, { "code": null, "e": 2042, "s": 1843, "text": "So just iterate over all the characters of the string from any character ch find out the maximal length of the substring such that all the characters in that substring are equal to the character ch." }, { "code": null, "e": 2113, "s": 2042, "text": "Find the length l of this substring and add floor ( l / 2) to the ans." }, { "code": null, "e": 2194, "s": 2113, "text": "After that start from the character just next to the end of the above substring." }, { "code": null, "e": 2200, "s": 2194, "text": "C++14" }, { "code": null, "e": 2205, "s": 2200, "text": "Java" }, { "code": null, "e": 2213, "s": 2205, "text": "Python3" }, { "code": null, "e": 2216, "s": 2213, "text": "C#" }, { "code": null, "e": 2227, "s": 2216, "text": "Javascript" }, { "code": "// C++ program to find minimum// replacements in a string to// make adjacent characters unequal #include <bits/stdc++.h>using namespace std; // Function which counts the minimum// number of required operationsvoid count_minimum(string s){ // n stores the length of the string s int n = s.length(); // ans will store the required ans int ans = 0; // i is the current index in the string int i = 0; while (i < n) { int j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (s[j] == s[i] && j < n) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it int diff = j - i; // We need atleast diff/2 operations // for this substring ans += diff / 2; i = j; } cout << ans << endl;} // Driver codeint main(){ string str = \"caaab\"; count_minimum(str); return 0;}", "e": 3232, "s": 2227, "text": null }, { "code": "// Java program to find minimum// replacements in a string to// make adjacent characters unequalimport java.util.*; class GFG{ // Function which counts the minimum// number of required operationsstatic void count_minimum(String s){ // n stores the length of the string s int n = s.length(); // ans will store the required ans int ans = 0; // i is the current index in the string int i = 0; while (i < n) { int j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (j < n && s.charAt(j) == s.charAt(i)) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it int diff = j - i; // We need atleast diff/2 operations // for this substring ans += diff / 2; i = j; } System.out.println(ans);} // Driver codepublic static void main(String[] args){ String str = \"caaab\"; count_minimum(str);}} // This code is contributed by offbeat", "e": 4340, "s": 3232, "text": null }, { "code": "# Python3 program to find minimum# replacements in a string to# make adjacent characters unequal # Function which counts the minimum# number of required operationsdef count_minimum(s): # n stores the length of the string s n = len(s) # ans will store the required ans ans = 0 # i is the current index in the string i = 0 while i < n: j = i # Move j until characters s[i] & s[j] # are equal or the end of the # string is reached while j < n and (s[j] == s[i]): j += 1 # diff stores the length of the # substring such that all the # characters are equal in it diff = j - i # We need atleast diff/2 operations # for this substring ans += diff // 2 i = j print(ans) # Driver codeif __name__==\"__main__\": str = \"caaab\" count_minimum(str) # This code is contributed by rutvik_56", "e": 5310, "s": 4340, "text": null }, { "code": "// C# program to find minimum// replacements in a string to// make adjacent characters unequalusing System; class GFG{ // Function which counts the minimum// number of required operationsstatic void count_minimum(string s){ // n stores the length of the string s int n = s.Length; // ans will store the required ans int ans = 0; // i is the current index in the string int i = 0; while (i < n) { int j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (j < n && s[j] == s[i]) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it int diff = j - i; // We need atleast diff/2 operations // for this substring ans += diff / 2; i = j; } Console.WriteLine(ans);} // Driver codestatic void Main(){ string str = \"caaab\"; count_minimum(str);}} // This code is contributed by divyeshrabadiya07", "e": 6368, "s": 5310, "text": null }, { "code": "<script> // JavaScript program to find minimum // replacements in a string to // make adjacent characters unequal // Function which counts the minimum // number of required operations function count_minimum(s) { // n stores the length of the string s var n = s.length; // ans will store the required ans var ans = 0; // i is the current index in the string var i = 0; while (i < n) { var j = i; // Move j until characters s[i] & s[j] // are equal or the end of the // string is reached while (s[j] === s[i] && j < n) { j++; } // diff stores the length of the // substring such that all the // characters are equal in it var diff = j - i; // We need atleast diff/2 operations // for this substring ans += parseInt(diff / 2); i = j; } document.write(ans + \"<br>\"); } // Driver code var str = \"caaab\"; count_minimum(str); </script>", "e": 7459, "s": 6368, "text": null }, { "code": null, "e": 7461, "s": 7459, "text": "1" }, { "code": null, "e": 7484, "s": 7461, "text": "Time Complexity: O (N)" }, { "code": null, "e": 7507, "s": 7484, "text": "Auxiliary Space: O (1)" }, { "code": null, "e": 7515, "s": 7507, "text": "offbeat" }, { "code": null, "e": 7533, "s": 7515, "text": "divyeshrabadiya07" }, { "code": null, "e": 7543, "s": 7533, "text": "rutvik_56" }, { "code": null, "e": 7550, "s": 7543, "text": "rdtank" }, { "code": null, "e": 7565, "s": 7550, "text": "sliding-window" }, { "code": null, "e": 7575, "s": 7565, "text": "substring" }, { "code": null, "e": 7583, "s": 7575, "text": "Strings" }, { "code": null, "e": 7598, "s": 7583, "text": "sliding-window" }, { "code": null, "e": 7606, "s": 7598, "text": "Strings" } ]
Different Ways to Get List of All Apps Installed in Your Android Phone
17 Dec, 2021 In this article, we are going to show the list of all the installed apps on your Android phone. So here we are going to learn how to implement that feature in three different ways. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" android:padding="16sp" tools:context=".MainActivity"> <Button android:id="@+id/check" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:onClick="getallapps" android:text="Get Installed Apps" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/totalapp" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/check" /> <ListView android:id="@+id/listview" android:layout_width="365dp" android:layout_height="523dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/totalapp" tools:layout_editor_absoluteY="150dp" /> </androidx.constraintlayout.widget.ConstraintLayout> Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.pm.ApplicationInfo;import android.content.pm.PackageManager;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise layout listView = findViewById(R.id.listview); text = findViewById(R.id.totalapp); } public void getallapps(View view) { // get list of all the apps installed List<ApplicationInfo> infos = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); // create a list with size of total number of apps String[] apps = new String[infos.size()]; int i = 0; // add all the app name in string list for (ApplicationInfo info : infos) { apps[i] = info.packageName; i++; } // set all the apps name in list view listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, apps)); // write total count of apps available. text.setText(infos.size() + " Apps are installed"); } @Override protected void onStart() { super.onStart(); }} Output: Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.pm.PackageInfo;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise layout listView = findViewById(R.id.listview); text = findViewById(R.id.totalapp); } public void getallapps(View view) { // get list of all the apps installed List<PackageInfo> packList = getPackageManager().getInstalledPackages(0); String[] apps = new String[packList.size()]; for (int i = 0; i < packList.size(); i++) { PackageInfo packInfo = packList.get(i); apps[i] = packInfo.applicationInfo.loadLabel(getPackageManager()).toString(); } // set all the apps name in list view listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, apps)); // write total count of apps available. text.setText(packList.size() + " Apps are installed"); } @Override protected void onStart() { super.onStart(); }} Output: Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.content.pm.PackageManager;import android.content.pm.ResolveInfo;import android.content.res.Resources;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise layout listView = findViewById(R.id.listview); text = findViewById(R.id.totalapp); } public void getallapps(View view) throws PackageManager.NameNotFoundException { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // get list of all the apps installed List<ResolveInfo> ril = getPackageManager().queryIntentActivities(mainIntent, 0); List<String> componentList = new ArrayList<String>(); String name = null; int i = 0; // get size of ril and create a list String[] apps = new String[ril.size()]; for (ResolveInfo ri : ril) { if (ri.activityInfo != null) { // get package Resources res = getPackageManager().getResourcesForApplication(ri.activityInfo.applicationInfo); // if activity label res is found if (ri.activityInfo.labelRes != 0) { name = res.getString(ri.activityInfo.labelRes); } else { name = ri.activityInfo.applicationInfo.loadLabel( getPackageManager()).toString(); } apps[i] = name; i++; } } // set all the apps name in list view listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, apps)); // write total count of apps available. text.setText(ril.size() + " Apps are installed"); } @Override protected void onStart() { super.onStart(); }} Output: as5853535 Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2021" }, { "code": null, "e": 285, "s": 28, "text": "In this article, we are going to show the list of all the installed apps on your Android phone. So here we are going to learn how to implement that feature in three different ways. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 314, "s": 285, "text": "Step 1: Create a New Project" }, { "code": null, "e": 476, "s": 314, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 524, "s": 476, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 667, "s": 524, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 671, "s": 667, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:gravity=\"center\" android:orientation=\"vertical\" android:padding=\"16sp\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/check\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:onClick=\"getallapps\" android:text=\"Get Installed Apps\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/totalapp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/check\" /> <ListView android:id=\"@+id/listview\" android:layout_width=\"365dp\" android:layout_height=\"523dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/totalapp\" tools:layout_editor_absoluteY=\"150dp\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 2246, "s": 671, "text": null }, { "code": null, "e": 2436, "s": 2246, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2441, "s": 2436, "text": "Java" }, { "code": "import android.content.pm.ApplicationInfo;import android.content.pm.PackageManager;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise layout listView = findViewById(R.id.listview); text = findViewById(R.id.totalapp); } public void getallapps(View view) { // get list of all the apps installed List<ApplicationInfo> infos = getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA); // create a list with size of total number of apps String[] apps = new String[infos.size()]; int i = 0; // add all the app name in string list for (ApplicationInfo info : infos) { apps[i] = info.packageName; i++; } // set all the apps name in list view listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, apps)); // write total count of apps available. text.setText(infos.size() + \" Apps are installed\"); } @Override protected void onStart() { super.onStart(); }}", "e": 3955, "s": 2441, "text": null }, { "code": null, "e": 3963, "s": 3955, "text": "Output:" }, { "code": null, "e": 4153, "s": 3963, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4158, "s": 4153, "text": "Java" }, { "code": "import android.content.pm.PackageInfo;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise layout listView = findViewById(R.id.listview); text = findViewById(R.id.totalapp); } public void getallapps(View view) { // get list of all the apps installed List<PackageInfo> packList = getPackageManager().getInstalledPackages(0); String[] apps = new String[packList.size()]; for (int i = 0; i < packList.size(); i++) { PackageInfo packInfo = packList.get(i); apps[i] = packInfo.applicationInfo.loadLabel(getPackageManager()).toString(); } // set all the apps name in list view listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, apps)); // write total count of apps available. text.setText(packList.size() + \" Apps are installed\"); } @Override protected void onStart() { super.onStart(); }}", "e": 5575, "s": 4158, "text": null }, { "code": null, "e": 5584, "s": 5575, "text": "Output: " }, { "code": null, "e": 5774, "s": 5584, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5779, "s": 5774, "text": "Java" }, { "code": "import android.content.Intent;import android.content.pm.PackageManager;import android.content.pm.ResolveInfo;import android.content.res.Resources;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { ListView listView; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise layout listView = findViewById(R.id.listview); text = findViewById(R.id.totalapp); } public void getallapps(View view) throws PackageManager.NameNotFoundException { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // get list of all the apps installed List<ResolveInfo> ril = getPackageManager().queryIntentActivities(mainIntent, 0); List<String> componentList = new ArrayList<String>(); String name = null; int i = 0; // get size of ril and create a list String[] apps = new String[ril.size()]; for (ResolveInfo ri : ril) { if (ri.activityInfo != null) { // get package Resources res = getPackageManager().getResourcesForApplication(ri.activityInfo.applicationInfo); // if activity label res is found if (ri.activityInfo.labelRes != 0) { name = res.getString(ri.activityInfo.labelRes); } else { name = ri.activityInfo.applicationInfo.loadLabel( getPackageManager()).toString(); } apps[i] = name; i++; } } // set all the apps name in list view listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, apps)); // write total count of apps available. text.setText(ril.size() + \" Apps are installed\"); } @Override protected void onStart() { super.onStart(); }}", "e": 8073, "s": 5779, "text": null }, { "code": null, "e": 8081, "s": 8073, "text": "Output:" }, { "code": null, "e": 8091, "s": 8081, "text": "as5853535" }, { "code": null, "e": 8099, "s": 8091, "text": "Android" }, { "code": null, "e": 8104, "s": 8099, "text": "Java" }, { "code": null, "e": 8109, "s": 8104, "text": "Java" }, { "code": null, "e": 8117, "s": 8109, "text": "Android" } ]
Python-interface module
26 Mar, 2020 In object-oriented languages like Python, the interface is a collection of method signatures that should be provided by the implementing class. Implementing an interface is a way of writing an organized code and achieve abstraction. The package zope.interface provides an implementation of “object interfaces” for Python. It is maintained by the Zope Toolkit project. The package exports two objects, ‘Interface’ and ‘Attribute’ directly. It also exports several helper methods. It aims to provide stricter semantics and better error messages than Python’s built-in abc module. In python, interface is defined using python class statements and is a subclass of interface.Interface which is the parent interface for all interfaces. Syntax : class IMyInterface(zope.interface.Interface): # methods and attributes Example import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute("foo") def method1(self, x): pass def method2(self): pass print(type(MyInterface))print(MyInterface.__module__)print(MyInterface.__name__) # get attributex = MyInterface['x']print(x)print(type(x)) Output : <class zope.interface.interface.InterfaceClass> __main__ MyInterface <zope.interface.interface.Attribute object at 0x00000270A8C74358> <class 'zope.interface.interface.Attribute'> Interface acts as a blueprint for designing classes, so interfaces are implemented using implementer decorator on class. If a class implements an interface, then the instances of the class provide the interface. Objects can provide interfaces directly, in addition to what their classes implement. Syntax : @zope.interface.implementer(*interfaces) class Class_name: # methods Example import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute("foo") def method1(self, x): pass def method2(self): pass @zope.interface.implementer(MyInterface)class MyClass: def method1(self, x): return x**2 def method2(self): return "foo" We declared that MyClass implements MyInterface. This means that instances of MyClass provide MyInterface. implementedBy(class) – returns a boolean value, True if class implements the interface else False providedBy(object) – returns a boolean value, True if object provides the interface else False providedBy(class) – returns False as class does not provide interface but implements it list(zope.interface.implementedBy(class)) – returns the list of interfaces implemented by a class list(zope.interface.providedBy(object)) – returns the list of interfaces provided by an object. list(zope.interface.providedBy(class)) – returns empty list as class does not provide interface butimplements it. import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute('foo') def method1(self, x, y, z): pass def method2(self): pass @zope.interface.implementer(MyInterface)class MyClass: def method1(self, x): return x**2 def method2(self): return "foo"obj = MyClass() # ask an interface whether it # is implemented by a class:print(MyInterface.implementedBy(MyClass)) # MyClass does not provide # MyInterface but implements it:print(MyInterface.providedBy(MyClass)) # ask whether an interface# is provided by an object:print(MyInterface.providedBy(obj)) # ask what interfaces are # implemented by a class:print(list(zope.interface.implementedBy(MyClass))) # ask what interfaces are# provided by an object:print(list(zope.interface.providedBy(obj))) # class does not provide interfaceprint(list(zope.interface.providedBy(MyClass))) Output : True False True [<InterfaceClass __main__.MyInterface>] [<InterfaceClass __main__.MyInterface>] [] Interfaces can extend other interfaces by listing the other interfaces as base interfaces. extends(interface) – returns boolean value, whether one interface extends another. isOrExtends(interface) – returns boolean value, whether interfaces are same or one extends another. isEqualOrExtendedBy(interface) – returns boolean value, whether interfaces are same or one is extended by another. import zope.interface class BaseI(zope.interface.Interface): def m1(self, x): pass def m2(self): pass class DerivedI(BaseI): def m3(self, x, y): pass @zope.interface.implementer(DerivedI)class cls: def m1(self, z): return z**3 def m2(self): return 'foo' def m3(self, x, y): return x ^ y # Get base interfacesprint(DerivedI.__bases__) # Ask whether baseI extends # DerivedIprint(BaseI.extends(DerivedI)) # Ask whether baseI is equal to# or is extended by DerivedIprint(BaseI.isEqualOrExtendedBy(DerivedI)) # Ask whether baseI is equal to# or extends DerivedIprint(BaseI.isOrExtends(DerivedI)) # Ask whether DerivedI is equal# to or extends BaseIprint(DerivedI.isOrExtends(DerivedI)) Output : (<InterfaceClass __main__.BaseI>, ) False True False True python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Mar, 2020" }, { "code": null, "e": 285, "s": 52, "text": "In object-oriented languages like Python, the interface is a collection of method signatures that should be provided by the implementing class. Implementing an interface is a way of writing an organized code and achieve abstraction." }, { "code": null, "e": 630, "s": 285, "text": "The package zope.interface provides an implementation of “object interfaces” for Python. It is maintained by the Zope Toolkit project. The package exports two objects, ‘Interface’ and ‘Attribute’ directly. It also exports several helper methods. It aims to provide stricter semantics and better error messages than Python’s built-in abc module." }, { "code": null, "e": 783, "s": 630, "text": "In python, interface is defined using python class statements and is a subclass of interface.Interface which is the parent interface for all interfaces." }, { "code": null, "e": 869, "s": 783, "text": "Syntax : \nclass IMyInterface(zope.interface.Interface):\n # methods and attributes\n" }, { "code": null, "e": 877, "s": 869, "text": "Example" }, { "code": "import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute(\"foo\") def method1(self, x): pass def method2(self): pass print(type(MyInterface))print(MyInterface.__module__)print(MyInterface.__name__) # get attributex = MyInterface['x']print(x)print(type(x))", "e": 1202, "s": 877, "text": null }, { "code": null, "e": 1211, "s": 1202, "text": "Output :" }, { "code": null, "e": 1392, "s": 1211, "text": "<class zope.interface.interface.InterfaceClass>\n__main__\nMyInterface\n<zope.interface.interface.Attribute object at 0x00000270A8C74358>\n<class 'zope.interface.interface.Attribute'>\n" }, { "code": null, "e": 1690, "s": 1392, "text": "Interface acts as a blueprint for designing classes, so interfaces are implemented using implementer decorator on class. If a class implements an interface, then the instances of the class provide the interface. Objects can provide interfaces directly, in addition to what their classes implement." }, { "code": null, "e": 1773, "s": 1690, "text": "Syntax : \n@zope.interface.implementer(*interfaces)\nclass Class_name:\n # methods" }, { "code": null, "e": 1781, "s": 1773, "text": "Example" }, { "code": "import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute(\"foo\") def method1(self, x): pass def method2(self): pass @zope.interface.implementer(MyInterface)class MyClass: def method1(self, x): return x**2 def method2(self): return \"foo\"", "e": 2103, "s": 1781, "text": null }, { "code": null, "e": 2210, "s": 2103, "text": "We declared that MyClass implements MyInterface. This means that instances of MyClass provide MyInterface." }, { "code": null, "e": 2308, "s": 2210, "text": "implementedBy(class) – returns a boolean value, True if class implements the interface else False" }, { "code": null, "e": 2403, "s": 2308, "text": "providedBy(object) – returns a boolean value, True if object provides the interface else False" }, { "code": null, "e": 2491, "s": 2403, "text": "providedBy(class) – returns False as class does not provide interface but implements it" }, { "code": null, "e": 2589, "s": 2491, "text": "list(zope.interface.implementedBy(class)) – returns the list of interfaces implemented by a class" }, { "code": null, "e": 2685, "s": 2589, "text": "list(zope.interface.providedBy(object)) – returns the list of interfaces provided by an object." }, { "code": null, "e": 2799, "s": 2685, "text": "list(zope.interface.providedBy(class)) – returns empty list as class does not provide interface butimplements it." }, { "code": "import zope.interface class MyInterface(zope.interface.Interface): x = zope.interface.Attribute('foo') def method1(self, x, y, z): pass def method2(self): pass @zope.interface.implementer(MyInterface)class MyClass: def method1(self, x): return x**2 def method2(self): return \"foo\"obj = MyClass() # ask an interface whether it # is implemented by a class:print(MyInterface.implementedBy(MyClass)) # MyClass does not provide # MyInterface but implements it:print(MyInterface.providedBy(MyClass)) # ask whether an interface# is provided by an object:print(MyInterface.providedBy(obj)) # ask what interfaces are # implemented by a class:print(list(zope.interface.implementedBy(MyClass))) # ask what interfaces are# provided by an object:print(list(zope.interface.providedBy(obj))) # class does not provide interfaceprint(list(zope.interface.providedBy(MyClass)))", "e": 3711, "s": 2799, "text": null }, { "code": null, "e": 3720, "s": 3711, "text": "Output :" }, { "code": null, "e": 3820, "s": 3720, "text": "True\nFalse\nTrue\n[<InterfaceClass __main__.MyInterface>]\n[<InterfaceClass __main__.MyInterface>]\n[]\n" }, { "code": null, "e": 3911, "s": 3820, "text": "Interfaces can extend other interfaces by listing the other interfaces as base interfaces." }, { "code": null, "e": 3994, "s": 3911, "text": "extends(interface) – returns boolean value, whether one interface extends another." }, { "code": null, "e": 4094, "s": 3994, "text": "isOrExtends(interface) – returns boolean value, whether interfaces are same or one extends another." }, { "code": null, "e": 4209, "s": 4094, "text": "isEqualOrExtendedBy(interface) – returns boolean value, whether interfaces are same or one is extended by another." }, { "code": "import zope.interface class BaseI(zope.interface.Interface): def m1(self, x): pass def m2(self): pass class DerivedI(BaseI): def m3(self, x, y): pass @zope.interface.implementer(DerivedI)class cls: def m1(self, z): return z**3 def m2(self): return 'foo' def m3(self, x, y): return x ^ y # Get base interfacesprint(DerivedI.__bases__) # Ask whether baseI extends # DerivedIprint(BaseI.extends(DerivedI)) # Ask whether baseI is equal to# or is extended by DerivedIprint(BaseI.isEqualOrExtendedBy(DerivedI)) # Ask whether baseI is equal to# or extends DerivedIprint(BaseI.isOrExtends(DerivedI)) # Ask whether DerivedI is equal# to or extends BaseIprint(DerivedI.isOrExtends(DerivedI))", "e": 4965, "s": 4209, "text": null }, { "code": null, "e": 4974, "s": 4965, "text": "Output :" }, { "code": null, "e": 5033, "s": 4974, "text": "(<InterfaceClass __main__.BaseI>, )\nFalse\nTrue\nFalse\nTrue\n" }, { "code": null, "e": 5048, "s": 5033, "text": "python-modules" }, { "code": null, "e": 5055, "s": 5048, "text": "Python" } ]
Java Examples - File Size
How to get a files size in bytes ? This example shows how to get a file's size in bytes by using file.exists() and file.length() method of File class. import java.io.File; public class Main { public static long getFileSize(String filename) { File file = new File(filename); if (!file.exists() || !file.isFile()) { System.out.println("File doesn\'t exist"); return -1; } return file.length(); } public static void main(String[] args) { long size = getFileSize("c:/java.txt"); System.out.println("Filesize in bytes: " + size); } } The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file. File size in bytes: 480 The following is another sample example of files size in java import java.io.File; public class FileSizeExample { public static void main(String[] args) { File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.png"); if(file.exists()) { double bytes = file.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); double gigabytes = (megabytes / 1024); double terabytes = (gigabytes / 1024); double petabytes = (terabytes / 1024); double exabytes = (petabytes / 1024); double zettabytes = (exabytes / 1024); double yottabytes = (zettabytes / 1024); System.out.println("bytes : " + bytes); System.out.println("kilobytes : " + kilobytes); System.out.println("megabytes : " + megabytes); System.out.println("gigabytes : " + gigabytes); System.out.println("terabytes : " + terabytes); System.out.println("petabytes : " + petabytes); System.out.println("exabytes : " + exabytes); System.out.println("zettabytes : " + zettabytes); System.out.println("yottabytes : " + yottabytes); } else { System.out.println("File does not exists!"); } } } The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file. bytes : 6119.0 kilobytes : 5.9755859375 megabytes : 0.005835533142089844 gigabytes : 5.698762834072113E-6 terabytes : 5.565198080148548E-9 petabytes : 5.434763750145066E-12 exabytes : 5.307386474751041E-15 zettabytes : 5.182994604249064E-18 yottabytes : 5.061518168211976E-21 Print Add Notes Bookmark this page
[ { "code": null, "e": 2103, "s": 2068, "text": "How to get a files size in bytes ?" }, { "code": null, "e": 2219, "s": 2103, "text": "This example shows how to get a file's size in bytes by using file.exists() and file.length() method of File class." }, { "code": null, "e": 2664, "s": 2219, "text": "import java.io.File;\n\npublic class Main {\n public static long getFileSize(String filename) {\n File file = new File(filename);\n if (!file.exists() || !file.isFile()) {\n System.out.println(\"File doesn\\'t exist\");\n return -1;\n }\n return file.length();\n }\n public static void main(String[] args) {\n long size = getFileSize(\"c:/java.txt\");\n System.out.println(\"Filesize in bytes: \" + size);\n }\n}" }, { "code": null, "e": 2846, "s": 2664, "text": "The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file." }, { "code": null, "e": 2871, "s": 2846, "text": "File size in bytes: 480\n" }, { "code": null, "e": 2933, "s": 2871, "text": "The following is another sample example of files size in java" }, { "code": null, "e": 4156, "s": 2933, "text": "import java.io.File;\n\npublic class FileSizeExample { \n public static void main(String[] args) { \n File file = new File(\"C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\abc.png\");\n if(file.exists()) { \n double bytes = file.length();\n double kilobytes = (bytes / 1024);\n double megabytes = (kilobytes / 1024);\n double gigabytes = (megabytes / 1024);\n double terabytes = (gigabytes / 1024);\n double petabytes = (terabytes / 1024);\n double exabytes = (petabytes / 1024);\n double zettabytes = (exabytes / 1024);\n double yottabytes = (zettabytes / 1024);\n \n System.out.println(\"bytes : \" + bytes);\n System.out.println(\"kilobytes : \" + kilobytes);\n System.out.println(\"megabytes : \" + megabytes);\n System.out.println(\"gigabytes : \" + gigabytes);\n System.out.println(\"terabytes : \" + terabytes);\n System.out.println(\"petabytes : \" + petabytes);\n System.out.println(\"exabytes : \" + exabytes);\n System.out.println(\"zettabytes : \" + zettabytes);\n System.out.println(\"yottabytes : \" + yottabytes);\n } else {\n System.out.println(\"File does not exists!\");\n }\n }\n}" }, { "code": null, "e": 4338, "s": 4156, "text": "The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file." }, { "code": null, "e": 4615, "s": 4338, "text": "bytes : 6119.0\nkilobytes : 5.9755859375\nmegabytes : 0.005835533142089844\ngigabytes : 5.698762834072113E-6\nterabytes : 5.565198080148548E-9\npetabytes : 5.434763750145066E-12\nexabytes : 5.307386474751041E-15\nzettabytes : 5.182994604249064E-18\nyottabytes : 5.061518168211976E-21\n" }, { "code": null, "e": 4622, "s": 4615, "text": " Print" }, { "code": null, "e": 4633, "s": 4622, "text": " Add Notes" } ]
Can we have variables and methods in an enum in Java?
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can define an enumeration using the keyword enum followed by the name of the enumeration as − enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Enumerations are similar to classes and, you can have variables, methods, and constructors within them. Only concrete methods are allowed in an enumeration. In the following example, we are defining an enumeration with name Vehicles and declaring five constants in it. In addition to it we are having a constructor, instance variable and an instance method. Live Demo enum Vehicles { //Declaring the constants of the enum ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER; //Instance variable of the enum int i; //Constructor of the enum Vehicles() {} //method of the enum public void enumMethod() { System.out.println("This is a method of enumeration"); } } public class EnumExample{ public static void main(String args[]) { Vehicles vehicles[] = Vehicles.values(); for(Vehicles veh: vehicles) { System.out.println(veh); } System.out.println("Value of the variable: "+vehicles[0].i); vehicles[0].enumMethod(); } } ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Value of the variable: 0 This is a method of enumeration In the Following Java example, we are declaring 5 constants with values, we have an instance variable to hold the value(s) of the constant, a parameterized constructor to initialize it and a getter method to get these values. Live Demo import java.util.Scanner; enum Scoters { //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Scoters (int price) { this.price = price; } //Static method to display the price public static void displayPrice(int model){ Scoters constants[] = Scoters.values(); System.out.println("Price of: "+constants[model]+" is "+constants[model].price); } } public class EnumerationExample { public static void main(String args[]) { Scoters constants[] = Scoters.values(); System.out.println("Value of constants: "); for(Scoters d: constants) { System.out.println(d.ordinal()+": "+d); } System.out.println("Select one model: "); Scanner sc = new Scanner(System.in); int model = sc.nextInt(); //Calling the static method of the enum Scoters.displayPrice(model); } } Value of constants: 0: ACTIVA125 1: ACTIVA5G 2: ACCESS125 3: VESPA 4: TVSJUPITER Select one model: 2 Price of: ACCESS125 is 75000
[ { "code": null, "e": 1235, "s": 1062, "text": "Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc." }, { "code": null, "e": 1333, "s": 1235, "text": "You can define an enumeration using the keyword enum followed by the name of the enumeration as −" }, { "code": null, "e": 1413, "s": 1333, "text": "enum Days {\n SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY\n}" }, { "code": null, "e": 1570, "s": 1413, "text": "Enumerations are similar to classes and, you can have variables, methods, and constructors within them. Only concrete methods are allowed in an enumeration." }, { "code": null, "e": 1682, "s": 1570, "text": "In the following example, we are defining an enumeration with name Vehicles and declaring five constants in it." }, { "code": null, "e": 1771, "s": 1682, "text": "In addition to it we are having a constructor, instance variable and an instance method." }, { "code": null, "e": 1782, "s": 1771, "text": " Live Demo" }, { "code": null, "e": 2407, "s": 1782, "text": "enum Vehicles {\n //Declaring the constants of the enum\n ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;\n //Instance variable of the enum\n int i;\n //Constructor of the enum\n Vehicles() {}\n //method of the enum\n public void enumMethod() {\n System.out.println(\"This is a method of enumeration\");\n }\n}\npublic class EnumExample{\n public static void main(String args[]) {\n Vehicles vehicles[] = Vehicles.values();\n for(Vehicles veh: vehicles) {\n System.out.println(veh);\n }\n System.out.println(\"Value of the variable: \"+vehicles[0].i);\n vehicles[0].enumMethod();\n }\n}" }, { "code": null, "e": 2510, "s": 2407, "text": "ACTIVA125\nACTIVA5G\nACCESS125\nVESPA\nTVSJUPITER\nValue of the variable: 0\nThis is a method of enumeration" }, { "code": null, "e": 2736, "s": 2510, "text": "In the Following Java example, we are declaring 5 constants with values, we have an instance variable to hold the value(s) of the constant, a parameterized constructor to initialize it and a getter method to get these values." }, { "code": null, "e": 2747, "s": 2736, "text": " Live Demo" }, { "code": null, "e": 3761, "s": 2747, "text": "import java.util.Scanner;\nenum Scoters {\n //Constants with values\n ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);\n //Instance variable\n private int price;\n //Constructor to initialize the instance variable\n Scoters (int price) {\n this.price = price;\n }\n //Static method to display the price\n public static void displayPrice(int model){\n Scoters constants[] = Scoters.values();\n System.out.println(\"Price of: \"+constants[model]+\" is \"+constants[model].price);\n }\n}\npublic class EnumerationExample {\n public static void main(String args[]) {\n Scoters constants[] = Scoters.values();\n System.out.println(\"Value of constants: \");\n for(Scoters d: constants) {\n System.out.println(d.ordinal()+\": \"+d);\n }\n System.out.println(\"Select one model: \");\n Scanner sc = new Scanner(System.in);\n int model = sc.nextInt();\n //Calling the static method of the enum\n Scoters.displayPrice(model);\n }\n}" }, { "code": null, "e": 3891, "s": 3761, "text": "Value of constants:\n0: ACTIVA125\n1: ACTIVA5G\n2: ACCESS125\n3: VESPA\n4: TVSJUPITER\nSelect one model:\n2\nPrice of: ACCESS125 is 75000" } ]
Ruby on Rails - Introduction
Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails. Ruby is the successful combination of − Smalltalk's conceptual elegance, Python's ease of use and learning, and Perl's pragmatism. Ruby is − A high-level programming language. Interpreted like Perl, Python, Tcl/TK. Object-oriented like Smalltalk, Eiffel, Ada, Java. Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity − Easy to learn Open source (very liberal license) Rich libraries Very easy to extend Truly object-oriented Less coding with fewer bugs Helpful community Although we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby − Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++. Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++. Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads. Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads. Here is a sample Ruby code to print "Hello Ruby" # The Hello Class class Hello def initialize( name ) @name = name.capitalize end def salute puts "Hello #{@name}!" end end # Create a new object h = Hello.new("Ruby") # Output "Hello Ruby!" h.salute Output − This will produce the following result − Hello Ruby! Ruby provides a program called ERB (Embedded Ruby), written by Seki Masatoshi. ERB allows you to put Ruby codes inside an HTML file. ERB reads along, word for word, and then at a certain point, when it encounters a Ruby code embedded in the document, it starts executing the Ruby code. You need to know only two things to prepare an ERB document − If you want some Ruby code executed, enclose it between <% and %>. If you want some Ruby code executed, enclose it between <% and %>. If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>. If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>. Here's an example. Save the code in erbdemo.rb file. Note that a Ruby file will have an extension .rb − <% page_title = "Demonstration of ERB" %> <% salutation = "Dear programmer," %> <html> <head> <title><%= page_title %></title> </head> <body> <p><%= salutation %></p> <p>This is an example of how ERB fills out a template.</p> </body> </html> Now, run the program using the command-line utility erb. tp> erb erbdemo.rb This will produce the following result − <html> <head> <title>Demonstration of ERb</title> </head> <body> <p>Dear programmer,</p> <p>This is an example of how ERb fills out a template.</p> </body> </html> An extremely productive web-application framework. An extremely productive web-application framework. Written in Ruby by David Heinemeier Hansson. Written in Ruby by David Heinemeier Hansson. You could develop a web application at least ten times faster with Rails than you could with a typical Java framework. You could develop a web application at least ten times faster with Rails than you could with a typical Java framework. An open source Ruby framework for developing database-backed web applications. An open source Ruby framework for developing database-backed web applications. Configure your code with Database Schema. Configure your code with Database Schema. No compilation phase required. No compilation phase required. Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern. Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern. Being a full-stack framework means all the layers are built to work seamlessly together with less code. Being a full-stack framework means all the layers are built to work seamlessly together with less code. Requires fewer lines of code than other frameworks. Requires fewer lines of code than other frameworks. Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions. Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions. Your application code and your running database already contain everything that Rails needs to know! Your application code and your running database already contain everything that Rails needs to know! Rails is packed with features that make you more productive, with many of the following features building on one other. Where other frameworks use extensive code generation from scratch, Rail framework uses Metaprogramming techniques to write programs. Ruby is one of the best languages for Metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on Metaprogramming for the heavy lifting. Rails introduces the Active Record framework, which saves objects into the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming. Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn't need much configuration. You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need. Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility. Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run. Print Add Notes Bookmark this page
[ { "code": null, "e": 2198, "s": 2103, "text": "Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails." }, { "code": null, "e": 2238, "s": 2198, "text": "Ruby is the successful combination of −" }, { "code": null, "e": 2271, "s": 2238, "text": "Smalltalk's conceptual elegance," }, { "code": null, "e": 2310, "s": 2271, "text": "Python's ease of use and learning, and" }, { "code": null, "e": 2329, "s": 2310, "text": "Perl's pragmatism." }, { "code": null, "e": 2339, "s": 2329, "text": "Ruby is −" }, { "code": null, "e": 2374, "s": 2339, "text": "A high-level programming language." }, { "code": null, "e": 2413, "s": 2374, "text": "Interpreted like Perl, Python, Tcl/TK." }, { "code": null, "e": 2464, "s": 2413, "text": "Object-oriented like Smalltalk, Eiffel, Ada, Java." }, { "code": null, "e": 2606, "s": 2464, "text": "Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity −" }, { "code": null, "e": 2620, "s": 2606, "text": "Easy to learn" }, { "code": null, "e": 2655, "s": 2620, "text": "Open source (very liberal license)" }, { "code": null, "e": 2670, "s": 2655, "text": "Rich libraries" }, { "code": null, "e": 2690, "s": 2670, "text": "Very easy to extend" }, { "code": null, "e": 2712, "s": 2690, "text": "Truly object-oriented" }, { "code": null, "e": 2740, "s": 2712, "text": "Less coding with fewer bugs" }, { "code": null, "e": 2758, "s": 2740, "text": "Helpful community" }, { "code": null, "e": 2892, "s": 2758, "text": "Although we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby −" }, { "code": null, "e": 3063, "s": 2892, "text": "Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++." }, { "code": null, "e": 3234, "s": 3063, "text": "Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++." }, { "code": null, "e": 3365, "s": 3234, "text": "Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads." }, { "code": null, "e": 3496, "s": 3365, "text": "Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads." }, { "code": null, "e": 3545, "s": 3496, "text": "Here is a sample Ruby code to print \"Hello Ruby\"" }, { "code": null, "e": 3779, "s": 3545, "text": "# The Hello Class\nclass Hello\n \n def initialize( name )\n @name = name.capitalize\n end\n\n def salute\n puts \"Hello #{@name}!\"\n end\n \nend\n\n# Create a new object\nh = Hello.new(\"Ruby\")\n\n# Output \"Hello Ruby!\"\nh.salute" }, { "code": null, "e": 3829, "s": 3779, "text": "Output − This will produce the following result −" }, { "code": null, "e": 3842, "s": 3829, "text": "Hello Ruby!\n" }, { "code": null, "e": 4128, "s": 3842, "text": "Ruby provides a program called ERB (Embedded Ruby), written by Seki Masatoshi. ERB allows you to put Ruby codes inside an HTML file. ERB reads along, word for word, and then at a certain point, when it encounters a Ruby code embedded in the document, it starts executing the Ruby code." }, { "code": null, "e": 4190, "s": 4128, "text": "You need to know only two things to prepare an ERB document −" }, { "code": null, "e": 4257, "s": 4190, "text": "If you want some Ruby code executed, enclose it between <% and %>." }, { "code": null, "e": 4324, "s": 4257, "text": "If you want some Ruby code executed, enclose it between <% and %>." }, { "code": null, "e": 4450, "s": 4324, "text": "If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>." }, { "code": null, "e": 4576, "s": 4450, "text": "If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>." }, { "code": null, "e": 4680, "s": 4576, "text": "Here's an example. Save the code in erbdemo.rb file. Note that a Ruby file will have an extension .rb −" }, { "code": null, "e": 4958, "s": 4680, "text": "<% page_title = \"Demonstration of ERB\" %>\n<% salutation = \"Dear programmer,\" %>\n\n<html>\n\n <head>\n <title><%= page_title %></title>\n </head>\n\t\n <body>\n <p><%= salutation %></p>\n <p>This is an example of how ERB fills out a template.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 5015, "s": 4958, "text": "Now, run the program using the command-line utility erb." }, { "code": null, "e": 5035, "s": 5015, "text": "tp> erb erbdemo.rb\n" }, { "code": null, "e": 5076, "s": 5035, "text": "This will produce the following result −" }, { "code": null, "e": 5276, "s": 5076, "text": "<html>\n\n <head>\n <title>Demonstration of ERb</title>\n </head>\n\t\n <body>\n <p>Dear programmer,</p>\n <p>This is an example of how ERb fills out a template.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 5327, "s": 5276, "text": "An extremely productive web-application framework." }, { "code": null, "e": 5378, "s": 5327, "text": "An extremely productive web-application framework." }, { "code": null, "e": 5423, "s": 5378, "text": "Written in Ruby by David Heinemeier Hansson." }, { "code": null, "e": 5468, "s": 5423, "text": "Written in Ruby by David Heinemeier Hansson." }, { "code": null, "e": 5587, "s": 5468, "text": "You could develop a web application at least ten times faster with Rails than you could with a typical Java framework." }, { "code": null, "e": 5706, "s": 5587, "text": "You could develop a web application at least ten times faster with Rails than you could with a typical Java framework." }, { "code": null, "e": 5785, "s": 5706, "text": "An open source Ruby framework for developing database-backed web applications." }, { "code": null, "e": 5864, "s": 5785, "text": "An open source Ruby framework for developing database-backed web applications." }, { "code": null, "e": 5906, "s": 5864, "text": "Configure your code with Database Schema." }, { "code": null, "e": 5948, "s": 5906, "text": "Configure your code with Database Schema." }, { "code": null, "e": 5979, "s": 5948, "text": "No compilation phase required." }, { "code": null, "e": 6010, "s": 5979, "text": "No compilation phase required." }, { "code": null, "e": 6123, "s": 6010, "text": "Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern." }, { "code": null, "e": 6236, "s": 6123, "text": "Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern." }, { "code": null, "e": 6340, "s": 6236, "text": "Being a full-stack framework means all the layers are built to work seamlessly together with less code." }, { "code": null, "e": 6444, "s": 6340, "text": "Being a full-stack framework means all the layers are built to work seamlessly together with less code." }, { "code": null, "e": 6496, "s": 6444, "text": "Requires fewer lines of code than other frameworks." }, { "code": null, "e": 6548, "s": 6496, "text": "Requires fewer lines of code than other frameworks." }, { "code": null, "e": 6649, "s": 6548, "text": "Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions." }, { "code": null, "e": 6750, "s": 6649, "text": "Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions." }, { "code": null, "e": 6851, "s": 6750, "text": "Your application code and your running database already contain everything that Rails needs to know!" }, { "code": null, "e": 6952, "s": 6851, "text": "Your application code and your running database already contain everything that Rails needs to know!" }, { "code": null, "e": 7072, "s": 6952, "text": "Rails is packed with features that make you more productive, with many of the following features building on one other." }, { "code": null, "e": 7392, "s": 7072, "text": "Where other frameworks use extensive code generation from scratch, Rail framework uses Metaprogramming techniques to write programs. Ruby is one of the best languages for Metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on Metaprogramming for the heavy lifting." }, { "code": null, "e": 7637, "s": 7392, "text": "Rails introduces the Active Record framework, which saves objects into the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming." }, { "code": null, "e": 7821, "s": 7637, "text": "Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn't need much configuration." }, { "code": null, "e": 8035, "s": 7821, "text": "You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need." }, { "code": null, "e": 8275, "s": 8035, "text": "Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility." }, { "code": null, "e": 8526, "s": 8275, "text": "Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run." }, { "code": null, "e": 8533, "s": 8526, "text": " Print" }, { "code": null, "e": 8544, "s": 8533, "text": " Add Notes" } ]
Find the size of a list - Python - GeeksforGeeks
17 May, 2020 In Python, a list is a collection data type that can store elements in an ordered manner and can also have duplicate elements. The size of a list means the amount of memory (in bytes) occupied by a list object. In this article, we will learn various ways to get the size of a python list. 1.Using getsizeof() function: The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example. Example 1: import sys # sample listslist1 = [1, 2, 3, 5]list2 = ["GeeksForGeeks", "Data Structure", "Algorithms"]list3 = [1, "Geeks", 2, "For", 3, "Geeks"] # print the sizes of sample listsprint("Size of list1: " + str(sys.getsizeof(list1)) + "bytes")print("Size of list2: " + str(sys.getsizeof(list2)) + "bytes")print("Size of list3: " + str(sys.getsizeof(list3)) + "bytes") Output: Size of list1: 96bytes Size of list1: 88bytes Size of list1: 112bytes Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used. 1.Using inbuilt __sizeof__() method: Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2: # sample listslist1 = [1, 2, 3, 5]list2 = ["GeeksForGeeks", "Data Structure", "Algorithms"]list3 = [1, "Geeks", 2, "For", 3, "Geeks"] # print the sizes of the sample listsprint("Size of list1: " + str(list1.__sizeof__()) + "bytes")print("Size of list2: " + str(list2.__sizeof__()) + "bytes")print("Size of list3: " + str(list3.__sizeof__()) + "bytes") Output: Size of list1: 72bytes Size of list1: 64bytes Size of list1: 88bytes Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n17 May, 2020" }, { "code": null, "e": 24581, "s": 24292, "text": "In Python, a list is a collection data type that can store elements in an ordered manner and can also have duplicate elements. The size of a list means the amount of memory (in bytes) occupied by a list object. In this article, we will learn various ways to get the size of a python list." }, { "code": null, "e": 24611, "s": 24581, "text": "1.Using getsizeof() function:" }, { "code": null, "e": 24718, "s": 24611, "text": "The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example." }, { "code": null, "e": 24729, "s": 24718, "text": "Example 1:" }, { "code": "import sys # sample listslist1 = [1, 2, 3, 5]list2 = [\"GeeksForGeeks\", \"Data Structure\", \"Algorithms\"]list3 = [1, \"Geeks\", 2, \"For\", 3, \"Geeks\"] # print the sizes of sample listsprint(\"Size of list1: \" + str(sys.getsizeof(list1)) + \"bytes\")print(\"Size of list2: \" + str(sys.getsizeof(list2)) + \"bytes\")print(\"Size of list3: \" + str(sys.getsizeof(list3)) + \"bytes\")", "e": 25096, "s": 24729, "text": null }, { "code": null, "e": 25104, "s": 25096, "text": "Output:" }, { "code": null, "e": 25174, "s": 25104, "text": "Size of list1: 96bytes\nSize of list1: 88bytes\nSize of list1: 112bytes" }, { "code": null, "e": 25438, "s": 25174, "text": "Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used." }, { "code": null, "e": 25475, "s": 25438, "text": "1.Using inbuilt __sizeof__() method:" }, { "code": null, "e": 25663, "s": 25475, "text": "Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:" }, { "code": "# sample listslist1 = [1, 2, 3, 5]list2 = [\"GeeksForGeeks\", \"Data Structure\", \"Algorithms\"]list3 = [1, \"Geeks\", 2, \"For\", 3, \"Geeks\"] # print the sizes of the sample listsprint(\"Size of list1: \" + str(list1.__sizeof__()) + \"bytes\")print(\"Size of list2: \" + str(list2.__sizeof__()) + \"bytes\")print(\"Size of list3: \" + str(list3.__sizeof__()) + \"bytes\")", "e": 26016, "s": 25663, "text": null }, { "code": null, "e": 26024, "s": 26016, "text": "Output:" }, { "code": null, "e": 26093, "s": 26024, "text": "Size of list1: 72bytes\nSize of list1: 64bytes\nSize of list1: 88bytes" }, { "code": null, "e": 26114, "s": 26093, "text": "Python list-programs" }, { "code": null, "e": 26121, "s": 26114, "text": "Python" }, { "code": null, "e": 26137, "s": 26121, "text": "Python Programs" }, { "code": null, "e": 26235, "s": 26137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26244, "s": 26235, "text": "Comments" }, { "code": null, "e": 26257, "s": 26244, "text": "Old Comments" }, { "code": null, "e": 26289, "s": 26257, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26345, "s": 26289, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26400, "s": 26345, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26442, "s": 26400, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26484, "s": 26442, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26506, "s": 26484, "text": "Defaultdict in Python" }, { "code": null, "e": 26552, "s": 26506, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26591, "s": 26552, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26629, "s": 26591, "text": "Python | Convert a list to dictionary" } ]
Traversing a map (or unordered_map) in C++ STL
Here we will see the map container and its use in C++. The maps are defined as associative containers that store elements in a hash-mapped fashion. Each element is associated with a key and value. No two mapped values can have identical keys. These are some fundamental methods that are present inside the map container in C++. begin(): This returns an iterator to the first element in the map. end()− This returns an iterator to the theoretical element that follows last element in the map. size() − This returns the number of elements in the map. max_size() − This returns the maximum number of elements that the map can hold. empty() − This returns whether the map is empty or not. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; int main() { int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 }; int num = sizeof(A) / sizeof(A[0]); map<int, int> my_map; for (int p = 0; p < num; p++) my_map[A[p]]++; cout <<"Item Frequency"<< endl; for (auto p : my_map) cout << p.first <<" : "<< p.second << endl; } Item Frequency 2 : 4 3 : 1 4 : 2 5 : 1 The unordered_map is another type of map container present in C++ STL. This is an associated container that collects or stores elements formed by combination of key value pair. The key is used to uniquely identify the value. In this case, both key and value can be of any type predefined or user-defined. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; int main() { int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 }; int num = sizeof(A) / sizeof(A[0]); unordered_map<int, int> my_map; for (int p = 0; p < num; p++) my_map[A[p]]++; cout <<Item Frequency"<< endl; for (auto p : my_map) cout << p.first <<" : "<< p.second << endl; } Item Frequency 5 : 1 4 : 2 2 : 4 3 : 1
[ { "code": null, "e": 1390, "s": 1062, "text": "Here we will see the map container and its use in C++. The maps are defined as associative containers that store elements in a hash-mapped fashion. Each element is associated with a key and value. No two mapped values can have identical keys. These are some fundamental methods that are present inside the map container in C++." }, { "code": null, "e": 1457, "s": 1390, "text": "begin(): This returns an iterator to the first element in the map." }, { "code": null, "e": 1554, "s": 1457, "text": "end()− This returns an iterator to the theoretical element that follows last element in the map." }, { "code": null, "e": 1611, "s": 1554, "text": "size() − This returns the number of elements in the map." }, { "code": null, "e": 1691, "s": 1611, "text": "max_size() − This returns the maximum number of elements that the map can hold." }, { "code": null, "e": 1747, "s": 1691, "text": "empty() − This returns whether the map is empty or not." }, { "code": null, "e": 1817, "s": 1747, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1828, "s": 1817, "text": " Live Demo" }, { "code": null, "e": 2159, "s": 1828, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 };\n int num = sizeof(A) / sizeof(A[0]);\n map<int, int> my_map;\n for (int p = 0; p < num; p++)\n my_map[A[p]]++;\n cout <<\"Item Frequency\"<< endl;\n for (auto p : my_map)\n cout << p.first <<\" : \"<< p.second << endl;\n}" }, { "code": null, "e": 2198, "s": 2159, "text": "Item Frequency\n2 : 4\n3 : 1\n4 : 2\n5 : 1" }, { "code": null, "e": 2503, "s": 2198, "text": "The unordered_map is another type of map container present in C++ STL. This is an associated container that collects or stores elements formed by combination of key value pair. The key is used to uniquely identify the value. In this case, both key and value can be of any type predefined or user-defined." }, { "code": null, "e": 2573, "s": 2503, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2584, "s": 2573, "text": " Live Demo" }, { "code": null, "e": 2924, "s": 2584, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n int A[] = { 2, 2, 3, 2, 2, 4, 5, 4 };\n int num = sizeof(A) / sizeof(A[0]);\n unordered_map<int, int> my_map;\n for (int p = 0; p < num; p++)\n my_map[A[p]]++;\n cout <<Item Frequency\"<< endl;\n for (auto p : my_map)\n cout << p.first <<\" : \"<< p.second << endl;\n}" }, { "code": null, "e": 2963, "s": 2924, "text": "Item Frequency\n5 : 1\n4 : 2\n2 : 4\n3 : 1" } ]
Polynomial Regression — Gradient Descent from Scratch | by Mark Garvey | Towards Data Science
Gradient descent is an important algorithm to understand, as it underpins many of the more advanced algorithms used in Machine Learning and Deep Learning. Getting to grips with the inner workings of gradient descent will therefore be of great benefit to anyone who plans on exploring ML algorithms further. The best way to learn is by doing, so in this article I will be walking through the steps of how the gradient descent process works, without using ML libraries such as scikit-learn for example. In day-to-day work, it is of course quicker and neater to make use of such libraries, but regarding the learning process I have found the exercise of implementing by hand to be invaluable for this particular algorithm. The goal of gradient descent is to minimize the error of a model’s prediction, relative to the original data. In this article’s context, we will be looking at a second-degree polynomial model, also known as a quadratic equation: Second degree polynomials tend to look something like this, when plotted: We’re specifically looking at polynomial regression here, where the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial in x. Simply put, the coefficients of our second degree polynomial a,b and c will be estimated, evaluated and altered until we can accurately fit a line to the input x data. Gradient descent is the optimization step in this process that alters and improves on the values of these coefficients. We will now look at how to create and plot such a curve, and then build an initial model to fit to this data, which we will then optimize and improve on using gradient descent. If we can get a model that accurately describes the data, the hope is that it should be able to accurately predict the y values of another set of x values. We can start be choosing coefficients for a second degree polynomial equation (ax2+bx+c) that will distribute the data we will try to model: These will be the coefficients for our base/ground truth model we hope to get our predictive model as close as possible to. Next, we need an evaluation function for a second degree polynomial, which, given a set of coefficients and a given input x returns the corresponding y: We can see it in action when x=3: 7 Define some x data (inputs) we hope to predict y (outputs) of: This is good, but we could improve on this by making things more realistic. You can add noise or ‘jitter’ to the values so they can resemble real-world data: Test it out: 7Should get value in the range 3 - 116.233537936801398 This updated function will take in the inputs for the second-order polynomial and a jitter value j to add noise to this input, to give us a more realistic output than just a perfect curve: When we build our predictive model, and optimize it with gradient descent, hopefully we will get as close to these values as possible. The first pass at modelling involves generating and storing random coefficients for a second degree polynomial (y=ax2 +bx+c). This will be our initial model which will most likely not be that accurate, which we will aim to improve upon until it fits the data well enough. (7, 6, 3) Inspect this model’s accuracy by calculating the predicted output values from your input values: It is evident from the above plot that this new model with random coefficients does not fit our data all that well. To get a quantifiable measure of how incorrect it is, we calculate the Mean Squared Error loss for the model. This is the mean value of the sum of the squared differences between the actual and predicted outputs: 47922.39790821987 Quite a large number. Let’s now see if we can improve on this fairly high loss metric by optimizing the model with gradient descent. We wish to improve our model. Therefore we want to alter its coefficients a, b and c to decrease the error. Therefore we require knowledge about how each coefficient affects the error. This is achieved by calculating the partial derivative of the loss function with respect to each of the individual coefficients. In this case, we are using MSE as our loss function — this is the function we wish to calculate partial derivatives for: With output predictions for our model as: Loss can therefore be reformulated as: In this specific case, our partial derivatives for that loss function are the following: If you calculate the value of each derivative, you will obtain the gradient for each coefficient. These are the values that give you the slope of the loss function with regards to each specific coefficient. They indicate whether you should increase or decrease it to reduce the loss, and also by how much it should be safe to do so. Given coefficients a, b and c, calculated gradients ga, gb and gc and a learning rate lr, typically one would update the coefficients so that their new, updated values are defined as below: Once you have applied that new model to the data, your loss should have decreased. We need a gradient calculation function which, given a second degree polynomial’s coefficients, as well as a set of inputs x and a corresponding set of actual outputs y will return the respective gradients for each coefficient. We’re now going to: Use the above function to calculate gradients for our poor-performing random model, Adjust the model’s coefficients accordingly, Verify that the model’s loss is now smaller — that G.D. has worked! Let’s set an initial learning rate to experiment with. This should be kept small to avoid the missing the global minimum, but not so small that it takes forever or gets stuck in a local minimum. lr = 0.0001 is a good place to start. New model coeffs: 5.290395171471687 5.903335222089396 2.9704266522693037Now have smaller model loss: 23402.14716735533 vs 47922.39790821987 Visualize this improvement by plotting the training data, original random model and updated lower-loss model together: We’re almost ready. The last step will be to perform gradient descent iteratively over a number of epochs (cycles or iterations.) With every epoch we hope to see an improvement in the form of lowered loss, and better model-fitting to the original data. Let’s improve on the calc_gradient_2nd_poly function from above, to make it more usable for an iterative gradient descent process: This will be called as part of the gradient_descent function: Finally, let’s train for 1500 epochs and see if our model has learned anything: This trained model is showing vast improvements after it’s full training cycle. We can examine further by inspecting its final predicted coefficients a,b and c: Final Coefficients predicted: (2.0133237089326155, -4.9936501002139275, 3.1596042252126195)Original Coefficients: [2, -5, 4] Not too far off! A big improvement over the initial random model. Looking at the plot of the loss reduction over training offers further insights: We observe that the model loss reached close to zero, to give us our more accurate coefficients. We can also see there was no major improvement in loss after about 400 epochs — definitely no need for 1500 epochs. An alternative strategy would be to add some kind of condition to the training step that stops training when a certain minimum loss threshold has been reached. This would prevent excessive training and potential over-fitting for the model. I hope you enjoyed this dive into gradient descent for polynomial regression. Certain concepts can be daunting to understand at first glance, but over time we become familiar with the ‘nuts and bolts’ of a problem if we stick at it long enough. I found this was certainly the case for me with this exercise, and feel it was a worthwhile learning experience overall. If you liked this story, please consider following me on Medium. You can find more on https://mark-garvey.com/ Find me on LinkedIn: https://www.linkedin.com/in/mark-garvey/
[ { "code": null, "e": 479, "s": 172, "text": "Gradient descent is an important algorithm to understand, as it underpins many of the more advanced algorithms used in Machine Learning and Deep Learning. Getting to grips with the inner workings of gradient descent will therefore be of great benefit to anyone who plans on exploring ML algorithms further." }, { "code": null, "e": 892, "s": 479, "text": "The best way to learn is by doing, so in this article I will be walking through the steps of how the gradient descent process works, without using ML libraries such as scikit-learn for example. In day-to-day work, it is of course quicker and neater to make use of such libraries, but regarding the learning process I have found the exercise of implementing by hand to be invaluable for this particular algorithm." }, { "code": null, "e": 1121, "s": 892, "text": "The goal of gradient descent is to minimize the error of a model’s prediction, relative to the original data. In this article’s context, we will be looking at a second-degree polynomial model, also known as a quadratic equation:" }, { "code": null, "e": 1195, "s": 1121, "text": "Second degree polynomials tend to look something like this, when plotted:" }, { "code": null, "e": 1673, "s": 1195, "text": "We’re specifically looking at polynomial regression here, where the relationship between the independent variable x and the dependent variable y is modeled as an nth degree polynomial in x. Simply put, the coefficients of our second degree polynomial a,b and c will be estimated, evaluated and altered until we can accurately fit a line to the input x data. Gradient descent is the optimization step in this process that alters and improves on the values of these coefficients." }, { "code": null, "e": 2006, "s": 1673, "text": "We will now look at how to create and plot such a curve, and then build an initial model to fit to this data, which we will then optimize and improve on using gradient descent. If we can get a model that accurately describes the data, the hope is that it should be able to accurately predict the y values of another set of x values." }, { "code": null, "e": 2147, "s": 2006, "text": "We can start be choosing coefficients for a second degree polynomial equation (ax2+bx+c) that will distribute the data we will try to model:" }, { "code": null, "e": 2424, "s": 2147, "text": "These will be the coefficients for our base/ground truth model we hope to get our predictive model as close as possible to. Next, we need an evaluation function for a second degree polynomial, which, given a set of coefficients and a given input x returns the corresponding y:" }, { "code": null, "e": 2458, "s": 2424, "text": "We can see it in action when x=3:" }, { "code": null, "e": 2460, "s": 2458, "text": "7" }, { "code": null, "e": 2523, "s": 2460, "text": "Define some x data (inputs) we hope to predict y (outputs) of:" }, { "code": null, "e": 2681, "s": 2523, "text": "This is good, but we could improve on this by making things more realistic. You can add noise or ‘jitter’ to the values so they can resemble real-world data:" }, { "code": null, "e": 2694, "s": 2681, "text": "Test it out:" }, { "code": null, "e": 2749, "s": 2694, "text": "7Should get value in the range 3 - 116.233537936801398" }, { "code": null, "e": 2938, "s": 2749, "text": "This updated function will take in the inputs for the second-order polynomial and a jitter value j to add noise to this input, to give us a more realistic output than just a perfect curve:" }, { "code": null, "e": 3073, "s": 2938, "text": "When we build our predictive model, and optimize it with gradient descent, hopefully we will get as close to these values as possible." }, { "code": null, "e": 3345, "s": 3073, "text": "The first pass at modelling involves generating and storing random coefficients for a second degree polynomial (y=ax2 +bx+c). This will be our initial model which will most likely not be that accurate, which we will aim to improve upon until it fits the data well enough." }, { "code": null, "e": 3355, "s": 3345, "text": "(7, 6, 3)" }, { "code": null, "e": 3452, "s": 3355, "text": "Inspect this model’s accuracy by calculating the predicted output values from your input values:" }, { "code": null, "e": 3781, "s": 3452, "text": "It is evident from the above plot that this new model with random coefficients does not fit our data all that well. To get a quantifiable measure of how incorrect it is, we calculate the Mean Squared Error loss for the model. This is the mean value of the sum of the squared differences between the actual and predicted outputs:" }, { "code": null, "e": 3799, "s": 3781, "text": "47922.39790821987" }, { "code": null, "e": 3932, "s": 3799, "text": "Quite a large number. Let’s now see if we can improve on this fairly high loss metric by optimizing the model with gradient descent." }, { "code": null, "e": 4246, "s": 3932, "text": "We wish to improve our model. Therefore we want to alter its coefficients a, b and c to decrease the error. Therefore we require knowledge about how each coefficient affects the error. This is achieved by calculating the partial derivative of the loss function with respect to each of the individual coefficients." }, { "code": null, "e": 4367, "s": 4246, "text": "In this case, we are using MSE as our loss function — this is the function we wish to calculate partial derivatives for:" }, { "code": null, "e": 4409, "s": 4367, "text": "With output predictions for our model as:" }, { "code": null, "e": 4448, "s": 4409, "text": "Loss can therefore be reformulated as:" }, { "code": null, "e": 4537, "s": 4448, "text": "In this specific case, our partial derivatives for that loss function are the following:" }, { "code": null, "e": 4635, "s": 4537, "text": "If you calculate the value of each derivative, you will obtain the gradient for each coefficient." }, { "code": null, "e": 4744, "s": 4635, "text": "These are the values that give you the slope of the loss function with regards to each specific coefficient." }, { "code": null, "e": 4870, "s": 4744, "text": "They indicate whether you should increase or decrease it to reduce the loss, and also by how much it should be safe to do so." }, { "code": null, "e": 5060, "s": 4870, "text": "Given coefficients a, b and c, calculated gradients ga, gb and gc and a learning rate lr, typically one would update the coefficients so that their new, updated values are defined as below:" }, { "code": null, "e": 5143, "s": 5060, "text": "Once you have applied that new model to the data, your loss should have decreased." }, { "code": null, "e": 5371, "s": 5143, "text": "We need a gradient calculation function which, given a second degree polynomial’s coefficients, as well as a set of inputs x and a corresponding set of actual outputs y will return the respective gradients for each coefficient." }, { "code": null, "e": 5391, "s": 5371, "text": "We’re now going to:" }, { "code": null, "e": 5475, "s": 5391, "text": "Use the above function to calculate gradients for our poor-performing random model," }, { "code": null, "e": 5520, "s": 5475, "text": "Adjust the model’s coefficients accordingly," }, { "code": null, "e": 5588, "s": 5520, "text": "Verify that the model’s loss is now smaller — that G.D. has worked!" }, { "code": null, "e": 5821, "s": 5588, "text": "Let’s set an initial learning rate to experiment with. This should be kept small to avoid the missing the global minimum, but not so small that it takes forever or gets stuck in a local minimum. lr = 0.0001 is a good place to start." }, { "code": null, "e": 5961, "s": 5821, "text": "New model coeffs: 5.290395171471687 5.903335222089396 2.9704266522693037Now have smaller model loss: 23402.14716735533 vs 47922.39790821987" }, { "code": null, "e": 6080, "s": 5961, "text": "Visualize this improvement by plotting the training data, original random model and updated lower-loss model together:" }, { "code": null, "e": 6333, "s": 6080, "text": "We’re almost ready. The last step will be to perform gradient descent iteratively over a number of epochs (cycles or iterations.) With every epoch we hope to see an improvement in the form of lowered loss, and better model-fitting to the original data." }, { "code": null, "e": 6464, "s": 6333, "text": "Let’s improve on the calc_gradient_2nd_poly function from above, to make it more usable for an iterative gradient descent process:" }, { "code": null, "e": 6526, "s": 6464, "text": "This will be called as part of the gradient_descent function:" }, { "code": null, "e": 6606, "s": 6526, "text": "Finally, let’s train for 1500 epochs and see if our model has learned anything:" }, { "code": null, "e": 6767, "s": 6606, "text": "This trained model is showing vast improvements after it’s full training cycle. We can examine further by inspecting its final predicted coefficients a,b and c:" }, { "code": null, "e": 6892, "s": 6767, "text": "Final Coefficients predicted: (2.0133237089326155, -4.9936501002139275, 3.1596042252126195)Original Coefficients: [2, -5, 4]" }, { "code": null, "e": 7039, "s": 6892, "text": "Not too far off! A big improvement over the initial random model. Looking at the plot of the loss reduction over training offers further insights:" }, { "code": null, "e": 7492, "s": 7039, "text": "We observe that the model loss reached close to zero, to give us our more accurate coefficients. We can also see there was no major improvement in loss after about 400 epochs — definitely no need for 1500 epochs. An alternative strategy would be to add some kind of condition to the training step that stops training when a certain minimum loss threshold has been reached. This would prevent excessive training and potential over-fitting for the model." }, { "code": null, "e": 7858, "s": 7492, "text": "I hope you enjoyed this dive into gradient descent for polynomial regression. Certain concepts can be daunting to understand at first glance, but over time we become familiar with the ‘nuts and bolts’ of a problem if we stick at it long enough. I found this was certainly the case for me with this exercise, and feel it was a worthwhile learning experience overall." }, { "code": null, "e": 7969, "s": 7858, "text": "If you liked this story, please consider following me on Medium. You can find more on https://mark-garvey.com/" } ]
Python Program to swap the First and the Last Character of a string - GeeksforGeeks
25 Nov, 2020 Given a String. The task is to swap the first and the last character of the string. Examples: Input: GeeksForGeeks Output: seeksForGeekG Input: Python Output: nythoP Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follow the below steps to swap characters – We initialize a variable start, which stores the first character of the string (string[0])We initialize another variable end that stores the last character (string[-1])Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character.Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it. We initialize a variable start, which stores the first character of the string (string[0]) We initialize another variable end that stores the last character (string[-1]) Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character. Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it. Below is the implementation. Python3 def swap(string): # storing the first character start = string[0] # storing the last character end = string[-1] swapped_string = end + string[1:-1] + start print(swapped_string) # Driver Codeswap("GeeksforGeeks")swap("Python") Output: seeksforGeekG nythoP Python string-programs 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? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects 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": 26112, "s": 26084, "text": "\n25 Nov, 2020" }, { "code": null, "e": 26196, "s": 26112, "text": "Given a String. The task is to swap the first and the last character of the string." }, { "code": null, "e": 26206, "s": 26196, "text": "Examples:" }, { "code": null, "e": 26280, "s": 26206, "text": "Input: GeeksForGeeks\nOutput: seeksForGeekG\n \nInput: Python\nOutput: nythoP" }, { "code": null, "e": 26503, "s": 26280, "text": "Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follow the below steps to swap characters –" }, { "code": null, "e": 26960, "s": 26503, "text": "We initialize a variable start, which stores the first character of the string (string[0])We initialize another variable end that stores the last character (string[-1])Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character.Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it." }, { "code": null, "e": 27051, "s": 26960, "text": "We initialize a variable start, which stores the first character of the string (string[0])" }, { "code": null, "e": 27130, "s": 27051, "text": "We initialize another variable end that stores the last character (string[-1])" }, { "code": null, "e": 27265, "s": 27130, "text": "Then we will use string slicing, string[1:-1], this will access all the characters from the 2nd position excluding the last character." }, { "code": null, "e": 27420, "s": 27265, "text": "Then we add these three as required forming a new string that has the first and last characters of the original string swapped. And then we will print it." }, { "code": null, "e": 27449, "s": 27420, "text": "Below is the implementation." }, { "code": null, "e": 27457, "s": 27449, "text": "Python3" }, { "code": "def swap(string): # storing the first character start = string[0] # storing the last character end = string[-1] swapped_string = end + string[1:-1] + start print(swapped_string) # Driver Codeswap(\"GeeksforGeeks\")swap(\"Python\")", "e": 27725, "s": 27457, "text": null }, { "code": null, "e": 27733, "s": 27725, "text": "Output:" }, { "code": null, "e": 27754, "s": 27733, "text": "seeksforGeekG\nnythoP" }, { "code": null, "e": 27777, "s": 27754, "text": "Python string-programs" }, { "code": null, "e": 27784, "s": 27777, "text": "Python" }, { "code": null, "e": 27800, "s": 27784, "text": "Python Programs" }, { "code": null, "e": 27898, "s": 27800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27930, "s": 27898, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27972, "s": 27930, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28014, "s": 27972, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28070, "s": 28014, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28097, "s": 28070, "text": "Python Classes and Objects" }, { "code": null, "e": 28119, "s": 28097, "text": "Defaultdict in Python" }, { "code": null, "e": 28158, "s": 28119, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28204, "s": 28158, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28242, "s": 28204, "text": "Python | Convert a list to dictionary" } ]
What is class Invariant - GeeksforGeeks
22 Jun, 2021 Overview :An invariant in Object-Oriented programming refers to some set of conditions or assertions that need to hold throughout the life of an object of a class. These assertions need to hold from the time the constructor is called for an object, at the end of each member (mutator) method call to the end of the destructor call. These conditions verify that an object’s behavior is justified during its lifetime and that the object maintains its well-defined state as intended. The invariant, however, need not hold true during the execution of a mutator method but must hold true at the end of it. Example :Creating a snake game –Let’s say we were creating a snake game and our snake had the ability to teleport itself a few blocks in some direction. Let us also define our invariant that our snake’s head should not cross the playground bounds. Now, if we ensure that our invariant holds at the end of the function where we implement our teleportation ability, we are good. Otherwise, our assertions will fail, and we will find out that there probably is a bug in our code. Code Implementation in C++ :As a good programming practice, an invariant private member method is created whose duty is to check that all necessary conditions stay uncompromising and that all methods can make reasonable assumptions about the state of the object. We call this invariant member method at the end of constructors and every mutator method. Code – C++ #include <bits/stdc++.h>using namespace std; // self defined struct to // hold the position of snakestruct Pos{ int x; int y; Pos(int _x = 0, int _y = 0) { this->x = _x; this->y = _y; }}; class Snake{private: int play_width; // right bound int play_height; // height bound Pos loc; // position of snake's head void Invariant() { assert(loc.x >= 0 && loc.x <= play_width); assert(loc.y >= 0 && loc.y <= play_height); }public: // initialise the snake object with _width ans _height bounds // ans posx, posy current position Snake(int _width, int _height, Pos _p) { this->play_width = _width; this->play_height = _height; this->loc.x = _p.x; this->loc.y = _p.y; // call the invariant to ensure the object // was constructed correctly Invariant(); } // teleport and add inc.x units to current X coordinate // ans inc.y units to Y coordinate of snake void TeleportAhead(Pos inc) { loc.x += inc.x; loc.y += inc.y; //ensure that our snake wasn't // teleported out of play bounds Invariant(); } // return current position // calling invariant is unnecessary // because this is an accessor method Pos GetLoc() { return loc; }}; int main(){ Snake snek(30, 20, Pos(5, 5)); // will throw assert error because // our snake is teleported out of bound snek.TeleportAhead(Pos(20, 20)); // will also fail Invariant() assertion // because the snake is being spawned out // of bounds Snake snek2(10, 10, Pos(12, 8)); return 0;} Object-Oriented-Design Picked Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Characteristics of Internet of Things Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Advantages and Disadvantages of OOP Activation Functions Introduction to Internet of Things (IoT) | Set 1 Election algorithm and distributed processing Communication Models in IoT (Internet of Things ) Introduction to Electronic Mail Lex Program to count number of words
[ { "code": null, "e": 26003, "s": 25975, "text": "\n22 Jun, 2021" }, { "code": null, "e": 26605, "s": 26003, "text": "Overview :An invariant in Object-Oriented programming refers to some set of conditions or assertions that need to hold throughout the life of an object of a class. These assertions need to hold from the time the constructor is called for an object, at the end of each member (mutator) method call to the end of the destructor call. These conditions verify that an object’s behavior is justified during its lifetime and that the object maintains its well-defined state as intended. The invariant, however, need not hold true during the execution of a mutator method but must hold true at the end of it." }, { "code": null, "e": 27082, "s": 26605, "text": "Example :Creating a snake game –Let’s say we were creating a snake game and our snake had the ability to teleport itself a few blocks in some direction. Let us also define our invariant that our snake’s head should not cross the playground bounds. Now, if we ensure that our invariant holds at the end of the function where we implement our teleportation ability, we are good. Otherwise, our assertions will fail, and we will find out that there probably is a bug in our code." }, { "code": null, "e": 27435, "s": 27082, "text": "Code Implementation in C++ :As a good programming practice, an invariant private member method is created whose duty is to check that all necessary conditions stay uncompromising and that all methods can make reasonable assumptions about the state of the object. We call this invariant member method at the end of constructors and every mutator method." }, { "code": null, "e": 27442, "s": 27435, "text": "Code –" }, { "code": null, "e": 27446, "s": 27442, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; // self defined struct to // hold the position of snakestruct Pos{ int x; int y; Pos(int _x = 0, int _y = 0) { this->x = _x; this->y = _y; }}; class Snake{private: int play_width; // right bound int play_height; // height bound Pos loc; // position of snake's head void Invariant() { assert(loc.x >= 0 && loc.x <= play_width); assert(loc.y >= 0 && loc.y <= play_height); }public: // initialise the snake object with _width ans _height bounds // ans posx, posy current position Snake(int _width, int _height, Pos _p) { this->play_width = _width; this->play_height = _height; this->loc.x = _p.x; this->loc.y = _p.y; // call the invariant to ensure the object // was constructed correctly Invariant(); } // teleport and add inc.x units to current X coordinate // ans inc.y units to Y coordinate of snake void TeleportAhead(Pos inc) { loc.x += inc.x; loc.y += inc.y; //ensure that our snake wasn't // teleported out of play bounds Invariant(); } // return current position // calling invariant is unnecessary // because this is an accessor method Pos GetLoc() { return loc; }}; int main(){ Snake snek(30, 20, Pos(5, 5)); // will throw assert error because // our snake is teleported out of bound snek.TeleportAhead(Pos(20, 20)); // will also fail Invariant() assertion // because the snake is being spawned out // of bounds Snake snek2(10, 10, Pos(12, 8)); return 0;}", "e": 29101, "s": 27446, "text": null }, { "code": null, "e": 29124, "s": 29101, "text": "Object-Oriented-Design" }, { "code": null, "e": 29131, "s": 29124, "text": "Picked" }, { "code": null, "e": 29136, "s": 29131, "text": "Misc" }, { "code": null, "e": 29141, "s": 29136, "text": "Misc" }, { "code": null, "e": 29146, "s": 29141, "text": "Misc" }, { "code": null, "e": 29244, "s": 29146, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29282, "s": 29244, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 29317, "s": 29282, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 29356, "s": 29317, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 29392, "s": 29356, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 29413, "s": 29392, "text": "Activation Functions" }, { "code": null, "e": 29462, "s": 29413, "text": "Introduction to Internet of Things (IoT) | Set 1" }, { "code": null, "e": 29508, "s": 29462, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 29558, "s": 29508, "text": "Communication Models in IoT (Internet of Things )" }, { "code": null, "e": 29590, "s": 29558, "text": "Introduction to Electronic Mail" } ]
Python | Convert a list of Tuples into Dictionary - GeeksforGeeks
18 May, 2020 Sometimes you might need to convert a tuple to dict object to make it more readable.In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this.Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [10], 'gaurav': [12], 'anand': [14], 'ashish': [30], 'akhil': [25], 'suraj': [20]} Input : [('A', 1), ('B', 2), ('C', 3)] Output : {'B': [2], 'A': [1], 'C': [3]} Input : [("Nakul",93), ("Shivansh",45), ("Samved",65), ("Yash",88), ("Vidit",70), ("Pradeep",52)] Output : {'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 'Yash': [88], 'Vidit': [70], 'Pradeep': [52]} Input : [('Sachin', 10), ('MSD', 7), ('Kohli', 18), ('Rohit', 45)] Output : {'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45} Method 1 : Use of setdefault() Here we have used the dictionary method setdefault() to convert the first parameter to key and the second to the value of the dictionary. setdefault(key, def_value) function searches for a key and displays its value and creates a new key with def_value if the key is not present. Using the append function we just added the values to the dictionary. Example 1: # Python code to convert into dictionary def Convert(tup, di): for a, b in tup: di.setdefault(a, []).append(b) return di # Driver Code tups = [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)]dictionary = {}print (Convert(tups, dictionary)) Output: {'akash': [10], 'gaurav': [12], 'anand': [14], 'ashish': [30], 'akhil': [25], 'suraj': [20]} Example 2: # Python code to convert into dictionarylist_1=[("Nakul",93), ("Shivansh",45), ("Samved",65), ("Yash",88), ("Vidit",70), ("Pradeep",52)]dict_1=dict() for student,score in list_1: dict_1.setdefault(student, []).append(score)print(dict_1) Output: {'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 'Yash': [88], 'Vidit': [70], 'Pradeep': [52]} Method 2 : Use of dict() method Example 1: # Python code to convert into dictionarydef Convert(tup, di): di = dict(tup) return di # Driver Code tups = [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)]dictionary = {}print (Convert(tups, dictionary)) Output: {'anand': 14, 'akash': 10, 'akhil': 25, 'suraj': 20, 'ashish': 30, 'gaurav': 12} Example 2: # Python code to convert into dictionary print (dict([('Sachin', 10), ('MSD', 7), ('Kohli', 18), ('Rohit', 45)])) Output: {'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45} This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary. shardul_singh_tomar Python dictionary-programs python-dict python-tuple Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26318, "s": 26290, "text": "\n18 May, 2020" }, { "code": null, "e": 26545, "s": 26318, "text": "Sometimes you might need to convert a tuple to dict object to make it more readable.In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this.Examples:" }, { "code": null, "e": 27208, "s": 26545, "text": "Input : [(\"akash\", 10), (\"gaurav\", 12), (\"anand\", 14), \n (\"suraj\", 20), (\"akhil\", 25), (\"ashish\", 30)]\nOutput : {'akash': [10], 'gaurav': [12], 'anand': [14], \n 'ashish': [30], 'akhil': [25], 'suraj': [20]}\n\nInput : [('A', 1), ('B', 2), ('C', 3)]\nOutput : {'B': [2], 'A': [1], 'C': [3]}\n\nInput : [(\"Nakul\",93), (\"Shivansh\",45), (\"Samved\",65),\n (\"Yash\",88), (\"Vidit\",70), (\"Pradeep\",52)]\nOutput : {'Nakul': [93], 'Shivansh': [45], 'Samved': [65], \n 'Yash': [88], 'Vidit': [70], 'Pradeep': [52]}\n\nInput : [('Sachin', 10), ('MSD', 7), ('Kohli', 18), ('Rohit', 45)]\nOutput : {'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45}\n" }, { "code": null, "e": 27239, "s": 27208, "text": "Method 1 : Use of setdefault()" }, { "code": null, "e": 27589, "s": 27239, "text": "Here we have used the dictionary method setdefault() to convert the first parameter to key and the second to the value of the dictionary. setdefault(key, def_value) function searches for a key and displays its value and creates a new key with def_value if the key is not present. Using the append function we just added the values to the dictionary." }, { "code": null, "e": 27600, "s": 27589, "text": "Example 1:" }, { "code": "# Python code to convert into dictionary def Convert(tup, di): for a, b in tup: di.setdefault(a, []).append(b) return di # Driver Code tups = [(\"akash\", 10), (\"gaurav\", 12), (\"anand\", 14), (\"suraj\", 20), (\"akhil\", 25), (\"ashish\", 30)]dictionary = {}print (Convert(tups, dictionary))", "e": 27910, "s": 27600, "text": null }, { "code": null, "e": 27918, "s": 27910, "text": "Output:" }, { "code": null, "e": 28014, "s": 27918, "text": "{'akash': [10], 'gaurav': [12], 'anand': [14], \n 'ashish': [30], 'akhil': [25], 'suraj': [20]}\n" }, { "code": null, "e": 28025, "s": 28014, "text": "Example 2:" }, { "code": "# Python code to convert into dictionarylist_1=[(\"Nakul\",93), (\"Shivansh\",45), (\"Samved\",65), (\"Yash\",88), (\"Vidit\",70), (\"Pradeep\",52)]dict_1=dict() for student,score in list_1: dict_1.setdefault(student, []).append(score)print(dict_1)", "e": 28276, "s": 28025, "text": null }, { "code": null, "e": 28284, "s": 28276, "text": "Output:" }, { "code": null, "e": 28381, "s": 28284, "text": "{'Nakul': [93], 'Shivansh': [45], 'Samved': [65], 'Yash': [88], 'Vidit': [70], 'Pradeep': [52]}\n" }, { "code": null, "e": 28413, "s": 28381, "text": "Method 2 : Use of dict() method" }, { "code": null, "e": 28424, "s": 28413, "text": "Example 1:" }, { "code": "# Python code to convert into dictionarydef Convert(tup, di): di = dict(tup) return di # Driver Code tups = [(\"akash\", 10), (\"gaurav\", 12), (\"anand\", 14), (\"suraj\", 20), (\"akhil\", 25), (\"ashish\", 30)]dictionary = {}print (Convert(tups, dictionary))", "e": 28688, "s": 28424, "text": null }, { "code": null, "e": 28696, "s": 28688, "text": "Output:" }, { "code": null, "e": 28779, "s": 28696, "text": "{'anand': 14, 'akash': 10, 'akhil': 25, \n 'suraj': 20, 'ashish': 30, 'gaurav': 12}" }, { "code": null, "e": 28790, "s": 28779, "text": "Example 2:" }, { "code": "# Python code to convert into dictionary print (dict([('Sachin', 10), ('MSD', 7), ('Kohli', 18), ('Rohit', 45)]))", "e": 28905, "s": 28790, "text": null }, { "code": null, "e": 28913, "s": 28905, "text": "Output:" }, { "code": null, "e": 28965, "s": 28913, "text": "{'Sachin': 10, 'MSD': 7, 'Kohli': 18, 'Rohit': 45}\n" }, { "code": null, "e": 29145, "s": 28965, "text": "This is a simple method of conversion from a list or tuple to a dictionary. Here we pass a tuple into the dict() method which converts the tuple into the corresponding dictionary." }, { "code": null, "e": 29165, "s": 29145, "text": "shardul_singh_tomar" }, { "code": null, "e": 29192, "s": 29165, "text": "Python dictionary-programs" }, { "code": null, "e": 29204, "s": 29192, "text": "python-dict" }, { "code": null, "e": 29217, "s": 29204, "text": "python-tuple" }, { "code": null, "e": 29224, "s": 29217, "text": "Python" }, { "code": null, "e": 29236, "s": 29224, "text": "python-dict" }, { "code": null, "e": 29334, "s": 29236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29352, "s": 29334, "text": "Python Dictionary" }, { "code": null, "e": 29387, "s": 29352, "text": "Read a file line by line in Python" }, { "code": null, "e": 29419, "s": 29387, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29441, "s": 29419, "text": "Enumerate() in Python" }, { "code": null, "e": 29483, "s": 29441, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29513, "s": 29483, "text": "Iterate over a list in Python" }, { "code": null, "e": 29539, "s": 29513, "text": "Python String | replace()" }, { "code": null, "e": 29583, "s": 29539, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29612, "s": 29583, "text": "*args and **kwargs in Python" } ]
How does Query.prototype.lean() work in Mongoose ? - GeeksforGeeks
17 Mar, 2021 The Query.prototype.lean() function return the documents from queries with the lean option enabled are plain JavaScript objects, not Mongoose Documents. Syntax: Query.prototype.lean() Parameters: This function has one val parameter of boolean type.Return Value: This function returns Query Object. Mongoose Installation: npm install mongoose After installing the mongoose module, you can check your mongoose version in command prompt using the command. npm mongoose --version After that, you can just create a folder and add a file for example, index.js as shown below. Database: The sample database used here is shown below: Example 1: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = User.find().lean(true)console.log("Lean Value:", query._mongooseOptions); The project structure will look like this: Run index.js file using below command: node index.js Output: Lean Value: { lean: true } Example 2: index.js const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = User.find().lean(false)console.log("Lean Value:", query._mongooseOptions); app.listen(3000, function(error ) { if(error) console.log(error) console.log("Server listening on PORT 3000")}); The project structure will look like this: Run index.js file using below command: node index.js Output: Server listening on PORT 3000 Lean Value: { lean: false } Reference: https://mongoosejs.com/docs/api/query.html#query_Query-lean Mongoose 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 Node.js Export Module Mongoose Populate() Method Mongoose find() Function How to connect Node.js with React.js ? 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": "\n17 Mar, 2021" }, { "code": null, "e": 26420, "s": 26267, "text": "The Query.prototype.lean() function return the documents from queries with the lean option enabled are plain JavaScript objects, not Mongoose Documents." }, { "code": null, "e": 26430, "s": 26420, "text": "Syntax: " }, { "code": null, "e": 26453, "s": 26430, "text": "Query.prototype.lean()" }, { "code": null, "e": 26567, "s": 26453, "text": "Parameters: This function has one val parameter of boolean type.Return Value: This function returns Query Object." }, { "code": null, "e": 26590, "s": 26567, "text": "Mongoose Installation:" }, { "code": null, "e": 26611, "s": 26590, "text": "npm install mongoose" }, { "code": null, "e": 26723, "s": 26611, "text": "After installing the mongoose module, you can check your mongoose version in command prompt using the command. " }, { "code": null, "e": 26746, "s": 26723, "text": "npm mongoose --version" }, { "code": null, "e": 26840, "s": 26746, "text": "After that, you can just create a folder and add a file for example, index.js as shown below." }, { "code": null, "e": 26898, "s": 26840, "text": "Database: The sample database used here is shown below: " }, { "code": null, "e": 26909, "s": 26898, "text": "Example 1:" }, { "code": null, "e": 26918, "s": 26909, "text": "index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = User.find().lean(true)console.log(\"Lean Value:\", query._mongooseOptions);", "e": 27320, "s": 26918, "text": null }, { "code": null, "e": 27365, "s": 27320, "text": "The project structure will look like this: " }, { "code": null, "e": 27405, "s": 27365, "text": "Run index.js file using below command: " }, { "code": null, "e": 27419, "s": 27405, "text": "node index.js" }, { "code": null, "e": 27428, "s": 27419, "text": "Output: " }, { "code": null, "e": 27455, "s": 27428, "text": "Lean Value: { lean: true }" }, { "code": null, "e": 27466, "s": 27455, "text": "Example 2:" }, { "code": null, "e": 27475, "s": 27466, "text": "index.js" }, { "code": "const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); const query = User.find().lean(false)console.log(\"Lean Value:\", query._mongooseOptions); app.listen(3000, function(error ) { if(error) console.log(error) console.log(\"Server listening on PORT 3000\")});", "e": 28054, "s": 27475, "text": null }, { "code": null, "e": 28099, "s": 28054, "text": "The project structure will look like this: " }, { "code": null, "e": 28139, "s": 28099, "text": "Run index.js file using below command: " }, { "code": null, "e": 28153, "s": 28139, "text": "node index.js" }, { "code": null, "e": 28162, "s": 28153, "text": "Output: " }, { "code": null, "e": 28220, "s": 28162, "text": "Server listening on PORT 3000\nLean Value: { lean: false }" }, { "code": null, "e": 28292, "s": 28220, "text": "Reference: https://mongoosejs.com/docs/api/query.html#query_Query-lean " }, { "code": null, "e": 28301, "s": 28292, "text": "Mongoose" }, { "code": null, "e": 28309, "s": 28301, "text": "Node.js" }, { "code": null, "e": 28326, "s": 28309, "text": "Web Technologies" }, { "code": null, "e": 28424, "s": 28326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28494, "s": 28424, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 28516, "s": 28494, "text": "Node.js Export Module" }, { "code": null, "e": 28543, "s": 28516, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28568, "s": 28543, "text": "Mongoose find() Function" }, { "code": null, "e": 28607, "s": 28568, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28647, "s": 28607, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28692, "s": 28647, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28735, "s": 28692, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28785, "s": 28735, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to remove focus from a Tkinter widget?
To active the focus on a particular widget during the execution of a Tkinter program, we can use focus_set() method. Adding the focus creates a gray line around the widget and makes it visible to the user. There might be some cases when we need to remove the focus from the desired widget. This can be done either by removing the focus_set() property or switching the focus from one widget to another. #Import the required Libraries from tkinter import * from tkinter import ttk from tkinter import messagebox #Create an instance of Tkinter frame win = Tk() #Set the geometry of Tkinter Frame win.geometry("750x250") #Define a function to show the message def logged_in(): messagebox.showinfo("Message", "Successfully Logged In!") win.destroy() #Define a Label widget Label(win, text= "Login to the System", font=('Aerial', 14, 'bold')).pack(pady=15) #Create an entry widget Label(win, text="Enter Username").pack() username= Entry(win, width= 20) username.pack() Label(win, text= "Enter passowrd").pack() password= Entry(win, show="*", width= 20) password.pack() password.focus_set() #Add a Bottom widget button=ttk.Button(win, text="Login", command= logged_in) button.pack(pady=13) #Create a Button widget win.mainloop() In the above code snippet, the focus is currently set to the Password Entry Field, which can be unset or switched by adding focus_set() to another widget.
[ { "code": null, "e": 1268, "s": 1062, "text": "To active the focus on a particular widget during the execution of a Tkinter program, we can use focus_set() method. Adding the focus creates a gray line around the widget and makes it visible to the user." }, { "code": null, "e": 1352, "s": 1268, "text": "There might be some cases when we need to remove the focus from the desired widget." }, { "code": null, "e": 1464, "s": 1352, "text": "This can be done either by removing the focus_set() property or switching the focus from one widget to another." }, { "code": null, "e": 2295, "s": 1464, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n#Create an instance of Tkinter frame\nwin = Tk()\n#Set the geometry of Tkinter Frame\nwin.geometry(\"750x250\")\n\n#Define a function to show the message\ndef logged_in():\n messagebox.showinfo(\"Message\", \"Successfully Logged In!\")\n win.destroy()\n\n#Define a Label widget\nLabel(win, text= \"Login to the System\", font=('Aerial', 14, 'bold')).pack(pady=15)\n#Create an entry widget\nLabel(win, text=\"Enter Username\").pack()\nusername= Entry(win, width= 20)\nusername.pack()\nLabel(win, text= \"Enter passowrd\").pack()\npassword= Entry(win, show=\"*\", width= 20)\npassword.pack()\npassword.focus_set()\n#Add a Bottom widget\nbutton=ttk.Button(win, text=\"Login\", command= logged_in)\nbutton.pack(pady=13)\n\n#Create a Button widget\nwin.mainloop()" }, { "code": null, "e": 2450, "s": 2295, "text": "In the above code snippet, the focus is currently set to the Password Entry Field, which can be unset or switched by adding focus_set() to another widget." } ]
How to Revise Marketing Mix Model under COVID-19 | Towards Data Science
COVID-19 has shocked the world and inevitably transformed how people work, shop and live. It not only sent economies spinning but also significantly impacted on how a wide range of advertisers are doing marketing. Influencer Marketing Hub recently unveiled COVID-19 Marketing Report saying 69% of brands indicated that they will decrease Ad Spend in 2020. And 74% of the firms they surveyed have slowed down their social media posting. Beyond all doubt, slashing marketing spend will ensure short term survival and send grappled business a slim chance of recovery. However, the rigorous measurement of your marketing performance and having every one dollar drive more sales are way more critical and essential than ever. In today’s post, We are going to talk about how to better evaluate marketing efficiency under COVID-19 pandemic. Methodologies to Measure Marketing Efficiency To evaluate the marketing performance and optimize channel mix, the most important question we need to answer entails what Return on Investment (ROI) we are getting for the money we spend on each channel. Marketing Mix Models and Multi-Touch Attribution are popular techniques that tend to provide the depth of insights required to answer this question. I am more inclined to go with the Marketing Mix Model to evaluate marketing ROI during COVID-19 pandemic for two reasons. First and foremost, Multi-Touch Attribution is a bottom-up approach to evaluating marketing efficacy. It is focused on online marketing and sales and better at analyzing real-time user level data. Rather than evaluating every touchpoint user takes towards final conversion, Marketing Mix Modeling takes more of a top-down and macro-level view. For this reason, not only marketing related factors, but also factors such as macro economy, seasonality, weather, and the competitive impact can be examined and captured. From this standpoint, the unprecedented COVID-19 pandemic is not within everyone’s normal control and MMM can better capture the effect from it. Moreover, MTA is mostly focused on the digital ecosystem while MMM can easily cover more offline channels. In light of Coronavirus, people are stuck at home. This consequently drove TV viewership up. According to the latest forecast from eMarketer, traditional TV is expected to add 8.3 million U.S. viewers this year, and this would be the first time that traditional TV viewing has increased since 2012👀. As a result, MMM may be doing a better job to measure the efficacy of TV performance compared to MTA. A Brief Intro of Building Marketing Mix Models In general, MMM employs the principle of Multivariate-Linear Regression, which is trying to form an equation between your Target KPI (Dependent Variable) and a set of drivers (Independent Variables) that will impact your KPI. Your candidate drivers can be ultimately categorized into these two big groups: Uncontrollable Factors: External factors that are out of our control, including Macro Economy, Seasonality, Holidays, and Weather etc. Controllable Factors: Media and Marketing related metrics that we can play around with and optimize. Usually, those uncontrollable factors are showing a linear relationship with your Target KPI, which means that every one unit increase in these factors will change your KPI by a certain amount (the change can be both negative and positive). However, for Media and Marketing related drivers, their impact is non-linear and three unique parameters have to be taken into consideration. They are Lag effect, Carryover Effect (Adstock) and Diminishing Return. Lag Effect means how long it takes your ads to convert customers. If we are going to use sales revenue as the target KPI, the lag effect from lower funnel channels such as Social Media Engagement will be shorter than channels from upper funnels, e.g. TV and Radio which are about raising awareness and sparking interest. Carry-over Effect (Adstock) is essentially described as that advertising will spread out over time and have a continuous impact on your KPI after it takes place. Let’s say if you see a Shopping Ads from Instagram, you will still remember those creative images for the next following days but with faded memories. The formula for Adstock is: At = Xt + Adstock Rate * At-1 To check more details about Adstock, check GroupM Marketing Mix models across Consumer Electronics, Retail, Finance, Auto and CPG from here Diminishing Return is originally an economics principle and here is a very classic example to elaborate it: When you are hungry, the utility you gain from eating the first burger will be higher than the utility the next burger brings to you. Applying this law into the measurement of marketing performance, it indicates that for every one dollar spent on advertising, it will lift your KPI but at a decreasing rate. The values of these three parameters are varied channel by channel. And they will not be the same for even the same channel when driving different KPIs or during different time periods. So, they are not predetermined or pre-assumed. Instead, it involves iterative model training and testing to get the most ideal combination of these three parameters for each channel impacting on specific KPIs during certain periods. Multivariate Regression Models enable us to easily identify the significant drivers that impact your target KPI and quantify their impact with coefficients. How to Capture COVID-19 Impact and Revise Your MMM? Since COVID-19 is an unprecedented situation, similar impact was never captured and evaluated historically in your model and thus will make your MMM not function well. You may be already aware that if applying the MMM built prior to the Coronavirus outbreak to do a forecast, you will see an extremely high error rate while comparing to the actual. Without taking Coronavirus impact into account, your marketing efficiency would also be mistakenly evaluated. How to revise our MMM to capture the COVID-19 impact? Here are some options you can give a shot. COVID-19 Dummy Variable This is a very straight forward and unsophisticated way to have Coronavirus impact fit into your model as an external factor. The biggest caveat of the Dummy variable is that it takes the value only 0 or 1 to indicate the absence or presence of certain factors. However, we have no idea when the pandemic will go to the end and there is a very real chance it might never go away. Also, the impact from COVID-19 is dynamic by flattening the curve rather than a fixed value. Therefore the Dummy variable with either 0 or 1 can’t fully and accurately pick up the decayed impact. COVID-19 Related Indicators To better capture the dynamic impact from COVID-19, we can directly approach pandemic related metrics such as number of Daily Incremental and Cumulative Confirmed Cases, Recoveries or Death etc. as the proxy. Google has provided free public datasets in Google Cloud Platform. You can go here and check more details. Macroeconomic Indices Coronavirus, a Black Swan incident, has resulted in a severe economic contraction. Therefore, besides COVID-19 related metrics, we can also indirectly leverage some macroeconomic indices to approximate the impact. The most intuitive one is the Unemployment Rate. Due to the Coronavirus, the U.S. unemployment rate soared to 14.7% in April, the highest rate since the Great Depression. Data is available and can be easily downloaded from U.S. Bureau of Labor Statistics. One limitation of using Unemployment Rate is that data is usually refreshed and published on a monthly level. Therefore, it may not fully capture the daily or weekly fluctuation and variation. Apart from this, considering that the stock market is always regarded as an economic barometer, indices in the stock market such as S&P 500 and Dow Jones are also potential candidates. Yahoo Finance is where I always go to download data of those indexes. Counterfactual Analysis Above proxies may help capture the general up and down of your business. Indeed, they may not be able to perfectly capture your trend. Another potential way to derive a metric of COVID-19 impact that is specific on your business is to utilize the MMM built prior to the Coronavirus outbreak to do a counterfactual estimation. To elaborate, Counterfactual Analysis measures what would have happened without COVID-19, so that we can quantify its impact by comparing the actual observed performance and counterfactual outcomes. You may ask how to do counterfactual analysis if you never built MMM before? We can leverage the forecast package in R using historical data prior to the pandemic. Here are sample codes to do the prediction. library(forecast)#Step 1: Convert sales data into time series. Here is using 2-year data to forecast next yearts <- ts(sales$Sales[sales.Period >= '2018-01-01' & sales.Period <='2019-12-31'])#Step 2: Fitting an auto.arima model in R using the Forecast packagesales<- auto.arima(ts)pred <- forecast(object = sales, h = 365) So far, we have talked about four ways we can derive COVID-19 metrics and measure its impact as an external factor. Nevertheless, the COVID-19 is not only impacting our business externally, but also essentially affecting marketing efficiencies and effectiveness. On this account, what else do you need to do to revise your Marketing Mix Models to account different marketing efficacy during the pandemic? You need to retrain your Marketing Mix Models with the latest data by splitting each of media and marketing metric into two parts. By doing so, we can get different coefficients prior and post COVID-19 and calculate corresponding ROI across marketing channels. In the next article, we will talk about how to utilize R to build a mini optimizer based on your Marketing Mix Model results and improve your marketing efficacy.💖
[ { "code": null, "e": 608, "s": 172, "text": "COVID-19 has shocked the world and inevitably transformed how people work, shop and live. It not only sent economies spinning but also significantly impacted on how a wide range of advertisers are doing marketing. Influencer Marketing Hub recently unveiled COVID-19 Marketing Report saying 69% of brands indicated that they will decrease Ad Spend in 2020. And 74% of the firms they surveyed have slowed down their social media posting." }, { "code": null, "e": 1006, "s": 608, "text": "Beyond all doubt, slashing marketing spend will ensure short term survival and send grappled business a slim chance of recovery. However, the rigorous measurement of your marketing performance and having every one dollar drive more sales are way more critical and essential than ever. In today’s post, We are going to talk about how to better evaluate marketing efficiency under COVID-19 pandemic." }, { "code": null, "e": 1052, "s": 1006, "text": "Methodologies to Measure Marketing Efficiency" }, { "code": null, "e": 1406, "s": 1052, "text": "To evaluate the marketing performance and optimize channel mix, the most important question we need to answer entails what Return on Investment (ROI) we are getting for the money we spend on each channel. Marketing Mix Models and Multi-Touch Attribution are popular techniques that tend to provide the depth of insights required to answer this question." }, { "code": null, "e": 1528, "s": 1406, "text": "I am more inclined to go with the Marketing Mix Model to evaluate marketing ROI during COVID-19 pandemic for two reasons." }, { "code": null, "e": 2189, "s": 1528, "text": "First and foremost, Multi-Touch Attribution is a bottom-up approach to evaluating marketing efficacy. It is focused on online marketing and sales and better at analyzing real-time user level data. Rather than evaluating every touchpoint user takes towards final conversion, Marketing Mix Modeling takes more of a top-down and macro-level view. For this reason, not only marketing related factors, but also factors such as macro economy, seasonality, weather, and the competitive impact can be examined and captured. From this standpoint, the unprecedented COVID-19 pandemic is not within everyone’s normal control and MMM can better capture the effect from it." }, { "code": null, "e": 2698, "s": 2189, "text": "Moreover, MTA is mostly focused on the digital ecosystem while MMM can easily cover more offline channels. In light of Coronavirus, people are stuck at home. This consequently drove TV viewership up. According to the latest forecast from eMarketer, traditional TV is expected to add 8.3 million U.S. viewers this year, and this would be the first time that traditional TV viewing has increased since 2012👀. As a result, MMM may be doing a better job to measure the efficacy of TV performance compared to MTA." }, { "code": null, "e": 2745, "s": 2698, "text": "A Brief Intro of Building Marketing Mix Models" }, { "code": null, "e": 2971, "s": 2745, "text": "In general, MMM employs the principle of Multivariate-Linear Regression, which is trying to form an equation between your Target KPI (Dependent Variable) and a set of drivers (Independent Variables) that will impact your KPI." }, { "code": null, "e": 3051, "s": 2971, "text": "Your candidate drivers can be ultimately categorized into these two big groups:" }, { "code": null, "e": 3186, "s": 3051, "text": "Uncontrollable Factors: External factors that are out of our control, including Macro Economy, Seasonality, Holidays, and Weather etc." }, { "code": null, "e": 3287, "s": 3186, "text": "Controllable Factors: Media and Marketing related metrics that we can play around with and optimize." }, { "code": null, "e": 3742, "s": 3287, "text": "Usually, those uncontrollable factors are showing a linear relationship with your Target KPI, which means that every one unit increase in these factors will change your KPI by a certain amount (the change can be both negative and positive). However, for Media and Marketing related drivers, their impact is non-linear and three unique parameters have to be taken into consideration. They are Lag effect, Carryover Effect (Adstock) and Diminishing Return." }, { "code": null, "e": 4063, "s": 3742, "text": "Lag Effect means how long it takes your ads to convert customers. If we are going to use sales revenue as the target KPI, the lag effect from lower funnel channels such as Social Media Engagement will be shorter than channels from upper funnels, e.g. TV and Radio which are about raising awareness and sparking interest." }, { "code": null, "e": 4376, "s": 4063, "text": "Carry-over Effect (Adstock) is essentially described as that advertising will spread out over time and have a continuous impact on your KPI after it takes place. Let’s say if you see a Shopping Ads from Instagram, you will still remember those creative images for the next following days but with faded memories." }, { "code": null, "e": 4434, "s": 4376, "text": "The formula for Adstock is: At = Xt + Adstock Rate * At-1" }, { "code": null, "e": 4574, "s": 4434, "text": "To check more details about Adstock, check GroupM Marketing Mix models across Consumer Electronics, Retail, Finance, Auto and CPG from here" }, { "code": null, "e": 4816, "s": 4574, "text": "Diminishing Return is originally an economics principle and here is a very classic example to elaborate it: When you are hungry, the utility you gain from eating the first burger will be higher than the utility the next burger brings to you." }, { "code": null, "e": 4990, "s": 4816, "text": "Applying this law into the measurement of marketing performance, it indicates that for every one dollar spent on advertising, it will lift your KPI but at a decreasing rate." }, { "code": null, "e": 5409, "s": 4990, "text": "The values of these three parameters are varied channel by channel. And they will not be the same for even the same channel when driving different KPIs or during different time periods. So, they are not predetermined or pre-assumed. Instead, it involves iterative model training and testing to get the most ideal combination of these three parameters for each channel impacting on specific KPIs during certain periods." }, { "code": null, "e": 5566, "s": 5409, "text": "Multivariate Regression Models enable us to easily identify the significant drivers that impact your target KPI and quantify their impact with coefficients." }, { "code": null, "e": 5618, "s": 5566, "text": "How to Capture COVID-19 Impact and Revise Your MMM?" }, { "code": null, "e": 6077, "s": 5618, "text": "Since COVID-19 is an unprecedented situation, similar impact was never captured and evaluated historically in your model and thus will make your MMM not function well. You may be already aware that if applying the MMM built prior to the Coronavirus outbreak to do a forecast, you will see an extremely high error rate while comparing to the actual. Without taking Coronavirus impact into account, your marketing efficiency would also be mistakenly evaluated." }, { "code": null, "e": 6174, "s": 6077, "text": "How to revise our MMM to capture the COVID-19 impact? Here are some options you can give a shot." }, { "code": null, "e": 6198, "s": 6174, "text": "COVID-19 Dummy Variable" }, { "code": null, "e": 6774, "s": 6198, "text": "This is a very straight forward and unsophisticated way to have Coronavirus impact fit into your model as an external factor. The biggest caveat of the Dummy variable is that it takes the value only 0 or 1 to indicate the absence or presence of certain factors. However, we have no idea when the pandemic will go to the end and there is a very real chance it might never go away. Also, the impact from COVID-19 is dynamic by flattening the curve rather than a fixed value. Therefore the Dummy variable with either 0 or 1 can’t fully and accurately pick up the decayed impact." }, { "code": null, "e": 6802, "s": 6774, "text": "COVID-19 Related Indicators" }, { "code": null, "e": 7118, "s": 6802, "text": "To better capture the dynamic impact from COVID-19, we can directly approach pandemic related metrics such as number of Daily Incremental and Cumulative Confirmed Cases, Recoveries or Death etc. as the proxy. Google has provided free public datasets in Google Cloud Platform. You can go here and check more details." }, { "code": null, "e": 7140, "s": 7118, "text": "Macroeconomic Indices" }, { "code": null, "e": 7610, "s": 7140, "text": "Coronavirus, a Black Swan incident, has resulted in a severe economic contraction. Therefore, besides COVID-19 related metrics, we can also indirectly leverage some macroeconomic indices to approximate the impact. The most intuitive one is the Unemployment Rate. Due to the Coronavirus, the U.S. unemployment rate soared to 14.7% in April, the highest rate since the Great Depression. Data is available and can be easily downloaded from U.S. Bureau of Labor Statistics." }, { "code": null, "e": 7803, "s": 7610, "text": "One limitation of using Unemployment Rate is that data is usually refreshed and published on a monthly level. Therefore, it may not fully capture the daily or weekly fluctuation and variation." }, { "code": null, "e": 8058, "s": 7803, "text": "Apart from this, considering that the stock market is always regarded as an economic barometer, indices in the stock market such as S&P 500 and Dow Jones are also potential candidates. Yahoo Finance is where I always go to download data of those indexes." }, { "code": null, "e": 8082, "s": 8058, "text": "Counterfactual Analysis" }, { "code": null, "e": 8607, "s": 8082, "text": "Above proxies may help capture the general up and down of your business. Indeed, they may not be able to perfectly capture your trend. Another potential way to derive a metric of COVID-19 impact that is specific on your business is to utilize the MMM built prior to the Coronavirus outbreak to do a counterfactual estimation. To elaborate, Counterfactual Analysis measures what would have happened without COVID-19, so that we can quantify its impact by comparing the actual observed performance and counterfactual outcomes." }, { "code": null, "e": 8815, "s": 8607, "text": "You may ask how to do counterfactual analysis if you never built MMM before? We can leverage the forecast package in R using historical data prior to the pandemic. Here are sample codes to do the prediction." }, { "code": null, "e": 9138, "s": 8815, "text": "library(forecast)#Step 1: Convert sales data into time series. Here is using 2-year data to forecast next yearts <- ts(sales$Sales[sales.Period >= '2018-01-01' & sales.Period <='2019-12-31'])#Step 2: Fitting an auto.arima model in R using the Forecast packagesales<- auto.arima(ts)pred <- forecast(object = sales, h = 365)" }, { "code": null, "e": 9543, "s": 9138, "text": "So far, we have talked about four ways we can derive COVID-19 metrics and measure its impact as an external factor. Nevertheless, the COVID-19 is not only impacting our business externally, but also essentially affecting marketing efficiencies and effectiveness. On this account, what else do you need to do to revise your Marketing Mix Models to account different marketing efficacy during the pandemic?" }, { "code": null, "e": 9804, "s": 9543, "text": "You need to retrain your Marketing Mix Models with the latest data by splitting each of media and marketing metric into two parts. By doing so, we can get different coefficients prior and post COVID-19 and calculate corresponding ROI across marketing channels." } ]
Count and Sum of composite elements in an array in C++
We are given with an array of positive integers and the task is to calculate the count and sum of the composite elements in the given array. From the given set of integers, the numbers that are not prime are called composite numbers except 1 which is neither composite nor prime instead it’s a unit number. So, it is clearly stated that a number can be either prime or composite except the number 1. The composite upto 100 are given below − 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100 Input − array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output − total count of composite numbers is: 5 Sum of composite number is: 37 Explanation − 4, 6, 8, 9, 10 are the composite numbers present in a given array. So, their count is 5 and their sum is 4+6+8+9+10 = 37 Input − array[] = {1, 2, 3, 4, 5} Output − total count of composite numbers is: 1 Sum of composite number is: 4 Explanation − 4 is the only composite number present in a given array. So, their count is 1 and their sum is 4 Input the array of positive integers Input the array of positive integers Calculate its size Calculate its size Initialise the variable sum to store the sum of composite numbers Initialise the variable sum to store the sum of composite numbers Store the maximum value present in an array in a variable Store the maximum value present in an array in a variable Calculate the prime numbers till the maximum value Calculate the prime numbers till the maximum value Traverse the entire array and check for whether the number is prime or not. If the number isn’t prime then it will be composite number and if it is so, then increase the count for composite number by 1 and add its value to the sum Traverse the entire array and check for whether the number is prime or not. If the number isn’t prime then it will be composite number and if it is so, then increase the count for composite number by 1 and add its value to the sum Live Demo #include <iostream> #include <vector> #include <algorithm> using namespace std; // Function to find and return the // the count of the composite numbers int compcount(int ar[], int num, int* sum){ // storing the largest element of the array int max_val = *max_element(ar, ar + num); // Using sieve to find all prime numbers // less than or equal to max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false vector<bool> pr(max_val + 1, true); // setting the values of 0 and 1 as // true for prime. pr[0] = true; pr[1] = true; for (int p = 2; p * p <= max_val; p++){ // If prime[p] is not changed, then // it is a prime if (pr[p] == true){ // Update all multiples of p for (int i = p * 2; i <= max_val; i += p){ pr[i] = false; } } } // Count all composite // numbers in the arr[] int ans = 0; for (int i = 0; i < num; i++){ if (!pr[ar[i]]){ ans++; *sum = *sum + ar[i]; } } return ans; } // Driver code int main(){ int ar[] = { 1, 2, 3, 4, 5 }; int num = sizeof(ar) / sizeof(ar[0]); int sum = 0; cout << "Count of Composite Numbers = "<< compcount(ar, num, &sum); cout << "\nSum of Composite Numbers = " << sum; return 0; } If we run the above code it will generate the following output − Count of Composite Numbers = 1 Sum of Composite Numbers = 4
[ { "code": null, "e": 1203, "s": 1062, "text": "We are given with an array of positive integers and the task is to calculate the count and sum of the composite elements in the given array." }, { "code": null, "e": 1462, "s": 1203, "text": "From the given set of integers, the numbers that are not prime are called composite numbers except 1 which is neither composite nor prime instead it’s a unit number. So, it is clearly stated that a number can be either prime or composite except the number 1." }, { "code": null, "e": 1503, "s": 1462, "text": "The composite upto 100 are given below −" }, { "code": null, "e": 1800, "s": 1503, "text": "4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, \n26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, \n45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, \n63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, \n81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, \n98, 99, 100" }, { "code": null, "e": 1935, "s": 1800, "text": "Input − array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\nOutput − total count of composite numbers is: 5\n Sum of composite number is: 37" }, { "code": null, "e": 2070, "s": 1935, "text": "Explanation − 4, 6, 8, 9, 10 are the composite numbers present in a given array. So, their count is 5 and their sum is 4+6+8+9+10 = 37" }, { "code": null, "e": 2188, "s": 2070, "text": "Input − array[] = {1, 2, 3, 4, 5}\nOutput − total count of composite numbers is: 1\n Sum of composite number is: 4" }, { "code": null, "e": 2299, "s": 2188, "text": "Explanation − 4 is the only composite number present in a given array. So, their count is 1 and their sum is 4" }, { "code": null, "e": 2336, "s": 2299, "text": "Input the array of positive integers" }, { "code": null, "e": 2373, "s": 2336, "text": "Input the array of positive integers" }, { "code": null, "e": 2392, "s": 2373, "text": "Calculate its size" }, { "code": null, "e": 2411, "s": 2392, "text": "Calculate its size" }, { "code": null, "e": 2477, "s": 2411, "text": "Initialise the variable sum to store the sum of composite numbers" }, { "code": null, "e": 2543, "s": 2477, "text": "Initialise the variable sum to store the sum of composite numbers" }, { "code": null, "e": 2601, "s": 2543, "text": "Store the maximum value present in an array in a variable" }, { "code": null, "e": 2659, "s": 2601, "text": "Store the maximum value present in an array in a variable" }, { "code": null, "e": 2710, "s": 2659, "text": "Calculate the prime numbers till the maximum value" }, { "code": null, "e": 2761, "s": 2710, "text": "Calculate the prime numbers till the maximum value" }, { "code": null, "e": 2992, "s": 2761, "text": "Traverse the entire array and check for whether the number is prime or not. If the\nnumber isn’t prime then it will be composite number and if it is so, then increase the\ncount for composite number by 1 and add its value to the sum" }, { "code": null, "e": 3223, "s": 2992, "text": "Traverse the entire array and check for whether the number is prime or not. If the\nnumber isn’t prime then it will be composite number and if it is so, then increase the\ncount for composite number by 1 and add its value to the sum" }, { "code": null, "e": 3234, "s": 3223, "text": " Live Demo" }, { "code": null, "e": 4560, "s": 3234, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n// Function to find and return the\n// the count of the composite numbers\nint compcount(int ar[], int num, int* sum){\n // storing the largest element of the array\n int max_val = *max_element(ar, ar + num);\n // Using sieve to find all prime numbers\n // less than or equal to max_val\n // Create a boolean array \"prime[0..n]\". A\n // value in prime[i] will finally be false\n vector<bool> pr(max_val + 1, true);\n // setting the values of 0 and 1 as\n // true for prime.\n pr[0] = true;\n pr[1] = true;\n for (int p = 2; p * p <= max_val; p++){\n // If prime[p] is not changed, then\n // it is a prime\n if (pr[p] == true){\n // Update all multiples of p\n for (int i = p * 2; i <= max_val; i += p){\n pr[i] = false;\n }\n }\n }\n // Count all composite\n // numbers in the arr[]\n int ans = 0;\n for (int i = 0; i < num; i++){\n if (!pr[ar[i]]){\n ans++;\n *sum = *sum + ar[i];\n }\n }\n return ans;\n}\n// Driver code\nint main(){\n int ar[] = { 1, 2, 3, 4, 5 };\n int num = sizeof(ar) / sizeof(ar[0]);\n int sum = 0;\n cout << \"Count of Composite Numbers = \"<< compcount(ar, num, &sum);\n cout << \"\\nSum of Composite Numbers = \" << sum;\n return 0;\n}" }, { "code": null, "e": 4625, "s": 4560, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4685, "s": 4625, "text": "Count of Composite Numbers = 1\nSum of Composite Numbers = 4" } ]
Find smallest permutation of given number - GeeksforGeeks
04 May, 2021 Given a long integer, return the smallest(magnitude) integer permutation of that number.Examples: Input : 5468001 Output : 1004568 Input : 5341 Output : 1345 Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Question Source : GE digital Interview Experience | Set 6We have already discussed a solution in below post.Smallest number by rearranging digits of a given numberIn this post, a different approach is discussed.Approach : As number is long, store the number as string, sort the string, if there is no leading zero, return this string, if there is any leading zero, swap first element of string with first non-zero element of string, and return the string.Below is the implementation of above approach : C++ Java Python C# PHP Javascript // CPP program to find smallest// permutation of given number#include <bits/stdc++.h>using namespace std; // return the smallest number permutationstring findSmallestPermutation(string s){ int len = s.length(); // sort the string sort(s.begin(), s.end()); // check for leading zero in string // if there are any leading zeroes, // swap the first zero with first non-zero number int i = 0; while (s[i] == '0') i++; swap(s[0], s[i]); return s;} // driver programint main(){ // take number input in string string s = "5468001"; string res = findSmallestPermutation(s); cout << res << endl; return 0;} // Java program to find smallest// permutation of given numberimport java.util.Arrays; public class GFG { // return the smallest number permutation static char[] findSmallestPermutation(String s1) { // sort the string char s[] = s1.toCharArray(); Arrays.sort(s); // check for leading zero in string // if there are any leading zeroes, // swap the first zero with first non-zero // number int i = 0; while (s[i] == '0') i++; char temp = s[0]; s[0] = s[i]; s[i] = temp; return s; } // driver program public static void main(String args[]) { // take number input in string String s = "5468001"; char res[] = findSmallestPermutation(s); System.out.println(res); }}// This code is contributed by Sumit Ghosh # Python program to find smallest# permutation of given number # Sort functiondef sort_string(a): return ''.join(sorted(a)) # return the smallest number permutationdef findSmallestPermutation(s): # sort the string s = sort_string(s) # check for leading zero in string # if there are any leading zeroes, # swap the first zero with first non-zero number i = 0 while (s[i] == '0'): i += 1 a = list(s) temp = a[0] a[0] = a[i] a[i] = temp s = "".join(a) return s # driver program # take number input in strings = "5468001"res = findSmallestPermutation(s)print res # This code is contributed by Sachin Bisht // C# program to find smallest// permutation of given numberusing System; public class GFG { // return the smallest number permutation static char[] findSmallestPermutation(string s1) { // sort the string char []s = s1.ToCharArray();; Array.Sort(s); // check for leading zero in string // if there are any leading zeroes, // swap the first zero with first non-zero // number int i = 0; while (s[i] == '0') i++; char temp = s[0]; s[0] = s[i]; s[i] = temp; return s; } // driver program public static void Main() { // take number input in string string s = "5468001"; char []res = findSmallestPermutation(s); Console.WriteLine(res); }} // This code is contributed by vt_m. <?php// PHP program to find smallest// permutation of given number // return the smallest// number permutationfunction findSmallestPermutation($s){ $len = strlen($s); $s = str_split($s); // sort the string sort($s); // check for leading zero // in string if there are // any leading zeroes, // swap the first zero with // first non-zero number $i = 0; while ($s[$i] == '0') $i++; $tmp = $s[0]; $s[0] = $s[$i]; $s[$i] = $tmp; $s=implode("", $s); return $s;} // Driver Code // take number// input in string$s = "5468001";$res = findSmallestPermutation($s);echo $res; // This code is contributed// by mits.?> // Javascript program to find smallest// permutation of given number // return the smallest// number permutationfunction findSmallestPermutation(s){ let len = s.length; s = s.split(""); // sort the string s = s.sort(); // check for leading zero // in string if there are // any leading zeroes, // swap the first zero with // first non-zero number let i = 0; while (s[i] == '0') i++; let tmp = s[0]; s[0] = s[i]; s[i] = tmp; s= s.join(""); return s;} // Driver Code // take number// input in stringlet s = "5468001";let res = findSmallestPermutation(s);document.write(res); // This code is contributed// by _saurabh_jaiswal Output: 1004568 Optimization : Since character set is limited (‘0’ to ‘9’), we can write our own sort method that works in linear time (by counting frequencies of all characters)This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Mithun Kumar pandeyprince25 _saurabh_jaiswal GE number-digits Mathematical GE Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find sum of elements in a given array Operators in C / C++ The Knight's tour problem | Backtracking-1 Euclidean algorithms (Basic and Extended) Find minimum number of coins that make a given value Print all possible combinations of r elements in a given array of size n Write a program to calculate pow(x,n) Algorithm to solve Rubik's Cube Write a program to reverse digits of a number How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 25150, "s": 25122, "text": "\n04 May, 2021" }, { "code": null, "e": 25250, "s": 25150, "text": "Given a long integer, return the smallest(magnitude) integer permutation of that number.Examples: " }, { "code": null, "e": 25311, "s": 25250, "text": "Input : 5468001\nOutput : 1004568\n\nInput : 5341\nOutput : 1345" }, { "code": null, "e": 25399, "s": 25313, "text": "Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. " }, { "code": null, "e": 25906, "s": 25401, "text": "Question Source : GE digital Interview Experience | Set 6We have already discussed a solution in below post.Smallest number by rearranging digits of a given numberIn this post, a different approach is discussed.Approach : As number is long, store the number as string, sort the string, if there is no leading zero, return this string, if there is any leading zero, swap first element of string with first non-zero element of string, and return the string.Below is the implementation of above approach : " }, { "code": null, "e": 25910, "s": 25906, "text": "C++" }, { "code": null, "e": 25915, "s": 25910, "text": "Java" }, { "code": null, "e": 25922, "s": 25915, "text": "Python" }, { "code": null, "e": 25925, "s": 25922, "text": "C#" }, { "code": null, "e": 25929, "s": 25925, "text": "PHP" }, { "code": null, "e": 25940, "s": 25929, "text": "Javascript" }, { "code": "// CPP program to find smallest// permutation of given number#include <bits/stdc++.h>using namespace std; // return the smallest number permutationstring findSmallestPermutation(string s){ int len = s.length(); // sort the string sort(s.begin(), s.end()); // check for leading zero in string // if there are any leading zeroes, // swap the first zero with first non-zero number int i = 0; while (s[i] == '0') i++; swap(s[0], s[i]); return s;} // driver programint main(){ // take number input in string string s = \"5468001\"; string res = findSmallestPermutation(s); cout << res << endl; return 0;}", "e": 26597, "s": 25940, "text": null }, { "code": "// Java program to find smallest// permutation of given numberimport java.util.Arrays; public class GFG { // return the smallest number permutation static char[] findSmallestPermutation(String s1) { // sort the string char s[] = s1.toCharArray(); Arrays.sort(s); // check for leading zero in string // if there are any leading zeroes, // swap the first zero with first non-zero // number int i = 0; while (s[i] == '0') i++; char temp = s[0]; s[0] = s[i]; s[i] = temp; return s; } // driver program public static void main(String args[]) { // take number input in string String s = \"5468001\"; char res[] = findSmallestPermutation(s); System.out.println(res); }}// This code is contributed by Sumit Ghosh", "e": 27481, "s": 26597, "text": null }, { "code": "# Python program to find smallest# permutation of given number # Sort functiondef sort_string(a): return ''.join(sorted(a)) # return the smallest number permutationdef findSmallestPermutation(s): # sort the string s = sort_string(s) # check for leading zero in string # if there are any leading zeroes, # swap the first zero with first non-zero number i = 0 while (s[i] == '0'): i += 1 a = list(s) temp = a[0] a[0] = a[i] a[i] = temp s = \"\".join(a) return s # driver program # take number input in strings = \"5468001\"res = findSmallestPermutation(s)print res # This code is contributed by Sachin Bisht", "e": 28137, "s": 27481, "text": null }, { "code": "// C# program to find smallest// permutation of given numberusing System; public class GFG { // return the smallest number permutation static char[] findSmallestPermutation(string s1) { // sort the string char []s = s1.ToCharArray();; Array.Sort(s); // check for leading zero in string // if there are any leading zeroes, // swap the first zero with first non-zero // number int i = 0; while (s[i] == '0') i++; char temp = s[0]; s[0] = s[i]; s[i] = temp; return s; } // driver program public static void Main() { // take number input in string string s = \"5468001\"; char []res = findSmallestPermutation(s); Console.WriteLine(res); }} // This code is contributed by vt_m.", "e": 29013, "s": 28137, "text": null }, { "code": "<?php// PHP program to find smallest// permutation of given number // return the smallest// number permutationfunction findSmallestPermutation($s){ $len = strlen($s); $s = str_split($s); // sort the string sort($s); // check for leading zero // in string if there are // any leading zeroes, // swap the first zero with // first non-zero number $i = 0; while ($s[$i] == '0') $i++; $tmp = $s[0]; $s[0] = $s[$i]; $s[$i] = $tmp; $s=implode(\"\", $s); return $s;} // Driver Code // take number// input in string$s = \"5468001\";$res = findSmallestPermutation($s);echo $res; // This code is contributed// by mits.?>", "e": 29685, "s": 29013, "text": null }, { "code": "// Javascript program to find smallest// permutation of given number // return the smallest// number permutationfunction findSmallestPermutation(s){ let len = s.length; s = s.split(\"\"); // sort the string s = s.sort(); // check for leading zero // in string if there are // any leading zeroes, // swap the first zero with // first non-zero number let i = 0; while (s[i] == '0') i++; let tmp = s[0]; s[0] = s[i]; s[i] = tmp; s= s.join(\"\"); return s;} // Driver Code // take number// input in stringlet s = \"5468001\";let res = findSmallestPermutation(s);document.write(res); // This code is contributed// by _saurabh_jaiswal", "e": 30375, "s": 29685, "text": null }, { "code": null, "e": 30385, "s": 30375, "text": "Output: " }, { "code": null, "e": 30393, "s": 30385, "text": "1004568" }, { "code": null, "e": 30976, "s": 30393, "text": "Optimization : Since character set is limited (‘0’ to ‘9’), we can write our own sort method that works in linear time (by counting frequencies of all characters)This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30981, "s": 30976, "text": "vt_m" }, { "code": null, "e": 30994, "s": 30981, "text": "Mithun Kumar" }, { "code": null, "e": 31009, "s": 30994, "text": "pandeyprince25" }, { "code": null, "e": 31026, "s": 31009, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31029, "s": 31026, "text": "GE" }, { "code": null, "e": 31043, "s": 31029, "text": "number-digits" }, { "code": null, "e": 31056, "s": 31043, "text": "Mathematical" }, { "code": null, "e": 31059, "s": 31056, "text": "GE" }, { "code": null, "e": 31072, "s": 31059, "text": "Mathematical" }, { "code": null, "e": 31170, "s": 31072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31219, "s": 31170, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31240, "s": 31219, "text": "Operators in C / C++" }, { "code": null, "e": 31283, "s": 31240, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31325, "s": 31283, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 31378, "s": 31325, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 31451, "s": 31378, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31489, "s": 31451, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 31521, "s": 31489, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 31567, "s": 31521, "text": "Write a program to reverse digits of a number" } ]
Recursive program for prime number in C++
We are given an integer as input. The goal is to find whether the input number Num is a prime or non-prime using recursion. To check if a number is prime or not, start traversing from i=2 to i<=Num/2. If any i is fully divisible by Num then the number is non-prime as prime numbers are only divisible by 1 and the number itself. Input − Num = 32 Output − 32 is non-Prime! Explanation − If we start traversing from i=2 to i<=32/2, then at first it will be fully divisible by 2 which tells it is non-prime. Input − Num = 43 Output − 43 is a Prime number! Explanation − If we start traversing from i=2 to i<=43/2, then it will not be divisible by any number between 2 and 21. Which tells it is prime. In this approach we are using the recursive function checkPrime(int num1, int index) which takes input number and index which will take values from 2 to num1/2. For base case-: if num1<2 return 1 as it is non-prime. If num1==2 return 2 as it is prime. Else:- if(index<=num1/2) then we reached point upto which no index fully divided num1 so return 1 as it is possible for prime numbers only. Otherwise recurse for next index using result=checkPrime(num1, index+1) Take the input number Num Take the input number Num Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0. Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0. If num1<2 return 0 as numbers less than 2 are non-prime. If num1<2 return 0 as numbers less than 2 are non-prime. If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers. If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers. If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime Recurse for the next index using result=checkPrime(num1, index+1). Recurse for the next index using result=checkPrime(num1, index+1). Return result. Return result. Print result obtained inside main. Print result obtained inside main. #include <bits/stdc++.h> using namespace std; int checkPrime(int num1, int index){ if(num1<2){ return 0; } if (num1 == 2 || num1==3){ return 1; } if (num1 % index == 0){ return 0; } if (index <= num1/2){ return 1; } int result=checkPrime(num1, index+1); return (result); } int main(){ int Num = 31; if (checkPrime(Num,2)==1){ cout <<Num<<" is a Prime number !"; } else{ cout <<Num<<" is non Prime!"; } return 0; } If we run the above code it will generate the following Output 31 is a Prime number!
[ { "code": null, "e": 1186, "s": 1062, "text": "We are given an integer as input. The goal is to find whether the input number Num is a prime or non-prime using recursion." }, { "code": null, "e": 1391, "s": 1186, "text": "To check if a number is prime or not, start traversing from i=2 to i<=Num/2. If any i is fully divisible by Num then the number is non-prime as prime numbers are only divisible by 1 and the number itself." }, { "code": null, "e": 1408, "s": 1391, "text": "Input − Num = 32" }, { "code": null, "e": 1434, "s": 1408, "text": "Output − 32 is non-Prime!" }, { "code": null, "e": 1567, "s": 1434, "text": "Explanation − If we start traversing from i=2 to i<=32/2, then at first it will be fully divisible by 2 which tells it is non-prime." }, { "code": null, "e": 1584, "s": 1567, "text": "Input − Num = 43" }, { "code": null, "e": 1615, "s": 1584, "text": "Output − 43 is a Prime number!" }, { "code": null, "e": 1760, "s": 1615, "text": "Explanation − If we start traversing from i=2 to i<=43/2, then it will not be divisible by any number between 2 and 21. Which tells it is prime." }, { "code": null, "e": 1921, "s": 1760, "text": "In this approach we are using the recursive function checkPrime(int num1, int index) which takes input number and index which will take values from 2 to num1/2." }, { "code": null, "e": 1976, "s": 1921, "text": "For base case-: if num1<2 return 1 as it is non-prime." }, { "code": null, "e": 2012, "s": 1976, "text": "If num1==2 return 2 as it is prime." }, { "code": null, "e": 2224, "s": 2012, "text": "Else:- if(index<=num1/2) then we reached point upto which no index fully divided num1 so return 1 as it is possible for prime numbers only.\nOtherwise recurse for next index using result=checkPrime(num1, index+1)" }, { "code": null, "e": 2250, "s": 2224, "text": "Take the input number Num" }, { "code": null, "e": 2276, "s": 2250, "text": "Take the input number Num" }, { "code": null, "e": 2378, "s": 2276, "text": "Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0." }, { "code": null, "e": 2480, "s": 2378, "text": "Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0." }, { "code": null, "e": 2537, "s": 2480, "text": "If num1<2 return 0 as numbers less than 2 are non-prime." }, { "code": null, "e": 2594, "s": 2537, "text": "If num1<2 return 0 as numbers less than 2 are non-prime." }, { "code": null, "e": 2652, "s": 2594, "text": "If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers." }, { "code": null, "e": 2710, "s": 2652, "text": "If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers." }, { "code": null, "e": 2816, "s": 2710, "text": "If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime" }, { "code": null, "e": 2922, "s": 2816, "text": "If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime" }, { "code": null, "e": 2989, "s": 2922, "text": "Recurse for the next index using result=checkPrime(num1, index+1)." }, { "code": null, "e": 3056, "s": 2989, "text": "Recurse for the next index using result=checkPrime(num1, index+1)." }, { "code": null, "e": 3071, "s": 3056, "text": "Return result." }, { "code": null, "e": 3086, "s": 3071, "text": "Return result." }, { "code": null, "e": 3121, "s": 3086, "text": "Print result obtained inside main." }, { "code": null, "e": 3156, "s": 3121, "text": "Print result obtained inside main." }, { "code": null, "e": 3656, "s": 3156, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint checkPrime(int num1, int index){\n if(num1<2){\n return 0;\n }\n if (num1 == 2 || num1==3){\n return 1;\n }\n if (num1 % index == 0){\n return 0;\n }\n if (index <= num1/2){\n return 1;\n }\n int result=checkPrime(num1, index+1);\n\n return (result);\n}\nint main(){\n int Num = 31;\n if (checkPrime(Num,2)==1){\n cout <<Num<<\" is a Prime number !\";\n }\n else{\n cout <<Num<<\" is non Prime!\";\n }\n\n return 0;\n}" }, { "code": null, "e": 3719, "s": 3656, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 3741, "s": 3719, "text": "31 is a Prime number!" } ]
AI, Cluster Analysis of Categorical Data (Part I) | by Michelangiolo Mazzeschi | Towards Data Science
***The code begins after the Clash Royale introduction: skip, if you are not interested Full code available at my repository. The notebook is called: CRL_Clustering. In this article I will create an AI that, given a dataset of Clash Royale matches, will identify what are the main clusters. All data is categorical, hence I won’t be using a traditional factor analysis technique, but rather a K-Node algorithm. Before explaining the code behind the AI I am going to create, I need to clarify what are meta-decks and how they relate to this project. Professional Videogame players have turned the study of competitive videogames into a real subject. In videogames where you need to prepare your deck from a pool of cards, there is a gigantic number of possible combinations, and from this sea of possibilities emerge a small batch that helps players gain a competitive advantage: the so-called meta-decks. I will be creating an AI that can find which are the meta-decks used in the competitive game called Clash Royale, extracting them from raw data. In this game there is a pool of 98 cards (up to May 2020, every few months the game adds another card). Every player has to compose a deck of 8 cards, to play against other players. The number of possible decks is 6345015248033280, from this pool of combinations, top players find out which are the meta-decks. The meta-decks keep changing now and then, so pros need to stay updated and keep studying the game. Unfortunately, there is no mathematical way to determine which are the best decks. The only possibility that champions have is to try out many of them and see which one plays out better against other players. Essentially, through continuous iterations, the meta-decks are the ones that allow the top players to win with consistency, hence allowed them to climb the hierarchy of competitive players up to the top spots. Therefore, these specific decks survived a selection of millions of matches fought among the community. As you can see, being excellent at something, even at videogames, takes a lot of effort, commitment, and study. Finally, how does the community of players (not only the top 100) find out the meta decks of every season? Thanks to the use of Youtube, Facebook groups, and statistics websites of Clash Royale such as www.statsroyale.com, people can see what the top players play and their win rate. The decks are then copied and used by all the players in the community, average or expert, up to the pro level. Let us now assume that we do not know anything about this videogame and which are the main decks of this season. I have in my possession almost 700 matches (669) played by the top players. What my AI will do is finding out which are the decks that are played more consistently and isolate them. Let’s remember than anybody can edit their deck, so players can easily create a unique variation of a meta-deck that we do not want to take into account to the calculation, so we need an algorithm to figure out which are the original decks rather than the variations. We assume that the variations will be played with less frequency, leaving the original decks with the highest frequency. Within the hierarchy of meta-decks, the level of variations can reach a depth of hundreds due to the frequency of possible changes and experiments from millions of players. Entire Procedure Downloading match datasets with APIPre-processing: personalized sorting of every rowPre-processing: label encoding of the entire datasetPre-processing: one_hot encoding of the entire datasetPerform cluster analysisTrain K-Node algorithmTuning number of clusters to get an accurate resultEstimate the top meta-decks Downloading match datasets with API Pre-processing: personalized sorting of every row Pre-processing: label encoding of the entire dataset Pre-processing: one_hot encoding of the entire dataset Perform cluster analysis Train K-Node algorithm Tuning number of clusters to get an accurate result Estimate the top meta-decks In this article I will cover up to step 3: label encoding the entire dataset. In the next part of the tutorial I will finalize the AI. For your convenience, I already downloaded and prepared the dataset we are going to use for applying clustering on categorical data. If you wish to download your own dataset of Clash Royale matches, please follow this complete guide on how to create an API that downloads the data. X = pd.read_csv('/content/drive/My Drive/Colab Notebooks/CRL daily collector/CRL (1).csv') At the moment, the dataset contains too much information: we will need to get rid of all the columns that do not contain data about player n. 2. The reason is that I downloaded the most recent 25 games of several players selected as player n.1. One player usually plays a single archetype, and if the proportion of our entire dataset that contains repetitively the deck played by a single user is too high, the variance of meta-decks in our dataset would be highly decreased. X = X[['p2.card_1', 'p2.card_2', 'p2.card_3', 'p2.card_4', 'p2.card_5', 'p2.card_6', 'p2.card_7', 'p2.card_8']]X We will only be looking at a list of decks played by player n. 2. ***In my case I imported the data connecting it with my Google Drive. You should edit the first line depending on where you have stored your .csv file. Unfortunately, the data we collected is very chaotic. The order of the cards in every row corresponds to the order of the cards played in one match. A player could start using a Troop, but it may also start using a Spell. To see things clearly, we will need to sort the cards in a specific order. ***The order of the features do not impact the final results. However, I believe this step is necessary to see the final results clearly and in a comprehensive way. In the game, there are essentially four types of cards. They have been conceptualized in this order to allow people to create proper decks. Win conditions Troops Buildings Spells Because the dataset in my possession does not show the type of cards, we will need to create an algorithm capable of converting every card to its corresponding type. This is what I mean by mapping every card to its type: with the following mock list: ['Zap', 'Knight', 'Giant', 'Earthquake', 'Musketeer', 'Ice Spirit', 'Skeletons'] ...the corresponding types will be: ['Spell', 'Troop', 'Troop', 'Win Condition', 'Spell', 'Troop', 'Troop', 'Troop'] I have created a .csv file that maps every existing card with its corresponding Type called CRL_Cards_Classification.csv. #https://docs.google.com/spreadsheets/d/1wIH69gfuCCoPRoWOIyUqQHMKkUfpb4GAxUbBYX8PwRc/edit#gid=1477229539C = pd.read_csv('/content/drive/My Drive/Colab Notebooks/CRL daily collector/CRL_Cards_Classification.csv')cards_classifier = C.copy()#getting rid of the first column, uselesscards_classifier.pop('Type_1')cards_classifier = cards_classifier.values.transpose()cards_classifierdef order_row(list1): #mapping input list made of cards with their type card_dictionary = dict(zip(cards_classifier[0], cards_classifier[1])) card_dictionarylist_tot_classification = list() for m in list1: a = card_dictionary.get(m) list_tot_classification.append(a) list_tot_classification For every deck in the dataset I want all cards sorted in the order: Win Condition, Troop, Building, Spell. To do so, we will first assign an ascending value to each one of the types, so that we know which type comes first: class_dict = {'Win Condition': 0, 'Troop': 1, 'Building': 2, 'Spell': 3} list_tot_num = list() for m in list_tot_classification: a = class_dict.get(m) list_tot_num.append(a)ordered_list = [x for _,x in sorted(zip(list_tot_num, list1))] return ordered_list list1 = ['Arrows', 'Baby Dragon', 'Bomber', 'Golem', 'Lightning', 'Mega Minion', 'Mini P.E.K.K.A', 'Night Witch', 'Cannon']ordered_list = order_row(list1) will become: ordered_list['Golem', 'Baby Dragon', 'Bomber', 'Mega Minion', 'Mini P.E.K.K.A', 'Night Witch', 'Cannon', 'Arrows', 'Lightning'] #sort each row in the dataset based on type orderfor c in range(len(X.values)):X.values[c] = order_row(X.values[c])X = pd.DataFrame(e.X.values) ***If instead, we wanted to order the lists alphabetically, we would use the following code rather than using order_now X.values[c] = sorted(X.values[c]) Now that we have sorted our dataset based on a hierarchy we can comprehend easily, we can start pre-processing it. We will now label the entire dataset, you will understand why later on, and that will be more problematic that labeling a single row. Usually, engineers use scikit-learn tools to easily label categorical data. Unfortunately, scikit-learn and other tools only allow the labeling of a single column at a time. This is an example of why it can represent a problem for us: As you can see, in the first column b = 1, in the second column b = 0. The reason is that the algorithm is applying labeling to each individual column without considering the values in the other columns. To have accurate labeling, we will need to flat everything to one column, then apply the labeling and rebuild the initial dataset: This will be performed using the code below: #flat everything in one listone_row = list()for k in e.X.values:for n in k:one_row.append(n)one_row = pd.DataFrame(one_row)one_row#labeled listfrom sklearn.preprocessing import LabelEncoderle = LabelEncoder()le.fit(one_row[0])one_row_labeled = le.transform(one_row[0])one_row_labeled#rebuild the original dataset and convert it to DataFrameimport numpyX_labeled = numpy.array_split(one_row_labeled, (len(one_row)/8))X_labeled = pd.DataFrame(X_labeled)X_labeled Now that we managed to label correctly each of our features, we can perform one_hot encoding for feeding our dataset into the AI. In my next article I will describe the entire procedure, however, on the notebook available in my repository you will find Part II already. -> GO TO PART II
[ { "code": null, "e": 260, "s": 172, "text": "***The code begins after the Clash Royale introduction: skip, if you are not interested" }, { "code": null, "e": 338, "s": 260, "text": "Full code available at my repository. The notebook is called: CRL_Clustering." }, { "code": null, "e": 583, "s": 338, "text": "In this article I will create an AI that, given a dataset of Clash Royale matches, will identify what are the main clusters. All data is categorical, hence I won’t be using a traditional factor analysis technique, but rather a K-Node algorithm." }, { "code": null, "e": 821, "s": 583, "text": "Before explaining the code behind the AI I am going to create, I need to clarify what are meta-decks and how they relate to this project. Professional Videogame players have turned the study of competitive videogames into a real subject." }, { "code": null, "e": 1077, "s": 821, "text": "In videogames where you need to prepare your deck from a pool of cards, there is a gigantic number of possible combinations, and from this sea of possibilities emerge a small batch that helps players gain a competitive advantage: the so-called meta-decks." }, { "code": null, "e": 1222, "s": 1077, "text": "I will be creating an AI that can find which are the meta-decks used in the competitive game called Clash Royale, extracting them from raw data." }, { "code": null, "e": 1404, "s": 1222, "text": "In this game there is a pool of 98 cards (up to May 2020, every few months the game adds another card). Every player has to compose a deck of 8 cards, to play against other players." }, { "code": null, "e": 1633, "s": 1404, "text": "The number of possible decks is 6345015248033280, from this pool of combinations, top players find out which are the meta-decks. The meta-decks keep changing now and then, so pros need to stay updated and keep studying the game." }, { "code": null, "e": 1842, "s": 1633, "text": "Unfortunately, there is no mathematical way to determine which are the best decks. The only possibility that champions have is to try out many of them and see which one plays out better against other players." }, { "code": null, "e": 2156, "s": 1842, "text": "Essentially, through continuous iterations, the meta-decks are the ones that allow the top players to win with consistency, hence allowed them to climb the hierarchy of competitive players up to the top spots. Therefore, these specific decks survived a selection of millions of matches fought among the community." }, { "code": null, "e": 2268, "s": 2156, "text": "As you can see, being excellent at something, even at videogames, takes a lot of effort, commitment, and study." }, { "code": null, "e": 2664, "s": 2268, "text": "Finally, how does the community of players (not only the top 100) find out the meta decks of every season? Thanks to the use of Youtube, Facebook groups, and statistics websites of Clash Royale such as www.statsroyale.com, people can see what the top players play and their win rate. The decks are then copied and used by all the players in the community, average or expert, up to the pro level." }, { "code": null, "e": 2853, "s": 2664, "text": "Let us now assume that we do not know anything about this videogame and which are the main decks of this season. I have in my possession almost 700 matches (669) played by the top players." }, { "code": null, "e": 2959, "s": 2853, "text": "What my AI will do is finding out which are the decks that are played more consistently and isolate them." }, { "code": null, "e": 3348, "s": 2959, "text": "Let’s remember than anybody can edit their deck, so players can easily create a unique variation of a meta-deck that we do not want to take into account to the calculation, so we need an algorithm to figure out which are the original decks rather than the variations. We assume that the variations will be played with less frequency, leaving the original decks with the highest frequency." }, { "code": null, "e": 3521, "s": 3348, "text": "Within the hierarchy of meta-decks, the level of variations can reach a depth of hundreds due to the frequency of possible changes and experiments from millions of players." }, { "code": null, "e": 3538, "s": 3521, "text": "Entire Procedure" }, { "code": null, "e": 3853, "s": 3538, "text": "Downloading match datasets with APIPre-processing: personalized sorting of every rowPre-processing: label encoding of the entire datasetPre-processing: one_hot encoding of the entire datasetPerform cluster analysisTrain K-Node algorithmTuning number of clusters to get an accurate resultEstimate the top meta-decks" }, { "code": null, "e": 3889, "s": 3853, "text": "Downloading match datasets with API" }, { "code": null, "e": 3939, "s": 3889, "text": "Pre-processing: personalized sorting of every row" }, { "code": null, "e": 3992, "s": 3939, "text": "Pre-processing: label encoding of the entire dataset" }, { "code": null, "e": 4047, "s": 3992, "text": "Pre-processing: one_hot encoding of the entire dataset" }, { "code": null, "e": 4072, "s": 4047, "text": "Perform cluster analysis" }, { "code": null, "e": 4095, "s": 4072, "text": "Train K-Node algorithm" }, { "code": null, "e": 4147, "s": 4095, "text": "Tuning number of clusters to get an accurate result" }, { "code": null, "e": 4175, "s": 4147, "text": "Estimate the top meta-decks" }, { "code": null, "e": 4310, "s": 4175, "text": "In this article I will cover up to step 3: label encoding the entire dataset. In the next part of the tutorial I will finalize the AI." }, { "code": null, "e": 4592, "s": 4310, "text": "For your convenience, I already downloaded and prepared the dataset we are going to use for applying clustering on categorical data. If you wish to download your own dataset of Clash Royale matches, please follow this complete guide on how to create an API that downloads the data." }, { "code": null, "e": 4683, "s": 4592, "text": "X = pd.read_csv('/content/drive/My Drive/Colab Notebooks/CRL daily collector/CRL (1).csv')" }, { "code": null, "e": 5159, "s": 4683, "text": "At the moment, the dataset contains too much information: we will need to get rid of all the columns that do not contain data about player n. 2. The reason is that I downloaded the most recent 25 games of several players selected as player n.1. One player usually plays a single archetype, and if the proportion of our entire dataset that contains repetitively the deck played by a single user is too high, the variance of meta-decks in our dataset would be highly decreased." }, { "code": null, "e": 5272, "s": 5159, "text": "X = X[['p2.card_1', 'p2.card_2', 'p2.card_3', 'p2.card_4', 'p2.card_5', 'p2.card_6', 'p2.card_7', 'p2.card_8']]X" }, { "code": null, "e": 5338, "s": 5272, "text": "We will only be looking at a list of decks played by player n. 2." }, { "code": null, "e": 5490, "s": 5338, "text": "***In my case I imported the data connecting it with my Google Drive. You should edit the first line depending on where you have stored your .csv file." }, { "code": null, "e": 5787, "s": 5490, "text": "Unfortunately, the data we collected is very chaotic. The order of the cards in every row corresponds to the order of the cards played in one match. A player could start using a Troop, but it may also start using a Spell. To see things clearly, we will need to sort the cards in a specific order." }, { "code": null, "e": 5952, "s": 5787, "text": "***The order of the features do not impact the final results. However, I believe this step is necessary to see the final results clearly and in a comprehensive way." }, { "code": null, "e": 6092, "s": 5952, "text": "In the game, there are essentially four types of cards. They have been conceptualized in this order to allow people to create proper decks." }, { "code": null, "e": 6107, "s": 6092, "text": "Win conditions" }, { "code": null, "e": 6114, "s": 6107, "text": "Troops" }, { "code": null, "e": 6124, "s": 6114, "text": "Buildings" }, { "code": null, "e": 6131, "s": 6124, "text": "Spells" }, { "code": null, "e": 6297, "s": 6131, "text": "Because the dataset in my possession does not show the type of cards, we will need to create an algorithm capable of converting every card to its corresponding type." }, { "code": null, "e": 6382, "s": 6297, "text": "This is what I mean by mapping every card to its type: with the following mock list:" }, { "code": null, "e": 6463, "s": 6382, "text": "['Zap', 'Knight', 'Giant', 'Earthquake', 'Musketeer', 'Ice Spirit', 'Skeletons']" }, { "code": null, "e": 6499, "s": 6463, "text": "...the corresponding types will be:" }, { "code": null, "e": 6582, "s": 6499, "text": "['Spell', 'Troop', 'Troop', 'Win Condition', 'Spell', 'Troop', 'Troop', 'Troop']" }, { "code": null, "e": 6704, "s": 6582, "text": "I have created a .csv file that maps every existing card with its corresponding Type called CRL_Cards_Classification.csv." }, { "code": null, "e": 7387, "s": 6704, "text": "#https://docs.google.com/spreadsheets/d/1wIH69gfuCCoPRoWOIyUqQHMKkUfpb4GAxUbBYX8PwRc/edit#gid=1477229539C = pd.read_csv('/content/drive/My Drive/Colab Notebooks/CRL daily collector/CRL_Cards_Classification.csv')cards_classifier = C.copy()#getting rid of the first column, uselesscards_classifier.pop('Type_1')cards_classifier = cards_classifier.values.transpose()cards_classifierdef order_row(list1): #mapping input list made of cards with their type card_dictionary = dict(zip(cards_classifier[0], cards_classifier[1])) card_dictionarylist_tot_classification = list() for m in list1: a = card_dictionary.get(m) list_tot_classification.append(a) list_tot_classification" }, { "code": null, "e": 7494, "s": 7387, "text": "For every deck in the dataset I want all cards sorted in the order: Win Condition, Troop, Building, Spell." }, { "code": null, "e": 7610, "s": 7494, "text": "To do so, we will first assign an ascending value to each one of the types, so that we know which type comes first:" }, { "code": null, "e": 7875, "s": 7610, "text": "class_dict = {'Win Condition': 0, 'Troop': 1, 'Building': 2, 'Spell': 3} list_tot_num = list() for m in list_tot_classification: a = class_dict.get(m) list_tot_num.append(a)ordered_list = [x for _,x in sorted(zip(list_tot_num, list1))] return ordered_list" }, { "code": null, "e": 8034, "s": 7875, "text": "list1 = ['Arrows', 'Baby Dragon', 'Bomber', 'Golem', 'Lightning', 'Mega Minion', 'Mini P.E.K.K.A', 'Night Witch', 'Cannon']ordered_list = order_row(list1)" }, { "code": null, "e": 8047, "s": 8034, "text": "will become:" }, { "code": null, "e": 8183, "s": 8047, "text": "ordered_list['Golem', 'Baby Dragon', 'Bomber', 'Mega Minion', 'Mini P.E.K.K.A', 'Night Witch', 'Cannon', 'Arrows', 'Lightning']" }, { "code": null, "e": 8327, "s": 8183, "text": "#sort each row in the dataset based on type orderfor c in range(len(X.values)):X.values[c] = order_row(X.values[c])X = pd.DataFrame(e.X.values)" }, { "code": null, "e": 8447, "s": 8327, "text": "***If instead, we wanted to order the lists alphabetically, we would use the following code rather than using order_now" }, { "code": null, "e": 8481, "s": 8447, "text": "X.values[c] = sorted(X.values[c])" }, { "code": null, "e": 8730, "s": 8481, "text": "Now that we have sorted our dataset based on a hierarchy we can comprehend easily, we can start pre-processing it. We will now label the entire dataset, you will understand why later on, and that will be more problematic that labeling a single row." }, { "code": null, "e": 8965, "s": 8730, "text": "Usually, engineers use scikit-learn tools to easily label categorical data. Unfortunately, scikit-learn and other tools only allow the labeling of a single column at a time. This is an example of why it can represent a problem for us:" }, { "code": null, "e": 9169, "s": 8965, "text": "As you can see, in the first column b = 1, in the second column b = 0. The reason is that the algorithm is applying labeling to each individual column without considering the values in the other columns." }, { "code": null, "e": 9300, "s": 9169, "text": "To have accurate labeling, we will need to flat everything to one column, then apply the labeling and rebuild the initial dataset:" }, { "code": null, "e": 9345, "s": 9300, "text": "This will be performed using the code below:" }, { "code": null, "e": 9806, "s": 9345, "text": "#flat everything in one listone_row = list()for k in e.X.values:for n in k:one_row.append(n)one_row = pd.DataFrame(one_row)one_row#labeled listfrom sklearn.preprocessing import LabelEncoderle = LabelEncoder()le.fit(one_row[0])one_row_labeled = le.transform(one_row[0])one_row_labeled#rebuild the original dataset and convert it to DataFrameimport numpyX_labeled = numpy.array_split(one_row_labeled, (len(one_row)/8))X_labeled = pd.DataFrame(X_labeled)X_labeled" }, { "code": null, "e": 9936, "s": 9806, "text": "Now that we managed to label correctly each of our features, we can perform one_hot encoding for feeding our dataset into the AI." }, { "code": null, "e": 10076, "s": 9936, "text": "In my next article I will describe the entire procedure, however, on the notebook available in my repository you will find Part II already." } ]
How to replace innerHTML of a div using jQuery?
To replace innerHTML of a div in jQuery, use the html() or text() method. You can try to run the following code to learn how to replace innerHTML of a div: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#button1").click(function(){ $('#demo').html('Demo text'); }); }); </script> </head> <body> <div id="demo">This is <b>Amit</b>! </div> <button id="button1">Replace</button> </body> </html>
[ { "code": null, "e": 1136, "s": 1062, "text": "To replace innerHTML of a div in jQuery, use the html() or text() method." }, { "code": null, "e": 1218, "s": 1136, "text": "You can try to run the following code to learn how to replace innerHTML of a div:" }, { "code": null, "e": 1228, "s": 1218, "text": "Live Demo" }, { "code": null, "e": 1595, "s": 1228, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"#button1\").click(function(){ \n $('#demo').html('Demo text');\n });\n});\n</script>\n</head>\n<body>\n\n<div id=\"demo\">This is <b>Amit</b>!\n</div>\n<button id=\"button1\">Replace</button>\n</body>\n</html>" } ]
Byte string, Unicode string, Raw string — A Guide to all strings in Python | by Guangyuan(Frank) Li | Towards Data Science
“String” in Python? Sounds like the most basic topics that every Python programmer should have already mastered in their first Python tutorial. However, do you know there are at least four types of strings in primitive Python? Do you know how your strings are actually represented in Numpy or Pandas or any other packages? What are the differences and caveats that I need to know? (See below) Here, Let me try to clear some of your confusion based on my own learning experiences. We are going to cover these topics: What are the concepts of “Encoding” and “Decoding”?What is a raw(r) string or format(f) string and when I should use them?What are the differences between Numpy/Pandas string and primitive Python strings? What are the concepts of “Encoding” and “Decoding”? What is a raw(r) string or format(f) string and when I should use them? What are the differences between Numpy/Pandas string and primitive Python strings? To understand the differences between byte string and Unicode string, we first need to know what “Encoding” and “Decoding” are. To store the human-readable characters on computers, we need to encode them into bytes. In contrast, we need to decode the bytes into human-readable characters for representation. Byte, in computer science, indicates a unit of 0/1, commonly of length 8. So characters “Hi” are actually stored as “01001000 01101001” on the computer, which consumes 2 bytes (16-bits). The rule that defines the encoding process is called encoding schema, commonly used ones include “ASCII”, “UTF-8”, etc. Now, the question how do these encoding schemas look like? “ASCII” converts each character into one byte. Since one byte consisted of 8 bits and each bit contains 0/1. The total number of characters “ASCII” can represent is 28=256. It is more than enough for 26 English letters plus some commonly-used characters. See the “ASCII” table for full information. However, 256 characters are obviously not enough for storing all the characters in the world. In light of that, people designed Unicode in which each character will be encoded as a “code point”. For instance, “H” will be represented as code point “U+0048”. According to Wikipedia, Unicode can include 144,697 characters. But again, the code point still can not be recognized by the computer, so we have “UTF-8” or other variants encoding schema to convert the code point to the byte. “UTF-8” means the minimum length of bits to represent a character is 8, so you can guess, “UTF-16” means the minimum length of bits is 16. UTF-8 is way more popular than UTF-16 so in this article and for most of your work as they are compatible with the old original ASCII standard (one character can be represented using one byte), understanding the UTF-8 is enough. See the “UTF-8” table for full information. With the basic concepts understood, let’s cover some practical coding tips in Python. In Python3, the default string is called Unicode string (u string), you can understand them as human-readable characters. As explained above, you can encode them to the byte string (b string), and the byte string can be decoded back to the Unicode string. u'Hi'.encode('ASCII')> b'Hi'b'\x48\x69'.decode('ASCII')> 'Hi' In Python IDE, usually, the byte string will be automatically decoded using “ASCII” when printed out, so that’s why the first result is human-readable (b’Hi'). More often, Byte string should be represented as hex code (b’\x48\x69'), which can be found in any “ASCII” table. To wrap up this section, let’s look at one “UTF-8” example, again the hex code for every character can be found in the UTF-8 table: b'\xe0\xb0\x86'.decode('utf-8')> 'ఆ' To start with this type of string, we just need to know one thing about the default Unicode string (u string) — backslash (“\”) is a special character in Unicode string such that the following character will have the special meanings (i.e. \t, \n, etc). So in order to ignore the special meaning of the backslash, we have the Raw string (r string) in which backslash is just a backslash and it won’t have effects on changing the meaning of its following characters. Here comes my personal suggestions, unless in the scenario where you need to define the regular expression match pattern (See below example), I suggest using the Unicode string with escape (using backslash to ignore special character). As shown in the third example, we used backslash to make sure we output a literal “\” instead of a new tab “\t”. Why I would recommend that? This is because the raw string can not really solve everything, for instance, how to output a literal single quotation in a Raw string? r'ttt'g''File "<ipython-input-76-2839752ff4e6>", line 1 r'ttt'g'' ^SyntaxError: invalid syntax However, using the escape idea along with Unicode string seems to be a more general approach: u'ttt\'g\''> "ttt'g'" The only place that Raw string (r string) may be useful is when you are dealing with regular expression. The regular expression is a whole can of worms and I am not intending to cover that in this article. But when using a regular expression, we usually need to first define a matched pattern where the Raw string would be recommended. import repat = re.compile(r'ENSG\d+$')string = 'ENSG00000555're.search(pat,string)<_sre.SRE_Match object; span=(0, 12), match='ENSG00000555'> For experienced Python programmers, format string should not be an unfamiliar concept, it allows you to dynamically configure the string we want to print. Before Python version 3.5, the recommended approach for creating format string is like that: var = 'hello'print('{} world'.format(var))> hello world Since Python 3.5 and later, there’s a new “f string” to help us to achieve the same goal: var = 'hello'print(f'{var} world')> hello world The important thing I want to note here is, when using format string, curly brace “{}” becomes a very special character and contains its unique meaning. As a result, if we still aim to output the literal “{}”, we need to escape it use double curly brace “{{}}”: '{{}}{}'.format(5)> '{}5' What we covered so far are all about primitive string types in Python, we haven’t touched on how the string is handled in other popular Python packages. Here I am going to share a bit on string types in Numpy and Pandas. In Numpy, usually, String can be specified in three different “dtypes”: Variable-length Unicode (U)Fixed-length byte (S)Python object (O) Variable-length Unicode (U) Fixed-length byte (S) Python object (O) import numpy as nparr1 = np.array(['hello','hi','ha'],dtype='<U5')arr2 = np.array(['hello','hi','ha'],dtype='|S5')arr3 = np.array(['hello','hi','ha'],dtype='object')> array(['hello', 'hi', 'ha'], dtype='<U5')> array([b'hello', b'hi', b'ha'], dtype='|S5')> array(['hello', 'hi', 'ha'], dtype=object) <U5 means the longest one is a string of length 5, however, a more memory-saving way is to use fixed-length |S5 which essentially convert them to byte strings. This is the preferred way if you are trying to convert it to a strong-typed data structure (i.e. store as h5 file). In addition, we can treat strings as Python objects and store them in the Numpy array, since every Python object can be stored in the Numpy array using the “object” type. String in pandas can be represented in two ways: object dtype (most of the time should be fine)string dtype object dtype (most of the time should be fine) string dtype import pandas as pds1 = pd.Series(['hello','hi','ha'],dtype='object')s2 = pd.Series(['hello','hi','ha'],dtype='string')> s10 hello1 hi2 hadtype: object> s20 hello1 hi2 hadtype: string These two types are in general similar, the subtle differences are outlined in the documentation. In summary, we talked about the different representations of “string” in Python. Starting with the default Unicode string (u string), we touched on how it relates to Byte string (b string). Understanding the conversion is very important because sometimes the standard output from other programs will be in the format of bytes, and we need to first decode them to Unicode string for further Streaming operation. We then talked about Raw string (r string) and Format string (f string) and the caveats we need to pay attention to when using them. Finally, we summarised the different ways of string representation in Numpy and Pandas, and special care should be taken when instantiating Numpy or Pandas objects with string because the behaviors will be drastically different than primitive Python strings. That’s about it! I hope you find this article interesting and useful, thanks for reading! If you like this article, follow me on medium, thank you so much for your support. Connect me on my Twitter or LinkedIn, also please let me know if you have any questions or what kind of tutorials you would like to see in the future!
[ { "code": null, "e": 565, "s": 172, "text": "“String” in Python? Sounds like the most basic topics that every Python programmer should have already mastered in their first Python tutorial. However, do you know there are at least four types of strings in primitive Python? Do you know how your strings are actually represented in Numpy or Pandas or any other packages? What are the differences and caveats that I need to know? (See below)" }, { "code": null, "e": 688, "s": 565, "text": "Here, Let me try to clear some of your confusion based on my own learning experiences. We are going to cover these topics:" }, { "code": null, "e": 893, "s": 688, "text": "What are the concepts of “Encoding” and “Decoding”?What is a raw(r) string or format(f) string and when I should use them?What are the differences between Numpy/Pandas string and primitive Python strings?" }, { "code": null, "e": 945, "s": 893, "text": "What are the concepts of “Encoding” and “Decoding”?" }, { "code": null, "e": 1017, "s": 945, "text": "What is a raw(r) string or format(f) string and when I should use them?" }, { "code": null, "e": 1100, "s": 1017, "text": "What are the differences between Numpy/Pandas string and primitive Python strings?" }, { "code": null, "e": 1228, "s": 1100, "text": "To understand the differences between byte string and Unicode string, we first need to know what “Encoding” and “Decoding” are." }, { "code": null, "e": 1595, "s": 1228, "text": "To store the human-readable characters on computers, we need to encode them into bytes. In contrast, we need to decode the bytes into human-readable characters for representation. Byte, in computer science, indicates a unit of 0/1, commonly of length 8. So characters “Hi” are actually stored as “01001000 01101001” on the computer, which consumes 2 bytes (16-bits)." }, { "code": null, "e": 1774, "s": 1595, "text": "The rule that defines the encoding process is called encoding schema, commonly used ones include “ASCII”, “UTF-8”, etc. Now, the question how do these encoding schemas look like?" }, { "code": null, "e": 2073, "s": 1774, "text": "“ASCII” converts each character into one byte. Since one byte consisted of 8 bits and each bit contains 0/1. The total number of characters “ASCII” can represent is 28=256. It is more than enough for 26 English letters plus some commonly-used characters. See the “ASCII” table for full information." }, { "code": null, "e": 2969, "s": 2073, "text": "However, 256 characters are obviously not enough for storing all the characters in the world. In light of that, people designed Unicode in which each character will be encoded as a “code point”. For instance, “H” will be represented as code point “U+0048”. According to Wikipedia, Unicode can include 144,697 characters. But again, the code point still can not be recognized by the computer, so we have “UTF-8” or other variants encoding schema to convert the code point to the byte. “UTF-8” means the minimum length of bits to represent a character is 8, so you can guess, “UTF-16” means the minimum length of bits is 16. UTF-8 is way more popular than UTF-16 so in this article and for most of your work as they are compatible with the old original ASCII standard (one character can be represented using one byte), understanding the UTF-8 is enough. See the “UTF-8” table for full information." }, { "code": null, "e": 3311, "s": 2969, "text": "With the basic concepts understood, let’s cover some practical coding tips in Python. In Python3, the default string is called Unicode string (u string), you can understand them as human-readable characters. As explained above, you can encode them to the byte string (b string), and the byte string can be decoded back to the Unicode string." }, { "code": null, "e": 3373, "s": 3311, "text": "u'Hi'.encode('ASCII')> b'Hi'b'\\x48\\x69'.decode('ASCII')> 'Hi'" }, { "code": null, "e": 3647, "s": 3373, "text": "In Python IDE, usually, the byte string will be automatically decoded using “ASCII” when printed out, so that’s why the first result is human-readable (b’Hi'). More often, Byte string should be represented as hex code (b’\\x48\\x69'), which can be found in any “ASCII” table." }, { "code": null, "e": 3779, "s": 3647, "text": "To wrap up this section, let’s look at one “UTF-8” example, again the hex code for every character can be found in the UTF-8 table:" }, { "code": null, "e": 3816, "s": 3779, "text": "b'\\xe0\\xb0\\x86'.decode('utf-8')> 'ఆ'" }, { "code": null, "e": 4282, "s": 3816, "text": "To start with this type of string, we just need to know one thing about the default Unicode string (u string) — backslash (“\\”) is a special character in Unicode string such that the following character will have the special meanings (i.e. \\t, \\n, etc). So in order to ignore the special meaning of the backslash, we have the Raw string (r string) in which backslash is just a backslash and it won’t have effects on changing the meaning of its following characters." }, { "code": null, "e": 4631, "s": 4282, "text": "Here comes my personal suggestions, unless in the scenario where you need to define the regular expression match pattern (See below example), I suggest using the Unicode string with escape (using backslash to ignore special character). As shown in the third example, we used backslash to make sure we output a literal “\\” instead of a new tab “\\t”." }, { "code": null, "e": 4795, "s": 4631, "text": "Why I would recommend that? This is because the raw string can not really solve everything, for instance, how to output a literal single quotation in a Raw string?" }, { "code": null, "e": 4902, "s": 4795, "text": "r'ttt'g''File \"<ipython-input-76-2839752ff4e6>\", line 1 r'ttt'g'' ^SyntaxError: invalid syntax" }, { "code": null, "e": 4996, "s": 4902, "text": "However, using the escape idea along with Unicode string seems to be a more general approach:" }, { "code": null, "e": 5018, "s": 4996, "text": "u'ttt\\'g\\''> \"ttt'g'\"" }, { "code": null, "e": 5354, "s": 5018, "text": "The only place that Raw string (r string) may be useful is when you are dealing with regular expression. The regular expression is a whole can of worms and I am not intending to cover that in this article. But when using a regular expression, we usually need to first define a matched pattern where the Raw string would be recommended." }, { "code": null, "e": 5496, "s": 5354, "text": "import repat = re.compile(r'ENSG\\d+$')string = 'ENSG00000555're.search(pat,string)<_sre.SRE_Match object; span=(0, 12), match='ENSG00000555'>" }, { "code": null, "e": 5744, "s": 5496, "text": "For experienced Python programmers, format string should not be an unfamiliar concept, it allows you to dynamically configure the string we want to print. Before Python version 3.5, the recommended approach for creating format string is like that:" }, { "code": null, "e": 5800, "s": 5744, "text": "var = 'hello'print('{} world'.format(var))> hello world" }, { "code": null, "e": 5890, "s": 5800, "text": "Since Python 3.5 and later, there’s a new “f string” to help us to achieve the same goal:" }, { "code": null, "e": 5938, "s": 5890, "text": "var = 'hello'print(f'{var} world')> hello world" }, { "code": null, "e": 6200, "s": 5938, "text": "The important thing I want to note here is, when using format string, curly brace “{}” becomes a very special character and contains its unique meaning. As a result, if we still aim to output the literal “{}”, we need to escape it use double curly brace “{{}}”:" }, { "code": null, "e": 6226, "s": 6200, "text": "'{{}}{}'.format(5)> '{}5'" }, { "code": null, "e": 6447, "s": 6226, "text": "What we covered so far are all about primitive string types in Python, we haven’t touched on how the string is handled in other popular Python packages. Here I am going to share a bit on string types in Numpy and Pandas." }, { "code": null, "e": 6519, "s": 6447, "text": "In Numpy, usually, String can be specified in three different “dtypes”:" }, { "code": null, "e": 6585, "s": 6519, "text": "Variable-length Unicode (U)Fixed-length byte (S)Python object (O)" }, { "code": null, "e": 6613, "s": 6585, "text": "Variable-length Unicode (U)" }, { "code": null, "e": 6635, "s": 6613, "text": "Fixed-length byte (S)" }, { "code": null, "e": 6653, "s": 6635, "text": "Python object (O)" }, { "code": null, "e": 6952, "s": 6653, "text": "import numpy as nparr1 = np.array(['hello','hi','ha'],dtype='<U5')arr2 = np.array(['hello','hi','ha'],dtype='|S5')arr3 = np.array(['hello','hi','ha'],dtype='object')> array(['hello', 'hi', 'ha'], dtype='<U5')> array([b'hello', b'hi', b'ha'], dtype='|S5')> array(['hello', 'hi', 'ha'], dtype=object)" }, { "code": null, "e": 7399, "s": 6952, "text": "<U5 means the longest one is a string of length 5, however, a more memory-saving way is to use fixed-length |S5 which essentially convert them to byte strings. This is the preferred way if you are trying to convert it to a strong-typed data structure (i.e. store as h5 file). In addition, we can treat strings as Python objects and store them in the Numpy array, since every Python object can be stored in the Numpy array using the “object” type." }, { "code": null, "e": 7448, "s": 7399, "text": "String in pandas can be represented in two ways:" }, { "code": null, "e": 7507, "s": 7448, "text": "object dtype (most of the time should be fine)string dtype" }, { "code": null, "e": 7554, "s": 7507, "text": "object dtype (most of the time should be fine)" }, { "code": null, "e": 7567, "s": 7554, "text": "string dtype" }, { "code": null, "e": 7781, "s": 7567, "text": "import pandas as pds1 = pd.Series(['hello','hi','ha'],dtype='object')s2 = pd.Series(['hello','hi','ha'],dtype='string')> s10 hello1 hi2 hadtype: object> s20 hello1 hi2 hadtype: string" }, { "code": null, "e": 7879, "s": 7781, "text": "These two types are in general similar, the subtle differences are outlined in the documentation." }, { "code": null, "e": 8682, "s": 7879, "text": "In summary, we talked about the different representations of “string” in Python. Starting with the default Unicode string (u string), we touched on how it relates to Byte string (b string). Understanding the conversion is very important because sometimes the standard output from other programs will be in the format of bytes, and we need to first decode them to Unicode string for further Streaming operation. We then talked about Raw string (r string) and Format string (f string) and the caveats we need to pay attention to when using them. Finally, we summarised the different ways of string representation in Numpy and Pandas, and special care should be taken when instantiating Numpy or Pandas objects with string because the behaviors will be drastically different than primitive Python strings." } ]
Java Program to display table with columns in the output using Formatter
To display table with columns as output, use the Formatter class. For working with Formatter class, import the following package − import java.util.Formatter; Consider an array with some elements. This is the array which we will be shown as output in tabular form − double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 }; While displaying the double array values, use the %f to set spaces − for (double d : arr) { f.format("%14.2f %14.2f %15.2f\n", d, Math.ceil(d), Math.floor(d)); } The following is an example − Live Demo import java.util.Formatter; public class Demo { public static void main(String[] argv) throws Exception { double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 }; Formatter f = new Formatter(); f.format("%15s %15s %15s\n", "Points1", "Points2", "Points3"); System.out.println("The point list...\n"); for (double d : arr) { f.format("%14.2f %14.2f %15.2f\n", d, Math.ceil(d), Math.floor(d)); } System.out.println(f); } } The point list... Points1 Points2 Points3 1.70 2.00 1.00 2.50 3.00 2.00 3.10 4.00 3.00 4.50 5.00 4.00 5.70 6.00 5.00 6.90 7.00 6.00 7.70 8.00 7.00 8.90 9.00 8.00 9.10 10.00 9.00
[ { "code": null, "e": 1193, "s": 1062, "text": "To display table with columns as output, use the Formatter class. For working with Formatter class, import the following package −" }, { "code": null, "e": 1221, "s": 1193, "text": "import java.util.Formatter;" }, { "code": null, "e": 1328, "s": 1221, "text": "Consider an array with some elements. This is the array which we will be shown as output in tabular form −" }, { "code": null, "e": 1392, "s": 1328, "text": "double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 };" }, { "code": null, "e": 1461, "s": 1392, "text": "While displaying the double array values, use the %f to set spaces −" }, { "code": null, "e": 1557, "s": 1461, "text": "for (double d : arr) {\n f.format(\"%14.2f %14.2f %15.2f\\n\", d, Math.ceil(d), Math.floor(d));\n}" }, { "code": null, "e": 1587, "s": 1557, "text": "The following is an example −" }, { "code": null, "e": 1598, "s": 1587, "text": " Live Demo" }, { "code": null, "e": 2082, "s": 1598, "text": "import java.util.Formatter;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n double arr[] = { 1.7, 2.5, 3.1, 4.5, 5.7, 6.9, 7.7, 8.9, 9.1 };\n Formatter f = new Formatter();\n f.format(\"%15s %15s %15s\\n\", \"Points1\", \"Points2\", \"Points3\");\n System.out.println(\"The point list...\\n\");\n for (double d : arr) {\n f.format(\"%14.2f %14.2f %15.2f\\n\", d, Math.ceil(d), Math.floor(d));\n }\n System.out.println(f);\n }\n}" }, { "code": null, "e": 2260, "s": 2082, "text": "The point list...\nPoints1 Points2 Points3\n1.70 2.00 1.00\n2.50 3.00 2.00\n3.10 4.00 3.00\n4.50 5.00 4.00\n5.70 6.00 5.00\n6.90 7.00 6.00\n7.70 8.00 7.00\n8.90 9.00 8.00\n9.10 10.00 9.00" } ]
Coupling in Java - GeeksforGeeks
05 Feb, 2020 In object oriented design, Coupling refers to the degree of direct knowledge that one element has of another. In other words, how often do changes in class A force related changes in class B.There are two types of coupling: Tight coupling : In general, Tight coupling means the two classes often change together. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled.Example : If you want to change the skin, you would also have to change the design of your body as well because the two are joined together – they are tightly coupled. The best example of tight coupling is RMI(Remote Method Invocation).// Java program to illustrate// tight coupling conceptclass Subject { Topic t = new Topic(); public void startReading() { t.understand(); }}class Topic { public void understand() { System.out.println("Tight coupling concept"); }}Explanation: In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method.// Java program to illustrate// tight coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.volume); }}class Box { public int volume; Box(int length, int width, int height) { this.volume = length * width * height; }}Output:125 Explanation:In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class then they reflects in the result of Class Volume.Loose coupling : In simple words, loose coupling means they are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. In order to over come from the problems of tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/POJI model and through dependency injection its possible to achieve loose coupling.Example : If you change your shirt, then you are not forced to change your body – when you can do that, then you have loose coupling. When you can’t do that, then you have tight coupling. The examples of Loose coupling are Interface, JMS.// Java program to illustrate // loose coupling conceptpublic interface Topic{ void understand();}class Topic1 implements Topic {public void understand() { System.out.println("Got it"); }} class Topic2 implements Topic {public void understand() { System.out.println("understand"); }} public class Subject {public static void main(String[] args) { Topic t = new Topic1(); t.understand(); }}Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.// Java program to illustrate// loose coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.getVolume()); }}final class Box { private int volume; Box(int length, int width, int height) { this.volume = length * width * height; } public int getVolume() { return volume; }}Output:125 Explanation : In the above program, there is no dependency between both the classes. If we change anything in the Box classes then we dont have to change anything in Volume class.Which is better tight coupling or loose coupling?In general, Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes test ability etc. loose coupling is a better choice because A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change.Lets have a look on the pictorial view of tight coupling and loose coupling:Difference between tight coupling and loose couplingTight coupling is not good at the test-ability. But loose coupling improves the test ability.Tight coupling does not provide the concept of interface. But loose coupling helps us follow the GOF principle of program to interfaces, not implementations.In Tight coupling, it is not easy to swap the codes between two classes. But it’s much easier to swap other pieces of code/modules/objects/components in loose coupling.Tight coupling does not have the changing capability. But loose coupling is highly changeable.This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Tight coupling : In general, Tight coupling means the two classes often change together. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled.Example : If you want to change the skin, you would also have to change the design of your body as well because the two are joined together – they are tightly coupled. The best example of tight coupling is RMI(Remote Method Invocation).// Java program to illustrate// tight coupling conceptclass Subject { Topic t = new Topic(); public void startReading() { t.understand(); }}class Topic { public void understand() { System.out.println("Tight coupling concept"); }}Explanation: In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method.// Java program to illustrate// tight coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.volume); }}class Box { public int volume; Box(int length, int width, int height) { this.volume = length * width * height; }}Output:125 Explanation:In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class then they reflects in the result of Class Volume. // Java program to illustrate// tight coupling conceptclass Subject { Topic t = new Topic(); public void startReading() { t.understand(); }}class Topic { public void understand() { System.out.println("Tight coupling concept"); }} Explanation: In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method. // Java program to illustrate// tight coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.volume); }}class Box { public int volume; Box(int length, int width, int height) { this.volume = length * width * height; }} Output: 125 Explanation:In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class then they reflects in the result of Class Volume. Loose coupling : In simple words, loose coupling means they are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. In order to over come from the problems of tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/POJI model and through dependency injection its possible to achieve loose coupling.Example : If you change your shirt, then you are not forced to change your body – when you can do that, then you have loose coupling. When you can’t do that, then you have tight coupling. The examples of Loose coupling are Interface, JMS.// Java program to illustrate // loose coupling conceptpublic interface Topic{ void understand();}class Topic1 implements Topic {public void understand() { System.out.println("Got it"); }} class Topic2 implements Topic {public void understand() { System.out.println("understand"); }} public class Subject {public static void main(String[] args) { Topic t = new Topic1(); t.understand(); }}Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.// Java program to illustrate// loose coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.getVolume()); }}final class Box { private int volume; Box(int length, int width, int height) { this.volume = length * width * height; } public int getVolume() { return volume; }}Output:125 Explanation : In the above program, there is no dependency between both the classes. If we change anything in the Box classes then we dont have to change anything in Volume class.Which is better tight coupling or loose coupling?In general, Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes test ability etc. loose coupling is a better choice because A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change.Lets have a look on the pictorial view of tight coupling and loose coupling:Difference between tight coupling and loose couplingTight coupling is not good at the test-ability. But loose coupling improves the test ability.Tight coupling does not provide the concept of interface. But loose coupling helps us follow the GOF principle of program to interfaces, not implementations.In Tight coupling, it is not easy to swap the codes between two classes. But it’s much easier to swap other pieces of code/modules/objects/components in loose coupling.Tight coupling does not have the changing capability. But loose coupling is highly changeable.This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave // Java program to illustrate // loose coupling conceptpublic interface Topic{ void understand();}class Topic1 implements Topic {public void understand() { System.out.println("Got it"); }} class Topic2 implements Topic {public void understand() { System.out.println("understand"); }} public class Subject {public static void main(String[] args) { Topic t = new Topic1(); t.understand(); }} Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user. // Java program to illustrate// loose coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.getVolume()); }}final class Box { private int volume; Box(int length, int width, int height) { this.volume = length * width * height; } public int getVolume() { return volume; }} Output: 125 Explanation : In the above program, there is no dependency between both the classes. If we change anything in the Box classes then we dont have to change anything in Volume class. Which is better tight coupling or loose coupling? In general, Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes test ability etc. loose coupling is a better choice because A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change.Lets have a look on the pictorial view of tight coupling and loose coupling: Difference between tight coupling and loose coupling Tight coupling is not good at the test-ability. But loose coupling improves the test ability. Tight coupling does not provide the concept of interface. But loose coupling helps us follow the GOF principle of program to interfaces, not implementations. In Tight coupling, it is not easy to swap the codes between two classes. But it’s much easier to swap other pieces of code/modules/objects/components in loose coupling. Tight coupling does not have the changing capability. But loose coupling is highly changeable. This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. dasmanaswini10 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java Set in Java LinkedList in Java Collections in Java
[ { "code": null, "e": 24210, "s": 24182, "text": "\n05 Feb, 2020" }, { "code": null, "e": 24434, "s": 24210, "text": "In object oriented design, Coupling refers to the degree of direct knowledge that one element has of another. In other words, how often do changes in class A force related changes in class B.There are two types of coupling:" }, { "code": null, "e": 29655, "s": 24434, "text": "Tight coupling : In general, Tight coupling means the two classes often change together. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled.Example : If you want to change the skin, you would also have to change the design of your body as well because the two are joined together – they are tightly coupled. The best example of tight coupling is RMI(Remote Method Invocation).// Java program to illustrate// tight coupling conceptclass Subject { Topic t = new Topic(); public void startReading() { t.understand(); }}class Topic { public void understand() { System.out.println(\"Tight coupling concept\"); }}Explanation: In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method.// Java program to illustrate// tight coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.volume); }}class Box { public int volume; Box(int length, int width, int height) { this.volume = length * width * height; }}Output:125\nExplanation:In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class then they reflects in the result of Class Volume.Loose coupling : In simple words, loose coupling means they are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. In order to over come from the problems of tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/POJI model and through dependency injection its possible to achieve loose coupling.Example : If you change your shirt, then you are not forced to change your body – when you can do that, then you have loose coupling. When you can’t do that, then you have tight coupling. The examples of Loose coupling are Interface, JMS.// Java program to illustrate // loose coupling conceptpublic interface Topic{ void understand();}class Topic1 implements Topic {public void understand() { System.out.println(\"Got it\"); }} class Topic2 implements Topic {public void understand() { System.out.println(\"understand\"); }} public class Subject {public static void main(String[] args) { Topic t = new Topic1(); t.understand(); }}Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.// Java program to illustrate// loose coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.getVolume()); }}final class Box { private int volume; Box(int length, int width, int height) { this.volume = length * width * height; } public int getVolume() { return volume; }}Output:125\nExplanation : In the above program, there is no dependency between both the classes. If we change anything in the Box classes then we dont have to change anything in Volume class.Which is better tight coupling or loose coupling?In general, Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes test ability etc. loose coupling is a better choice because A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change.Lets have a look on the pictorial view of tight coupling and loose coupling:Difference between tight coupling and loose couplingTight coupling is not good at the test-ability. But loose coupling improves the test ability.Tight coupling does not provide the concept of interface. But loose coupling helps us follow the GOF principle of program to interfaces, not implementations.In Tight coupling, it is not easy to swap the codes between two classes. But it’s much easier to swap other pieces of code/modules/objects/components in loose coupling.Tight coupling does not have the changing capability. But loose coupling is highly changeable.This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31307, "s": 29655, "text": "Tight coupling : In general, Tight coupling means the two classes often change together. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled.Example : If you want to change the skin, you would also have to change the design of your body as well because the two are joined together – they are tightly coupled. The best example of tight coupling is RMI(Remote Method Invocation).// Java program to illustrate// tight coupling conceptclass Subject { Topic t = new Topic(); public void startReading() { t.understand(); }}class Topic { public void understand() { System.out.println(\"Tight coupling concept\"); }}Explanation: In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method.// Java program to illustrate// tight coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.volume); }}class Box { public int volume; Box(int length, int width, int height) { this.volume = length * width * height; }}Output:125\nExplanation:In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class then they reflects in the result of Class Volume." }, { "code": "// Java program to illustrate// tight coupling conceptclass Subject { Topic t = new Topic(); public void startReading() { t.understand(); }}class Topic { public void understand() { System.out.println(\"Tight coupling concept\"); }}", "e": 31572, "s": 31307, "text": null }, { "code": null, "e": 31989, "s": 31572, "text": "Explanation: In the above program the Subject class is dependents on Topic class. In the above program Subject class is tightly coupled with Topic class it means if any change in the Topic class requires Subject class to change. For example, if Topic class understand() method change to gotit() method then you have to change the startReading() method will call gotit() method instead of calling understand() method." }, { "code": "// Java program to illustrate// tight coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.volume); }}class Box { public int volume; Box(int length, int width, int height) { this.volume = length * width * height; }}", "e": 32323, "s": 31989, "text": null }, { "code": null, "e": 32331, "s": 32323, "text": "Output:" }, { "code": null, "e": 32336, "s": 32331, "text": "125\n" }, { "code": null, "e": 32517, "s": 32336, "text": "Explanation:In the above example, there is a strong inter-dependency between both the classes. If there is any change in Box class then they reflects in the result of Class Volume." }, { "code": null, "e": 36087, "s": 32517, "text": "Loose coupling : In simple words, loose coupling means they are mostly independent. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled. In order to over come from the problems of tight coupling between objects, spring framework uses dependency injection mechanism with the help of POJO/POJI model and through dependency injection its possible to achieve loose coupling.Example : If you change your shirt, then you are not forced to change your body – when you can do that, then you have loose coupling. When you can’t do that, then you have tight coupling. The examples of Loose coupling are Interface, JMS.// Java program to illustrate // loose coupling conceptpublic interface Topic{ void understand();}class Topic1 implements Topic {public void understand() { System.out.println(\"Got it\"); }} class Topic2 implements Topic {public void understand() { System.out.println(\"understand\"); }} public class Subject {public static void main(String[] args) { Topic t = new Topic1(); t.understand(); }}Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.// Java program to illustrate// loose coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.getVolume()); }}final class Box { private int volume; Box(int length, int width, int height) { this.volume = length * width * height; } public int getVolume() { return volume; }}Output:125\nExplanation : In the above program, there is no dependency between both the classes. If we change anything in the Box classes then we dont have to change anything in Volume class.Which is better tight coupling or loose coupling?In general, Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes test ability etc. loose coupling is a better choice because A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change.Lets have a look on the pictorial view of tight coupling and loose coupling:Difference between tight coupling and loose couplingTight coupling is not good at the test-ability. But loose coupling improves the test ability.Tight coupling does not provide the concept of interface. But loose coupling helps us follow the GOF principle of program to interfaces, not implementations.In Tight coupling, it is not easy to swap the codes between two classes. But it’s much easier to swap other pieces of code/modules/objects/components in loose coupling.Tight coupling does not have the changing capability. But loose coupling is highly changeable.This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": "// Java program to illustrate // loose coupling conceptpublic interface Topic{ void understand();}class Topic1 implements Topic {public void understand() { System.out.println(\"Got it\"); }} class Topic2 implements Topic {public void understand() { System.out.println(\"understand\"); }} public class Subject {public static void main(String[] args) { Topic t = new Topic1(); t.understand(); }}", "e": 36526, "s": 36087, "text": null }, { "code": null, "e": 36745, "s": 36526, "text": "Explanation : In the above example, Topic1 and Topic2 objects are loosely coupled. It means Topic is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user." }, { "code": "// Java program to illustrate// loose coupling conceptclass Volume { public static void main(String args[]) { Box b = new Box(5,5,5); System.out.println(b.getVolume()); }}final class Box { private int volume; Box(int length, int width, int height) { this.volume = length * width * height; } public int getVolume() { return volume; }}", "e": 37167, "s": 36745, "text": null }, { "code": null, "e": 37175, "s": 37167, "text": "Output:" }, { "code": null, "e": 37180, "s": 37175, "text": "125\n" }, { "code": null, "e": 37360, "s": 37180, "text": "Explanation : In the above program, there is no dependency between both the classes. If we change anything in the Box classes then we dont have to change anything in Volume class." }, { "code": null, "e": 37410, "s": 37360, "text": "Which is better tight coupling or loose coupling?" }, { "code": null, "e": 37919, "s": 37410, "text": "In general, Tight Coupling is bad in but most of the time, because it reduces flexibility and re-usability of code, it makes changes much more difficult, it impedes test ability etc. loose coupling is a better choice because A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change.Lets have a look on the pictorial view of tight coupling and loose coupling:" }, { "code": null, "e": 37972, "s": 37919, "text": "Difference between tight coupling and loose coupling" }, { "code": null, "e": 38066, "s": 37972, "text": "Tight coupling is not good at the test-ability. But loose coupling improves the test ability." }, { "code": null, "e": 38224, "s": 38066, "text": "Tight coupling does not provide the concept of interface. But loose coupling helps us follow the GOF principle of program to interfaces, not implementations." }, { "code": null, "e": 38393, "s": 38224, "text": "In Tight coupling, it is not easy to swap the codes between two classes. But it’s much easier to swap other pieces of code/modules/objects/components in loose coupling." }, { "code": null, "e": 38488, "s": 38393, "text": "Tight coupling does not have the changing capability. But loose coupling is highly changeable." }, { "code": null, "e": 38794, "s": 38488, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 38919, "s": 38794, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38934, "s": 38919, "text": "dasmanaswini10" }, { "code": null, "e": 38939, "s": 38934, "text": "Java" }, { "code": null, "e": 38944, "s": 38939, "text": "Java" }, { "code": null, "e": 39042, "s": 38944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39074, "s": 39042, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 39093, "s": 39074, "text": "Interfaces in Java" }, { "code": null, "e": 39111, "s": 39093, "text": "ArrayList in Java" }, { "code": null, "e": 39143, "s": 39111, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39163, "s": 39143, "text": "Stack Class in Java" }, { "code": null, "e": 39178, "s": 39163, "text": "Stream In Java" }, { "code": null, "e": 39202, "s": 39178, "text": "Singleton Class in Java" }, { "code": null, "e": 39214, "s": 39202, "text": "Set in Java" }, { "code": null, "e": 39233, "s": 39214, "text": "LinkedList in Java" } ]
Undo and redo features in a Tkinter Text widget
Tkinter Text widget is another input widget similar to the Entry widget which accepts multiline user input in a text field. It contains many inbuilt features and functions which helps to configure the default properties of the text widget. However, to add undo/Redo features in the Tkinter text widget, we can use Boolean attributes undo which ensures that the text can be retrieved again. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") # Create a Text widget with undo is set text=Text(win, width=60, height=20, undo=True) text.pack() text.insert(END, "Enter anything Here...") win.mainloop() Run the above code to display a text widget that has Undo/Redo features enabled. To test the feature, write something in the Text widget and press Ctrl+Z to undo or Ctrl+Y to redo the text.
[ { "code": null, "e": 1452, "s": 1062, "text": "Tkinter Text widget is another input widget similar to the Entry widget which accepts multiline user input in a text field. It contains many inbuilt features and functions which helps to configure the default properties of the text widget. However, to add undo/Redo features in the Tkinter text widget, we can use Boolean attributes undo which ensures that the text can be retrieved again." }, { "code": null, "e": 1802, "s": 1452, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a Text widget with undo is set\ntext=Text(win, width=60, height=20, undo=True)\ntext.pack()\n\ntext.insert(END, \"Enter anything Here...\")\n\nwin.mainloop()" }, { "code": null, "e": 1883, "s": 1802, "text": "Run the above code to display a text widget that has Undo/Redo features enabled." }, { "code": null, "e": 1992, "s": 1883, "text": "To test the feature, write something in the Text widget and press Ctrl+Z to undo or Ctrl+Y to redo the text." } ]
Django - Creating a Project
Now that we have installed Django, let's start using it. In Django, every web app you want to create is called a project; and a project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example let's say we want to build a website, the website is our project and, the forum, news, contact engine are applications. This structure makes it easier to move an application between projects since every application is independent. Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the place you want your project to be created, then use this code − $ django-admin startproject myproject This will create a "myproject" folder with the following structure − myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py The “myproject” folder is just your project container, it actually contains two elements − manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code − manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code − $ python manage.py help The “myproject” subfolder − This folder is the actual python package of your project. It contains four files − __init__.py − Just for python, treat this folder as package. settings.py − As the name indicates, your project settings. urls.py − All links of your project and the function to call. A kind of ToC of your project. wsgi.py − If you need to deploy your project over WSGI. The “myproject” subfolder − This folder is the actual python package of your project. It contains four files − __init__.py − Just for python, treat this folder as package. __init__.py − Just for python, treat this folder as package. settings.py − As the name indicates, your project settings. settings.py − As the name indicates, your project settings. urls.py − All links of your project and the function to call. A kind of ToC of your project. urls.py − All links of your project and the function to call. A kind of ToC of your project. wsgi.py − If you need to deploy your project over WSGI. wsgi.py − If you need to deploy your project over WSGI. Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set − DEBUG = True This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'database.sql', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports − MySQL (django.db.backends.mysql) PostGreSQL (django.db.backends.postgresql_psycopg2) Oracle (django.db.backends.oracle) and NoSQL DB MongoDB (django_mongodb_engine) Before setting any new engine, make sure you have the correct db driver installed. You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE... Now that your project is created and configured make sure it's working − $ python manage.py runserver You will get something like the following on running the above code − Validating models... 0 errors found September 03, 2015 - 11:41:50 Django version 1.6.11, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2515, "s": 2045, "text": "Now that we have installed Django, let's start using it. In Django, every web app you want to create is called a project; and a project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example let's say we want to build a website, the website is our project and, the forum, news, contact engine are applications. This structure makes it easier to move an application between projects since every application is independent." }, { "code": null, "e": 2672, "s": 2515, "text": "Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the place you want your project to be created, then use this code −" }, { "code": null, "e": 2711, "s": 2672, "text": "$ django-admin startproject myproject\n" }, { "code": null, "e": 2780, "s": 2711, "text": "This will create a \"myproject\" folder with the following structure −" }, { "code": null, "e": 2883, "s": 2780, "text": "myproject/\n manage.py\n myproject/\n __init__.py\n settings.py\n urls.py\n wsgi.py\n" }, { "code": null, "e": 2974, "s": 2883, "text": "The “myproject” folder is just your project container, it actually contains two elements −" }, { "code": null, "e": 3212, "s": 2974, "text": "manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code −" }, { "code": null, "e": 3450, "s": 3212, "text": "manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code −" }, { "code": null, "e": 3475, "s": 3450, "text": "$ python manage.py help\n" }, { "code": null, "e": 3859, "s": 3475, "text": "The “myproject” subfolder − This folder is the actual python package of your project. It contains four files −\n\n__init__.py − Just for python, treat this folder as package.\nsettings.py − As the name indicates, your project settings.\nurls.py − All links of your project and the function to call. A kind of ToC of your project.\nwsgi.py − If you need to deploy your project over WSGI.\n\n" }, { "code": null, "e": 3970, "s": 3859, "text": "The “myproject” subfolder − This folder is the actual python package of your project. It contains four files −" }, { "code": null, "e": 4031, "s": 3970, "text": "__init__.py − Just for python, treat this folder as package." }, { "code": null, "e": 4092, "s": 4031, "text": "__init__.py − Just for python, treat this folder as package." }, { "code": null, "e": 4152, "s": 4092, "text": "settings.py − As the name indicates, your project settings." }, { "code": null, "e": 4212, "s": 4152, "text": "settings.py − As the name indicates, your project settings." }, { "code": null, "e": 4305, "s": 4212, "text": "urls.py − All links of your project and the function to call. A kind of ToC of your project." }, { "code": null, "e": 4398, "s": 4305, "text": "urls.py − All links of your project and the function to call. A kind of ToC of your project." }, { "code": null, "e": 4454, "s": 4398, "text": "wsgi.py − If you need to deploy your project over WSGI." }, { "code": null, "e": 4510, "s": 4454, "text": "wsgi.py − If you need to deploy your project over WSGI." }, { "code": null, "e": 4634, "s": 4510, "text": "Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set −" }, { "code": null, "e": 4648, "s": 4634, "text": "DEBUG = True\n" }, { "code": null, "e": 4959, "s": 4648, "text": "This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode." }, { "code": null, "e": 5148, "s": 4959, "text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'database.sql',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}" }, { "code": null, "e": 5276, "s": 5148, "text": "Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports −" }, { "code": null, "e": 5309, "s": 5276, "text": "MySQL (django.db.backends.mysql)" }, { "code": null, "e": 5361, "s": 5309, "text": "PostGreSQL (django.db.backends.postgresql_psycopg2)" }, { "code": null, "e": 5409, "s": 5361, "text": "Oracle (django.db.backends.oracle) and NoSQL DB" }, { "code": null, "e": 5441, "s": 5409, "text": "MongoDB (django_mongodb_engine)" }, { "code": null, "e": 5524, "s": 5441, "text": "Before setting any new engine, make sure you have the correct db driver installed." }, { "code": null, "e": 5600, "s": 5524, "text": "You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE..." }, { "code": null, "e": 5673, "s": 5600, "text": "Now that your project is created and configured make sure it's working −" }, { "code": null, "e": 5703, "s": 5673, "text": "$ python manage.py runserver\n" }, { "code": null, "e": 5773, "s": 5703, "text": "You will get something like the following on running the above code −" }, { "code": null, "e": 5986, "s": 5773, "text": "Validating models...\n\n0 errors found\nSeptember 03, 2015 - 11:41:50\nDjango version 1.6.11, using settings 'myproject.settings'\nStarting development server at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n" }, { "code": null, "e": 6021, "s": 5986, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6033, "s": 6021, "text": " John Elder" }, { "code": null, "e": 6068, "s": 6033, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6080, "s": 6068, "text": " John Elder" }, { "code": null, "e": 6113, "s": 6080, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 6125, "s": 6113, "text": " John Elder" }, { "code": null, "e": 6158, "s": 6125, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 6170, "s": 6158, "text": " John Elder" }, { "code": null, "e": 6203, "s": 6170, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 6215, "s": 6203, "text": " John Elder" }, { "code": null, "e": 6249, "s": 6215, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 6263, "s": 6249, "text": " Rathan Kumar" }, { "code": null, "e": 6270, "s": 6263, "text": " Print" }, { "code": null, "e": 6281, "s": 6270, "text": " Add Notes" } ]
Snake and Ladder Problem
We know about the famous game Snake and Ladder. In this game, some rooms are present on the board, with the room number. Some rooms are connected with a ladder or with snakes. When we get a ladder, we can climb up to some rooms to reach near to the destination without moving sequentially. Similarly, when we get some snake, it sends us to a lower room to start the journey again from that room. In this problem, we have to find the minimum number of the dice throw is required to reach start to destination. Input: The starting and ending location of the snake and ladders. Snake: From 26 to 0, From 20 to 8, From 16 to 3, From 18 to 6 Ladder From 2 to 21, From 4 to 7, From 10 to 25, from 19 to 28 Output: Min Dice throws required is 3 minDiceThrow(move, cell) Input: jump location for snake or ladder, and the total number of cells.Output: Minimum number of dice throw required to reach to the final cell. Begin initially mark all cell as unvisited define queue q mark the staring vertex as visited for starting vertex the vertex number := 0 and distance := 0 add starting vertex s into q while q is not empty, do qVert := front element of the queue v := vertex number of qVert if v = cell -1, then //when it is last vertex break the loop delete one item from queue for j := v + 1, to v + 6 and j < cell, increase j by 1, do if j is not visited, then newVert.dist := (qVert.dist + 1) mark v as visited if there is snake or ladder, then newVert.vert := move[j] //jump to that location else newVert.vert := j insert newVert into queue done done return qVert.dist End #include<iostream> #include <queue> using namespace std; struct vertex { int vert; int dist; // Distance of this vertex from source }; int minDiceThrow(int move[], int cell) { bool visited[cell]; for (int i = 0; i < cell; i++) visited[i] = false; //initially all cells are unvisited queue<vertex> q; visited[0] = true; //initially starting from 0 vertex s = {0, 0}; q.push(s); // Enqueue 0'th vertex vertex qVert; while (!q.empty()) { qVert = q.front(); int v = qVert.vert; if (v == cell-1) //when v is the destination vertex break; q.pop(); for (int j=v+1; j<=(v+6) && j<cell; ++j) { //for next 1 to 6 cells if (!visited[j]) { vertex newVert; newVert.dist = (qVert.dist + 1); //initially distance increased by 1 visited[j] = true; if (move[j] != -1) newVert.vert = move[j]; //if jth place have snake or ladder else newVert.vert = j; q.push(newVert); } } } return qVert.dist; //number of minimum dice throw } int main() { int cell = 30; //consider there are 30 cells int moves[cell]; for (int i = 0; i<cell; i++) moves[i] = -1; //initially no snake or ladder are initialized //For ladder in cell i, it jumps to move[i] moves[2] = 21; moves[4] = 7; moves[10] = 25; moves[19] = 28; //For snake in cell i, it jumps to move[i] moves[26] = 0; moves[20] = 8; moves[16] = 3; moves[18] = 6; cout << "Min Dice throws required is " << minDiceThrow(moves, cell); } Min Dice throws required is 3
[ { "code": null, "e": 1458, "s": 1062, "text": "We know about the famous game Snake and Ladder. In this game, some rooms are present on the board, with the room number. Some rooms are connected with a ladder or with snakes. When we get a ladder, we can climb up to some rooms to reach near to the destination without moving sequentially. Similarly, when we get some snake, it sends us to a lower room to start the journey again from that room." }, { "code": null, "e": 1571, "s": 1458, "text": "In this problem, we have to find the minimum number of the dice throw is required to reach start to destination." }, { "code": null, "e": 1800, "s": 1571, "text": "Input:\nThe starting and ending location of the snake and ladders.\nSnake: From 26 to 0, From 20 to 8, From 16 to 3, From 18 to 6\nLadder From 2 to 21, From 4 to 7, From 10 to 25, from 19 to 28\nOutput:\nMin Dice throws required is 3" }, { "code": null, "e": 1825, "s": 1800, "text": "minDiceThrow(move, cell)" }, { "code": null, "e": 1971, "s": 1825, "text": "Input: jump location for snake or ladder, and the total number of cells.Output: Minimum number of dice throw required to reach to the final cell." }, { "code": null, "e": 2784, "s": 1971, "text": "Begin\n initially mark all cell as unvisited\n define queue q\n mark the staring vertex as visited\n\n for starting vertex the vertex number := 0 and distance := 0\n add starting vertex s into q\n while q is not empty, do\n qVert := front element of the queue\n v := vertex number of qVert\n if v = cell -1, then //when it is last vertex\n break the loop\n delete one item from queue\n for j := v + 1, to v + 6 and j < cell, increase j by 1, do\n if j is not visited, then\n newVert.dist := (qVert.dist + 1)\n mark v as visited\n if there is snake or ladder, then\n newVert.vert := move[j] //jump to that location\n else\n newVert.vert := j\n insert newVert into queue\n done\n done\n return qVert.dist\nEnd" }, { "code": null, "e": 4470, "s": 2784, "text": "#include<iostream>\n#include <queue>\nusing namespace std;\n\nstruct vertex {\n int vert;\n int dist; // Distance of this vertex from source\n};\n\nint minDiceThrow(int move[], int cell) {\n bool visited[cell];\n for (int i = 0; i < cell; i++)\n visited[i] = false; //initially all cells are unvisited\n\n queue<vertex> q;\n\n visited[0] = true; //initially starting from 0\n vertex s = {0, 0};\n q.push(s); // Enqueue 0'th vertex\n\n vertex qVert;\n while (!q.empty()) {\n qVert = q.front();\n int v = qVert.vert;\n\n if (v == cell-1) //when v is the destination vertex\n break;\n\n q.pop();\n for (int j=v+1; j<=(v+6) && j<cell; ++j) { //for next 1 to 6 cells\n if (!visited[j]) {\n vertex newVert;\n newVert.dist = (qVert.dist + 1); //initially distance increased by 1\n visited[j] = true;\n\n if (move[j] != -1)\n newVert.vert = move[j]; //if jth place have snake or ladder\n else\n newVert.vert = j;\n q.push(newVert);\n }\n }\n }\n return qVert.dist; //number of minimum dice throw\n}\n\nint main() {\n int cell = 30; //consider there are 30 cells\n int moves[cell];\n\n for (int i = 0; i<cell; i++)\n moves[i] = -1; //initially no snake or ladder are initialized\n\n //For ladder in cell i, it jumps to move[i]\n moves[2] = 21;\n moves[4] = 7;\n moves[10] = 25;\n moves[19] = 28;\n\n //For snake in cell i, it jumps to move[i]\n moves[26] = 0;\n moves[20] = 8;\n moves[16] = 3;\n moves[18] = 6;\n\n cout << \"Min Dice throws required is \" << minDiceThrow(moves, cell);\n}" }, { "code": null, "e": 4500, "s": 4470, "text": "Min Dice throws required is 3" } ]
expr - Unix, Linux Command
expr - Evaluate an expression expr EXPRESSION expr OPTION expr is a command line Unix utility which evaluates an expression and outputs the corresponding value. expr evaluates integer or string expressions, including pattern matching regular expressions. Most of the challenge posed in writing expressions is preventing the invoking command line shell from acting on characters intended for expr to process. The operators available for integers: addition, subtraction, multiplication, division and modulus for strings: find regular expression, find a set of characters in a string; in some versions: find substring, length of string for either: comparison (equal, not equal, less than, etc.) Example-1: To perform addition of two numbers: $ expr 3 + 5 output: 8 Example-2: To perform substraction of two numbers: $ expr 5 - 3 output: 2 Example-3: To perform multiplication of two numbers ( note: The multiplication operator (*) must be escaped when used in an arithmetic expression with expr ) $ expr 5 \* 3 output: 15 Example-4: To perform division operation: $ expr 10 / 2 output: 5 Example-5: To increament variable : $ y=10 $ y=`expr $y + 1` $ echo $y output:11 Example-6: To find length of string a=hello b=`expr length $a` echo $b output: 5 Example-7: To find the index/position of character in a string a=hello b=`expr index $a l` echo $b output: 3 ( as letter l is at position 3.) Example-8: To find substring of string: a=hello b=`expr substr $a 2 3` ( where 2 is position and 3 is length, command is to get substring from position 2 of length 3 characters) echo $b output: ell Example-9: The following is an example involving boolean expressions ( |- or operator ): $ expr length "abcdef" "<" 5 "|" 15 - 4 ">" 8output:1 Example-10: The following is an example involving boolean expressions ( & - and operator ): $ expr length "abcdef" "<" 5 "&" 15 - 4 ">" 8output:0 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10607, "s": 10577, "text": "expr - Evaluate an expression" }, { "code": null, "e": 10635, "s": 10607, "text": "expr EXPRESSION\nexpr OPTION" }, { "code": null, "e": 11273, "s": 10635, "text": "expr is a command line Unix utility which evaluates an expression and outputs the corresponding value. \nexpr evaluates integer or string expressions, including pattern matching regular expressions. \nMost of the challenge posed in writing expressions is preventing the invoking command line shell from acting on characters intended\nfor expr to process.\n\nThe operators available\n\nfor integers: addition, subtraction, multiplication, division and modulus\nfor strings: find regular expression, find a set of characters in a string; in some versions: find substring, length of string\nfor either: comparison (equal, not equal, less than, etc.)" }, { "code": null, "e": 11284, "s": 11273, "text": "Example-1:" }, { "code": null, "e": 11320, "s": 11284, "text": "To perform addition of two numbers:" }, { "code": null, "e": 11333, "s": 11320, "text": "$ expr 3 + 5" }, { "code": null, "e": 11341, "s": 11333, "text": "output:" }, { "code": null, "e": 11343, "s": 11341, "text": "8" }, { "code": null, "e": 11354, "s": 11343, "text": "Example-2:" }, { "code": null, "e": 11395, "s": 11354, "text": "To perform substraction of two numbers:" }, { "code": null, "e": 11408, "s": 11395, "text": "$ expr 5 - 3" }, { "code": null, "e": 11416, "s": 11408, "text": "output:" }, { "code": null, "e": 11418, "s": 11416, "text": "2" }, { "code": null, "e": 11429, "s": 11418, "text": "Example-3:" }, { "code": null, "e": 11576, "s": 11429, "text": "To perform multiplication of two numbers ( note: The multiplication operator (*) must be escaped when used in an arithmetic expression with expr )" }, { "code": null, "e": 11590, "s": 11576, "text": "$ expr 5 \\* 3" }, { "code": null, "e": 11598, "s": 11590, "text": "output:" }, { "code": null, "e": 11601, "s": 11598, "text": "15" }, { "code": null, "e": 11612, "s": 11601, "text": "Example-4:" }, { "code": null, "e": 11643, "s": 11612, "text": "To perform division operation:" }, { "code": null, "e": 11657, "s": 11643, "text": "$ expr 10 / 2" }, { "code": null, "e": 11665, "s": 11657, "text": "output:" }, { "code": null, "e": 11667, "s": 11665, "text": "5" }, { "code": null, "e": 11678, "s": 11667, "text": "Example-5:" }, { "code": null, "e": 11703, "s": 11678, "text": "To increament variable :" }, { "code": null, "e": 11710, "s": 11703, "text": "$ y=10" }, { "code": null, "e": 11728, "s": 11710, "text": "$ y=`expr $y + 1`" }, { "code": null, "e": 11738, "s": 11728, "text": "$ echo $y" }, { "code": null, "e": 11748, "s": 11738, "text": "output:11" }, { "code": null, "e": 11759, "s": 11748, "text": "Example-6:" }, { "code": null, "e": 11784, "s": 11759, "text": "To find length of string" }, { "code": null, "e": 11792, "s": 11784, "text": "a=hello" }, { "code": null, "e": 11811, "s": 11792, "text": "b=`expr length $a`" }, { "code": null, "e": 11819, "s": 11811, "text": "echo $b" }, { "code": null, "e": 11827, "s": 11819, "text": "output:" }, { "code": null, "e": 11829, "s": 11827, "text": "5" }, { "code": null, "e": 11840, "s": 11829, "text": "Example-7:" }, { "code": null, "e": 11892, "s": 11840, "text": "To find the index/position of character in a string" }, { "code": null, "e": 11900, "s": 11892, "text": "a=hello" }, { "code": null, "e": 11920, "s": 11900, "text": "b=`expr index $a l`" }, { "code": null, "e": 11928, "s": 11920, "text": "echo $b" }, { "code": null, "e": 11936, "s": 11928, "text": "output:" }, { "code": null, "e": 11972, "s": 11936, "text": "3 ( as letter l is at position 3.)" }, { "code": null, "e": 11983, "s": 11972, "text": "Example-8:" }, { "code": null, "e": 12012, "s": 11983, "text": "To find substring of string:" }, { "code": null, "e": 12020, "s": 12012, "text": "a=hello" }, { "code": null, "e": 12150, "s": 12020, "text": "b=`expr substr $a 2 3` ( where 2 is position and 3 is length, command is to get substring from position 2 of length 3 characters)" }, { "code": null, "e": 12158, "s": 12150, "text": "echo $b" }, { "code": null, "e": 12166, "s": 12158, "text": "output:" }, { "code": null, "e": 12170, "s": 12166, "text": "ell" }, { "code": null, "e": 12181, "s": 12170, "text": "Example-9:" }, { "code": null, "e": 12260, "s": 12181, "text": "The following is an example involving boolean expressions ( |- or operator ):" }, { "code": null, "e": 12325, "s": 12260, "text": "$ expr length \"abcdef\" \"<\" 5 \"|\" 15 - 4 \">\" 8output:1 " }, { "code": null, "e": 12337, "s": 12325, "text": "Example-10:" }, { "code": null, "e": 12417, "s": 12337, "text": "The following is an example involving boolean expressions ( & - and operator ):" }, { "code": null, "e": 12480, "s": 12417, "text": "$ expr length \"abcdef\" \"<\" 5 \"&\" 15 - 4 \">\" 8output:0" }, { "code": null, "e": 12515, "s": 12480, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 12543, "s": 12515, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12577, "s": 12543, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12594, "s": 12577, "text": " Frahaan Hussain" }, { "code": null, "e": 12627, "s": 12594, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 12638, "s": 12627, "text": " Pradeep D" }, { "code": null, "e": 12673, "s": 12638, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12689, "s": 12673, "text": " Musab Zayadneh" }, { "code": null, "e": 12722, "s": 12689, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 12734, "s": 12722, "text": " GUHARAJANM" }, { "code": null, "e": 12766, "s": 12734, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 12774, "s": 12766, "text": " Uplatz" }, { "code": null, "e": 12781, "s": 12774, "text": " Print" }, { "code": null, "e": 12792, "s": 12781, "text": " Add Notes" } ]
Capitalize the first and last character of each word in a string - GeeksforGeeks
21 May, 2021 Given the string, the task is to capitalise the first and last character of each word in a string.Examples: Input: Geeks for geeks Output: GeekS FoR GeekS Input: Geeksforgeeks is best Output: GeeksforgeekS IS BesT Approach Create a character array of the String Run a loop from the first letter to the last letter. Check if the character is the starting or end of the word Check if the character is a small letter. If yes, then Capitalise the character of the string. Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // CPP program to capitalise the first// and last character of each word in a string.#include<bits/stdc++.h>using namespace std; string FirstAndLast(string str){ // Create an equivalent string // of the given string string ch = str; for (int i = 0; i < ch.length(); i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.length() && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return ch;} // Driver codeint main(){ string str = "Geeks for Geeks"; cout << str << "\n"; cout << FirstAndLast(str);} // This code is contributed by ihritik // Java program to capitalise the first// and last character of each word in a string. class GFG { static String FirstAndLast(String str) { // Create an equivalent char array // of given string char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.length && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return new String(ch); } // Driver code public static void main(String args[]) { String str = "Geeks for Geeks"; System.out.println(str); System.out.println(FirstAndLast(str)); }} # Python3 program to capitalise the first# and last character of each word in a string.def FirstAndLast(string) : # Create an equivalent char array # of given string ch = list(string); i = 0 ; while i < len(ch): # k stores index of first character # and i is going to store index of last # character. k = i; while (i < len(ch) and ch[i] != ' ') : i += 1; # Check if the character is a small letter # If yes, then Capitalise if (ord(ch[k]) >= 97 and ord(ch[k]) <= 122 ): ch[k] = chr(ord(ch[k]) - 32); else : ch[k] = ch[k] if (ord(ch[i - 1]) >= 90 and ord(ch[i - 1]) <= 122 ): ch[i - 1] = chr(ord(ch[i - 1]) - 32); else : ch[i - 1] = ch[i - 1] i += 1 return "" . join(ch); # Driver codeif __name__ == "__main__" : string = "Geeks for Geeks"; print(string); print(FirstAndLast(string)); # This code is contributed by Ryuga // C# program to remove the first// and last character of each word in a string.using System; class GFG{ static String FirstAndLast(String str) { // Create an equivalent char array // of given string char[] ch = str.ToCharArray(); for (int i = 0; i < ch.Length; i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.Length && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return new String(ch); } // Driver code public static void Main(String []args) { String str = "Geeks for Geeks"; Console.WriteLine(str); Console.WriteLine(FirstAndLast(str)); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to capitalise the first// and last character of each word in a string. function FirstAndLast($str){ // Create an equivalent string // of the given string $ch = $str; for ($i = 0; $i < strlen($ch); $i++) { // $k stores index of first character // and $i is going to store index of last // character. $k = $i; while ($i < strlen($ch) && $ch[$i] != ' ') $i++; // Check if the character is a small letter // If yes, then Capitalise $ch[$k] = chr(($ch[$k] >= 'a' && $ch[$k] <= 'z') ? (ord($ch[$k]) - 32) : (ord($ch[$k]))); $ch[$i - 1] = chr(($ch[$i - 1] >= 'a' && $ch[$i - 1] <= 'z' ) ? (ord($ch[$i - 1]) - 32) : (ord($ch[$i - 1]))); } return $ch;} // Driver code $str = "Geeks for Geeks";echo $str, "\n";echo FirstAndLast($str); // This code is contributed by ihritik ?> <script> // JavaScript program to capitalise the first// and last character of each word in a string. function FirstAndLast(str){ // Create an equivalent string // of the given string var ch = str.split(''); for (var i = 0; i < ch.length; i++) { // k stores index of first character // and i is going to store index of last // character. var k = i; while (i < ch.length && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = String.fromCharCode(ch[k] >= 'a' && ch[k] <= 'z' ? (ch[k].charCodeAt(0) - 32) : ch[k].charCodeAt(0)); ch[i - 1] = String.fromCharCode(ch[i - 1] >= 'a' && ch[i - 1] <= 'z'? (ch[i - 1].charCodeAt(0) - 32) : ch[i - 1].charCodeAt(0)); } return ch.join('');} // Driver code var str = "Geeks for Geeks";document.write( str + "<br>");document.write( FirstAndLast(str)); </script> Geeks for Geeks GeekS FoR GeekS princiraj1992 ankthon ihritik importantly school-programming Java Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Iterate HashMap in Java? Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Modulo or Remainder Operator in Java Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24513, "s": 24485, "text": "\n21 May, 2021" }, { "code": null, "e": 24623, "s": 24513, "text": "Given the string, the task is to capitalise the first and last character of each word in a string.Examples: " }, { "code": null, "e": 24730, "s": 24623, "text": "Input: Geeks for geeks\nOutput: GeekS FoR GeekS\n\nInput: Geeksforgeeks is best\nOutput: GeeksforgeekS IS BesT" }, { "code": null, "e": 24741, "s": 24730, "text": "Approach " }, { "code": null, "e": 24780, "s": 24741, "text": "Create a character array of the String" }, { "code": null, "e": 24833, "s": 24780, "text": "Run a loop from the first letter to the last letter." }, { "code": null, "e": 24891, "s": 24833, "text": "Check if the character is the starting or end of the word" }, { "code": null, "e": 24933, "s": 24891, "text": "Check if the character is a small letter." }, { "code": null, "e": 24986, "s": 24933, "text": "If yes, then Capitalise the character of the string." }, { "code": null, "e": 25039, "s": 24986, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 25043, "s": 25039, "text": "C++" }, { "code": null, "e": 25048, "s": 25043, "text": "Java" }, { "code": null, "e": 25056, "s": 25048, "text": "Python3" }, { "code": null, "e": 25059, "s": 25056, "text": "C#" }, { "code": null, "e": 25063, "s": 25059, "text": "PHP" }, { "code": null, "e": 25074, "s": 25063, "text": "Javascript" }, { "code": "// CPP program to capitalise the first// and last character of each word in a string.#include<bits/stdc++.h>using namespace std; string FirstAndLast(string str){ // Create an equivalent string // of the given string string ch = str; for (int i = 0; i < ch.length(); i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.length() && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return ch;} // Driver codeint main(){ string str = \"Geeks for Geeks\"; cout << str << \"\\n\"; cout << FirstAndLast(str);} // This code is contributed by ihritik", "e": 26112, "s": 25074, "text": null }, { "code": "// Java program to capitalise the first// and last character of each word in a string. class GFG { static String FirstAndLast(String str) { // Create an equivalent char array // of given string char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.length && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return new String(ch); } // Driver code public static void main(String args[]) { String str = \"Geeks for Geeks\"; System.out.println(str); System.out.println(FirstAndLast(str)); }}", "e": 27283, "s": 26112, "text": null }, { "code": "# Python3 program to capitalise the first# and last character of each word in a string.def FirstAndLast(string) : # Create an equivalent char array # of given string ch = list(string); i = 0 ; while i < len(ch): # k stores index of first character # and i is going to store index of last # character. k = i; while (i < len(ch) and ch[i] != ' ') : i += 1; # Check if the character is a small letter # If yes, then Capitalise if (ord(ch[k]) >= 97 and ord(ch[k]) <= 122 ): ch[k] = chr(ord(ch[k]) - 32); else : ch[k] = ch[k] if (ord(ch[i - 1]) >= 90 and ord(ch[i - 1]) <= 122 ): ch[i - 1] = chr(ord(ch[i - 1]) - 32); else : ch[i - 1] = ch[i - 1] i += 1 return \"\" . join(ch); # Driver codeif __name__ == \"__main__\" : string = \"Geeks for Geeks\"; print(string); print(FirstAndLast(string)); # This code is contributed by Ryuga", "e": 28365, "s": 27283, "text": null }, { "code": "// C# program to remove the first// and last character of each word in a string.using System; class GFG{ static String FirstAndLast(String str) { // Create an equivalent char array // of given string char[] ch = str.ToCharArray(); for (int i = 0; i < ch.Length; i++) { // k stores index of first character // and i is going to store index of last // character. int k = i; while (i < ch.Length && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = (char)(ch[k] >= 'a' && ch[k] <= 'z' ? ((int)ch[k] - 32) : (int)ch[k]); ch[i - 1] = (char)(ch[i - 1] >= 'a' && ch[i - 1] <= 'z' ? ((int)ch[i - 1] - 32) : (int)ch[i - 1]); } return new String(ch); } // Driver code public static void Main(String []args) { String str = \"Geeks for Geeks\"; Console.WriteLine(str); Console.WriteLine(FirstAndLast(str)); }} /* This code contributed by PrinciRaj1992 */", "e": 29580, "s": 28365, "text": null }, { "code": "<?php// PHP program to capitalise the first// and last character of each word in a string. function FirstAndLast($str){ // Create an equivalent string // of the given string $ch = $str; for ($i = 0; $i < strlen($ch); $i++) { // $k stores index of first character // and $i is going to store index of last // character. $k = $i; while ($i < strlen($ch) && $ch[$i] != ' ') $i++; // Check if the character is a small letter // If yes, then Capitalise $ch[$k] = chr(($ch[$k] >= 'a' && $ch[$k] <= 'z') ? (ord($ch[$k]) - 32) : (ord($ch[$k]))); $ch[$i - 1] = chr(($ch[$i - 1] >= 'a' && $ch[$i - 1] <= 'z' ) ? (ord($ch[$i - 1]) - 32) : (ord($ch[$i - 1]))); } return $ch;} // Driver code $str = \"Geeks for Geeks\";echo $str, \"\\n\";echo FirstAndLast($str); // This code is contributed by ihritik ?>", "e": 30504, "s": 29580, "text": null }, { "code": "<script> // JavaScript program to capitalise the first// and last character of each word in a string. function FirstAndLast(str){ // Create an equivalent string // of the given string var ch = str.split(''); for (var i = 0; i < ch.length; i++) { // k stores index of first character // and i is going to store index of last // character. var k = i; while (i < ch.length && ch[i] != ' ') i++; // Check if the character is a small letter // If yes, then Capitalise ch[k] = String.fromCharCode(ch[k] >= 'a' && ch[k] <= 'z' ? (ch[k].charCodeAt(0) - 32) : ch[k].charCodeAt(0)); ch[i - 1] = String.fromCharCode(ch[i - 1] >= 'a' && ch[i - 1] <= 'z'? (ch[i - 1].charCodeAt(0) - 32) : ch[i - 1].charCodeAt(0)); } return ch.join('');} // Driver code var str = \"Geeks for Geeks\";document.write( str + \"<br>\");document.write( FirstAndLast(str)); </script>", "e": 31509, "s": 30504, "text": null }, { "code": null, "e": 31541, "s": 31509, "text": "Geeks for Geeks\nGeekS FoR GeekS" }, { "code": null, "e": 31557, "s": 31543, "text": "princiraj1992" }, { "code": null, "e": 31565, "s": 31557, "text": "ankthon" }, { "code": null, "e": 31573, "s": 31565, "text": "ihritik" }, { "code": null, "e": 31585, "s": 31573, "text": "importantly" }, { "code": null, "e": 31604, "s": 31585, "text": "school-programming" }, { "code": null, "e": 31618, "s": 31604, "text": "Java Programs" }, { "code": null, "e": 31626, "s": 31618, "text": "Strings" }, { "code": null, "e": 31634, "s": 31626, "text": "Strings" }, { "code": null, "e": 31732, "s": 31634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31741, "s": 31732, "text": "Comments" }, { "code": null, "e": 31754, "s": 31741, "text": "Old Comments" }, { "code": null, "e": 31786, "s": 31754, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 31834, "s": 31786, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 31885, "s": 31834, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 31919, "s": 31885, "text": "Java Program to Write into a File" }, { "code": null, "e": 31956, "s": 31919, "text": "Modulo or Remainder Operator in Java" }, { "code": null, "e": 31981, "s": 31956, "text": "Reverse a string in Java" }, { "code": null, "e": 32027, "s": 31981, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32061, "s": 32027, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32121, "s": 32061, "text": "Write a program to print all permutations of a given string" } ]
Nuts and Bolt Problem
A list of different nuts and another list of bolts are given. Our task is to find the correct match of nuts and bolts from the given list, and assign that nut with the Bolt, when it is matched. This problem is solved by the quick-sort technique. By taking the last element of the bolt as a pivot, rearrange the nuts list and get the final position of the nut whose bolt is the pivot element. After partitioning the nuts list, we can partition the bolts list using the selected nut. The same tasks are performed for left and right sub-lists to get all matches. Input: The lists of locks and keys. nuts = { ),@,*,^,(,%, !,$,&,#} bolts = { !, (, #, %, ), ^, &, *, $, @ } Output: After matching nuts and bolts: Nuts: ! # $ % & ( ) * @ ^ Bolts: ! # $ % & ( ) * @ ^ partition(array, low, high, pivot) Input: One array, the low and high index, the pivot element. Output: Final location of pivot element. Begin i := low for j in range low to high, do if array[j] < pivot, then swap array[i] and array[j] increase i by 1 else if array[j] = pivot, then swap array[j] and array[high] decrease j by 1 done swap array[i] and array[high] return i End nutAndBoltMatch(nuts, bolts, low, high) Input: The list of nuts, the list of bolts, lower and higher index of the array. Output: Display which nut is for which bolt. Begin pivotLoc := partition(nuts, low, high, bolts[high]) partition(bolts, low, high, nuts[pivotLoc]) nutAndBoltMatch(nuts, bolts, low, pivotLoc-1) nutAndBoltMatch(nuts, bolts, pivotLoc + 1, high) End #include<iostream> using namespace std; void show(char array[], int n) { for(int i = 0; i<n; i++) cout << array[i] << " "; } int partition(char array[], int low, int high, char pivot) { //find location of pivot for quick sort int i = low; for(int j = low; j<high; j++) { if(array[j] <pivot) { //when jth element less than pivot, swap ith and jth element swap(array[i], array[j]); i++; }else if(array[j] == pivot) { //when jth element is same as pivot, swap jth and last element swap(array[j], array[high]); j--; } } swap(array[i], array[high]); return i; //the location of pivot element } void nutAndBoltMatch(char nuts[], char bolts[], int low, int high) { if(low < high) { int pivotLoc = partition(nuts, low, high, bolts[high]); //choose item from bolt to nut partitioning partition(bolts, low, high, nuts[pivotLoc]); //place previous pivot location in bolt also nutAndBoltMatch(nuts, bolts, low, pivotLoc - 1); nutAndBoltMatch(nuts, bolts, pivotLoc+1, high); } } int main() { char nuts[] = {')','@','*','^','(','%','!','$','&','#'}; char bolts[] = {'!','(','#','%',')','^','&','*','$','@'}; int n = 10; nutAndBoltMatch(nuts, bolts, 0, n-1); cout << "After matching nuts and bolts:"<< endl; cout << "Nuts: "; show(nuts, n); cout << endl; cout << "Bolts: "; show(bolts, n); cout << endl; } After matching nuts and bolts: Nuts: ! # $ % & ( ) * @ ^ Bolts: ! # $ % & ( ) * @ ^
[ { "code": null, "e": 1256, "s": 1062, "text": "A list of different nuts and another list of bolts are given. Our task is to find the correct match of nuts and bolts from the given list, and assign that nut with the Bolt, when it is matched." }, { "code": null, "e": 1622, "s": 1256, "text": "This problem is solved by the quick-sort technique. By taking the last element of the bolt as a pivot, rearrange the nuts list and get the final position of the nut whose bolt is the pivot element. After partitioning the nuts list, we can partition the bolts list using the selected nut. The same tasks are performed for left and right sub-lists to get all matches." }, { "code": null, "e": 1823, "s": 1622, "text": "Input:\nThe lists of locks and keys.\nnuts = { ),@,*,^,(,%, !,$,&,#}\nbolts = { !, (, #, %, ), ^, &, *, $, @ }\nOutput:\nAfter matching nuts and bolts:\nNuts: ! # $ % & ( ) * @ ^\nBolts: ! # $ % & ( ) * @ ^" }, { "code": null, "e": 1858, "s": 1823, "text": "partition(array, low, high, pivot)" }, { "code": null, "e": 1919, "s": 1858, "text": "Input: One array, the low and high index, the pivot element." }, { "code": null, "e": 1960, "s": 1919, "text": "Output: Final location of pivot element." }, { "code": null, "e": 2264, "s": 1960, "text": "Begin\n i := low\n for j in range low to high, do\n if array[j] < pivot, then\n swap array[i] and array[j]\n increase i by 1\n else if array[j] = pivot, then\n swap array[j] and array[high]\n decrease j by 1\n done\n\n swap array[i] and array[high]\n return i\nEnd" }, { "code": null, "e": 2304, "s": 2264, "text": "nutAndBoltMatch(nuts, bolts, low, high)" }, { "code": null, "e": 2385, "s": 2304, "text": "Input: The list of nuts, the list of bolts, lower and higher index of the array." }, { "code": null, "e": 2430, "s": 2385, "text": "Output: Display which nut is for which bolt." }, { "code": null, "e": 2643, "s": 2430, "text": "Begin\n pivotLoc := partition(nuts, low, high, bolts[high])\n partition(bolts, low, high, nuts[pivotLoc])\n nutAndBoltMatch(nuts, bolts, low, pivotLoc-1)\n nutAndBoltMatch(nuts, bolts, pivotLoc + 1, high)\nEnd" }, { "code": null, "e": 4085, "s": 2643, "text": "#include<iostream>\nusing namespace std;\n\nvoid show(char array[], int n) {\n for(int i = 0; i<n; i++)\n cout << array[i] << \" \";\n}\n\nint partition(char array[], int low, int high, char pivot) { //find location of pivot for quick sort\n int i = low;\n for(int j = low; j<high; j++) {\n if(array[j] <pivot) { //when jth element less than pivot, swap ith and jth element\n swap(array[i], array[j]);\n i++;\n }else if(array[j] == pivot) { //when jth element is same as pivot, swap jth and last element\n swap(array[j], array[high]);\n j--;\n }\n }\n swap(array[i], array[high]);\n return i; //the location of pivot element\n}\n\nvoid nutAndBoltMatch(char nuts[], char bolts[], int low, int high) {\n if(low < high) {\n int pivotLoc = partition(nuts, low, high, bolts[high]); //choose item from bolt to nut partitioning\n partition(bolts, low, high, nuts[pivotLoc]); //place previous pivot location in bolt also\n nutAndBoltMatch(nuts, bolts, low, pivotLoc - 1);\n nutAndBoltMatch(nuts, bolts, pivotLoc+1, high);\n }\n}\n\nint main() {\n char nuts[] = {')','@','*','^','(','%','!','$','&','#'};\n char bolts[] = {'!','(','#','%',')','^','&','*','$','@'};\n int n = 10;\n nutAndBoltMatch(nuts, bolts, 0, n-1);\n cout << \"After matching nuts and bolts:\"<< endl;\n cout << \"Nuts: \"; show(nuts, n); cout << endl;\n cout << \"Bolts: \"; show(bolts, n); cout << endl;\n}" }, { "code": null, "e": 4170, "s": 4085, "text": "After matching nuts and bolts:\nNuts: ! # $ % & ( ) * @ ^\nBolts: ! # $ % & ( ) * @ ^" } ]
Write a program for Linear Search in Python
Linear Search is a searching technique to search some particular value from an array. This is the simplest searching technique. In this searching technique, the value to be searched is compared with all the elements in the array. the value to be searched is compared with all the elements in the array. If the value is found, the index of the element is returned. If the value is found, the index of the element is returned. If the particular element is not present throughout the array, then return -1 or some relevant string message. If the particular element is not present throughout the array, then return -1 or some relevant string message. linearSearch(int array[], int value): for i=0 to len(array): if(array[i]==value): Element is Present //outside for loop Element Not Present // element not found in the whole array Live Demo def linearSearch(arr,value): for i in range(len(arr)): if(arr[i]==value): return i return -1 array=[1,2,3,4,5,6,7,8,9,10] value=5 a=linearSearch(array,value) if(a==-1): print("Element not present") else: print("Element present at index",a) Element present at index 4 The worst case time complexity of linear search is O(n). The worst case occurs when the element is present at the last index of the array or not present at all. The best case time complexity of linear search is O(1). The best case occurs when element is present at the first index of the array. The worst case complexity of linear search can be improved to O(n/2). This can be done using two pointers, left and right and carrying on two comparisons at a time, hence reducing the worst case time complexity of linear search to O(n/2). Live Demo def linearSearch(arr,value): left=0 right=len(arr)-1 while(left<=right): if(arr[left]==value): return left elif(arr[right]==value): return right left+=1 right-=1 return -1 array=[1,2,3,4,5,6,7,8,9,10] value=10 a=linearSearch(array,value) if(a==-1): print("Element not present") else: print("Element present at index",a) Element present at index 9 In the above example, the element present at the last index, is found in the first iteration itself. Using the first method, it would have taken 10 iterations to find this element. If the element is not found, the worst case complexity is O(n/2), since the total number of iterations are n/2 in the second method. Linear search is rarely used since there are better searching algorithms such as binary search which provide better time complexities. Linear search is not efficient for large input array.
[ { "code": null, "e": 1315, "s": 1187, "text": "Linear Search is a searching technique to search some particular value from an array. This is the simplest searching technique." }, { "code": null, "e": 1344, "s": 1315, "text": "In this searching technique," }, { "code": null, "e": 1417, "s": 1344, "text": "the value to be searched is compared with all the elements in the array." }, { "code": null, "e": 1490, "s": 1417, "text": "the value to be searched is compared with all the elements in the array." }, { "code": null, "e": 1551, "s": 1490, "text": "If the value is found, the index of the element is returned." }, { "code": null, "e": 1612, "s": 1551, "text": "If the value is found, the index of the element is returned." }, { "code": null, "e": 1723, "s": 1612, "text": "If the particular element is not present throughout the array, then return -1 or some relevant string message." }, { "code": null, "e": 1834, "s": 1723, "text": "If the particular element is not present throughout the array, then return -1 or some relevant string message." }, { "code": null, "e": 2038, "s": 1834, "text": "linearSearch(int array[], int value):\n for i=0 to len(array):\n if(array[i]==value):\n Element is Present\n //outside for loop\n Element Not Present // element not found in the whole array" }, { "code": null, "e": 2049, "s": 2038, "text": " Live Demo" }, { "code": null, "e": 2316, "s": 2049, "text": "def linearSearch(arr,value):\n for i in range(len(arr)):\n if(arr[i]==value):\n return i\n return -1\narray=[1,2,3,4,5,6,7,8,9,10]\nvalue=5\na=linearSearch(array,value)\nif(a==-1):\n print(\"Element not present\")\nelse:\n print(\"Element present at index\",a)" }, { "code": null, "e": 2343, "s": 2316, "text": "Element present at index 4" }, { "code": null, "e": 2504, "s": 2343, "text": "The worst case time complexity of linear search is O(n). The worst case occurs when the element is present at the last index of the array or not present at all." }, { "code": null, "e": 2638, "s": 2504, "text": "The best case time complexity of linear search is O(1). The best case occurs when element is present at the first index of the array." }, { "code": null, "e": 2877, "s": 2638, "text": "The worst case complexity of linear search can be improved to O(n/2). This can be done using two pointers, left and right and carrying on two comparisons at a time, hence reducing the worst case time complexity of linear search to O(n/2)." }, { "code": null, "e": 2888, "s": 2877, "text": " Live Demo" }, { "code": null, "e": 3268, "s": 2888, "text": "def linearSearch(arr,value):\n left=0\n right=len(arr)-1\n while(left<=right):\n if(arr[left]==value):\n return left\n elif(arr[right]==value):\n return right\n left+=1\n right-=1\n return -1\narray=[1,2,3,4,5,6,7,8,9,10]\nvalue=10\na=linearSearch(array,value)\nif(a==-1):\n print(\"Element not present\")\nelse:\n print(\"Element present at index\",a)" }, { "code": null, "e": 3295, "s": 3268, "text": "Element present at index 9" }, { "code": null, "e": 3476, "s": 3295, "text": "In the above example, the element present at the last index, is found in the first iteration itself. Using the first method, it would have taken 10 iterations to find this element." }, { "code": null, "e": 3609, "s": 3476, "text": "If the element is not found, the worst case complexity is O(n/2), since the total number of iterations are n/2 in the second method." }, { "code": null, "e": 3798, "s": 3609, "text": "Linear search is rarely used since there are better searching algorithms such as binary search which provide better time complexities. Linear search is not efficient for large input array." } ]
DNA Cryptography
18 Oct, 2021 Cryptography is the branch of science which deals with the encoding of information for the purpose of hiding messages. It plays a vital role in the infrastructure of communication security. The Pioneering work had been done by Ashish Gehani et al and Amin et al after Leonard Max Adleman had shown the capability of molecular computation in 1994. This paved the way for DNA Computing. DNA Cryptology combines cryptology and modern biotechnology. Why DNA Cryptography? DNA Cryptography is one of the rapidly evolving technologies in the world. Adelman showed the world how it can be used to solve complex problems like directed Hamilton path problem and NP-complete problem (for example Travelling Salesman problem). Hence users can design and implement more complex Crypto algorithms. It brings forward new hope to break unbreakable algorithms. This is because DNA computing offers more speed, minimal storage, and power requirements. DNA stores memory at a density of about 1 bit/nm3 where conventional storage media requires 1012 nm3/bit. No power is required for DNA computing while the computation is taking place. Surprisingly, one gram of DNA contains 1021 DNA bases which are equivalent to 108 TB of data. Hence can store all the data in the world in a few milligrams. DNA Cryptography can be defined as hiding data in terms of DNA Sequence. Just like the RSA and DES algorithms, in DNA Cryptology users have DNA algorithms like “Public-key system using DNA as a one-way function for key distribution,” “DNASC cryptography system”, DNA Steganography Systems, Triple stage DNA Cryptography, Encryption algorithm inspired by DNA and Chaotic computing. So, how do encode data in a DNA strand which is mainly made, up of 4 nitrogenous bases namely: Adenine (A) Thymine (T) Cytosine (C) Guanine (G) Adenine (A) Thymine (T) Cytosine (C) Guanine (G) The easiest way to encode is to represent these four units as four figures: A(0) –00 T(1) –01 C(2)–10 G(3)–11 By these encoding rules, there are 4!=24 possible encoding methods. Based on some principles as A and G make pairs while T and C make pairs. Of those 24 methods, only 8 matches the DNA pairing rule but the best encoding scheme is 0123/CTAG. So now converted our initial number into a sequence of A, T, G, and C theoretically. This is then physically implemented using various DNA synthesizing techniques like Chemical Oligonucleotide Synthesis and Oligo Synthesis Platforms (this includes column-based Oligo Synthesis, Array-based Oligo Synthesis, Complex Strand and Gene Synthesis and Error Correction). Let’s take an example of the classic XOR One Time Pad and see how its implemented using DNA Cryptography: Example – Let M be the message and K be the key. The Ciphertext is obtained by finding M xor K = C. User can again obtain the Encoded message by doing: C xor K = M xor K xor K= M. Hence, get our original message. The steps involved in implementing it is: The message and the OTP key are converted to ASCII bits Zero Padding is added to the message and the key in order to make the size of their binary codes even The message and the key are XORed together The XOR output is represented in DNA bases format. This is our enciphered text. The message and the OTP key are converted to ASCII bits Zero Padding is added to the message and the key in order to make the size of their binary codes even The message and the key are XORed together The XOR output is represented in DNA bases format. This is our enciphered text. The decryption process involves the following processes and hence it is also prone to eavesdropping: All the DNA bases are transformed into bits. These bits are then XORed with the OTP key bits to reproduce the original plain text. This text so obtained in binary format is then converted into a sequence of ASCII characters. All the DNA bases are transformed into bits. These bits are then XORed with the OTP key bits to reproduce the original plain text. This text so obtained in binary format is then converted into a sequence of ASCII characters. Similarly, users can implement other crypto algorithms like AES and even DES. Instead of storing data as a sequence of 0s and 1s, storing them as a sequence of nitrogenous bases. Storing information in the form of DNA enables us to store a lot of data in a small area. Pushpender007 cryptography Genetic Algorithms Computer Networks Technical Scripter cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) UDP Server-Client implementation in C Caesar Cipher in Cryptography Advanced Encryption Standard (AES) Intrusion Detection System (IDS)
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Oct, 2021" }, { "code": null, "e": 499, "s": 52, "text": "Cryptography is the branch of science which deals with the encoding of information for the purpose of hiding messages. It plays a vital role in the infrastructure of communication security. The Pioneering work had been done by Ashish Gehani et al and Amin et al after Leonard Max Adleman had shown the capability of molecular computation in 1994. This paved the way for DNA Computing. DNA Cryptology combines cryptology and modern biotechnology. " }, { "code": null, "e": 523, "s": 499, "text": "Why DNA Cryptography? " }, { "code": null, "e": 599, "s": 523, "text": "DNA Cryptography is one of the rapidly evolving technologies in the world. " }, { "code": null, "e": 842, "s": 599, "text": "Adelman showed the world how it can be used to solve complex problems like directed Hamilton path problem and NP-complete problem (for example Travelling Salesman problem). Hence users can design and implement more complex Crypto algorithms. " }, { "code": null, "e": 993, "s": 842, "text": "It brings forward new hope to break unbreakable algorithms. This is because DNA computing offers more speed, minimal storage, and power requirements. " }, { "code": null, "e": 1100, "s": 993, "text": "DNA stores memory at a density of about 1 bit/nm3 where conventional storage media requires 1012 nm3/bit. " }, { "code": null, "e": 1179, "s": 1100, "text": "No power is required for DNA computing while the computation is taking place. " }, { "code": null, "e": 1338, "s": 1179, "text": "Surprisingly, one gram of DNA contains 1021 DNA bases which are equivalent to 108 TB of data. Hence can store all the data in the world in a few milligrams. " }, { "code": null, "e": 1720, "s": 1338, "text": "DNA Cryptography can be defined as hiding data in terms of DNA Sequence. Just like the RSA and DES algorithms, in DNA Cryptology users have DNA algorithms like “Public-key system using DNA as a one-way function for key distribution,” “DNASC cryptography system”, DNA Steganography Systems, Triple stage DNA Cryptography, Encryption algorithm inspired by DNA and Chaotic computing. " }, { "code": null, "e": 1816, "s": 1720, "text": "So, how do encode data in a DNA strand which is mainly made, up of 4 nitrogenous bases namely: " }, { "code": null, "e": 1867, "s": 1816, "text": "Adenine (A) Thymine (T) Cytosine (C) Guanine (G) " }, { "code": null, "e": 1880, "s": 1867, "text": "Adenine (A) " }, { "code": null, "e": 1893, "s": 1880, "text": "Thymine (T) " }, { "code": null, "e": 1907, "s": 1893, "text": "Cytosine (C) " }, { "code": null, "e": 1921, "s": 1907, "text": "Guanine (G) " }, { "code": null, "e": 1998, "s": 1921, "text": "The easiest way to encode is to represent these four units as four figures: " }, { "code": null, "e": 2033, "s": 1998, "text": "A(0) –00\nT(1) –01\nC(2)–10\nG(3)–11 " }, { "code": null, "e": 2175, "s": 2033, "text": "By these encoding rules, there are 4!=24 possible encoding methods. Based on some principles as A and G make pairs while T and C make pairs. " }, { "code": null, "e": 2277, "s": 2175, "text": "Of those 24 methods, only 8 matches the DNA pairing rule but the best encoding scheme is 0123/CTAG. " }, { "code": null, "e": 2642, "s": 2277, "text": "So now converted our initial number into a sequence of A, T, G, and C theoretically. This is then physically implemented using various DNA synthesizing techniques like Chemical Oligonucleotide Synthesis and Oligo Synthesis Platforms (this includes column-based Oligo Synthesis, Array-based Oligo Synthesis, Complex Strand and Gene Synthesis and Error Correction). " }, { "code": null, "e": 2749, "s": 2642, "text": "Let’s take an example of the classic XOR One Time Pad and see how its implemented using DNA Cryptography: " }, { "code": null, "e": 3006, "s": 2749, "text": "Example – Let M be the message and K be the key. The Ciphertext is obtained by finding M xor K = C. User can again obtain the Encoded message by doing: C xor K = M xor K xor K= M. Hence, get our original message. The steps involved in implementing it is: " }, { "code": null, "e": 3289, "s": 3006, "text": "The message and the OTP key are converted to ASCII bits Zero Padding is added to the message and the key in order to make the size of their binary codes even The message and the key are XORed together The XOR output is represented in DNA bases format. This is our enciphered text. " }, { "code": null, "e": 3346, "s": 3289, "text": "The message and the OTP key are converted to ASCII bits " }, { "code": null, "e": 3449, "s": 3346, "text": "Zero Padding is added to the message and the key in order to make the size of their binary codes even " }, { "code": null, "e": 3493, "s": 3449, "text": "The message and the key are XORed together " }, { "code": null, "e": 3575, "s": 3493, "text": "The XOR output is represented in DNA bases format. This is our enciphered text. " }, { "code": null, "e": 3677, "s": 3575, "text": "The decryption process involves the following processes and hence it is also prone to eavesdropping: " }, { "code": null, "e": 3904, "s": 3677, "text": "All the DNA bases are transformed into bits. These bits are then XORed with the OTP key bits to reproduce the original plain text. This text so obtained in binary format is then converted into a sequence of ASCII characters. " }, { "code": null, "e": 3950, "s": 3904, "text": "All the DNA bases are transformed into bits. " }, { "code": null, "e": 4037, "s": 3950, "text": "These bits are then XORed with the OTP key bits to reproduce the original plain text. " }, { "code": null, "e": 4133, "s": 4037, "text": "This text so obtained in binary format is then converted into a sequence of ASCII characters. " }, { "code": null, "e": 4403, "s": 4133, "text": "Similarly, users can implement other crypto algorithms like AES and even DES. Instead of storing data as a sequence of 0s and 1s, storing them as a sequence of nitrogenous bases. Storing information in the form of DNA enables us to store a lot of data in a small area. " }, { "code": null, "e": 4417, "s": 4403, "text": "Pushpender007" }, { "code": null, "e": 4430, "s": 4417, "text": "cryptography" }, { "code": null, "e": 4449, "s": 4430, "text": "Genetic Algorithms" }, { "code": null, "e": 4467, "s": 4449, "text": "Computer Networks" }, { "code": null, "e": 4486, "s": 4467, "text": "Technical Scripter" }, { "code": null, "e": 4499, "s": 4486, "text": "cryptography" }, { "code": null, "e": 4517, "s": 4499, "text": "Computer Networks" }, { "code": null, "e": 4615, "s": 4517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4645, "s": 4615, "text": "GSM in Wireless Communication" }, { "code": null, "e": 4674, "s": 4645, "text": "Socket Programming in Python" }, { "code": null, "e": 4708, "s": 4674, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 4734, "s": 4708, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 4764, "s": 4734, "text": "Wireless Application Protocol" }, { "code": null, "e": 4804, "s": 4764, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 4842, "s": 4804, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 4872, "s": 4842, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 4907, "s": 4872, "text": "Advanced Encryption Standard (AES)" } ]
SciPy - Integrate
When a function cannot be integrated analytically, or is very difficult to integrate analytically, one generally turns to numerical integration methods. SciPy has a number of routines for performing numerical integration. Most of them are found in the same scipy.integrate library. The following table lists some commonly used functions. quad Single integration dblquad Double integration tplquad Triple integration nquad n-fold multiple integration fixed_quad Gaussian quadrature, order n quadrature Gaussian quadrature to tolerance romberg Romberg integration trapz Trapezoidal rule cumtrapz Trapezoidal rule to cumulatively compute integral simps Simpson’s rule romb Romberg integration polyint Analytical polynomial integration (NumPy) poly1d Helper function for polyint (NumPy) The Quad function is the workhorse of SciPy’s integration functions. Numerical integration is sometimes called quadrature, hence the name. It is normally the default choice for performing single integrals of a function f(x) over a given fixed range from a to b. $$\int_{a}^{b} f(x)dx$$ The general form of quad is scipy.integrate.quad(f, a, b), Where ‘f’ is the name of the function to be integrated. Whereas, ‘a’ and ‘b’ are the lower and upper limits, respectively. Let us see an example of the Gaussian function, integrated over a range of 0 and 1. We first need to define the function → $f(x) = e^{-x^2}$ , this can be done using a lambda expression and then call the quad method on that function. import scipy.integrate from numpy import exp f= lambda x:exp(-x**2) i = scipy.integrate.quad(f, 0, 1) print i The above program will generate the following output. (0.7468241328124271, 8.291413475940725e-15) The quad function returns the two values, in which the first number is the value of integral and the second value is the estimate of the absolute error in the value of integral. Note − Since quad requires the function as the first argument, we cannot directly pass exp as the argument. The Quad function accepts positive and negative infinity as limits. The Quad function can integrate standard predefined NumPy functions of a single variable, such as exp, sin and cos. The mechanics for double and triple integration have been wrapped up into the functions dblquad, tplquad and nquad. These functions integrate four or six arguments, respectively. The limits of all inner integrals need to be defined as functions. The general form of dblquad is scipy.integrate.dblquad(func, a, b, gfun, hfun). Where, func is the name of the function to be integrated, ‘a’ and ‘b’ are the lower and upper limits of the x variable, respectively, while gfun and hfun are the names of the functions that define the lower and upper limits of the y variable. As an example, let us perform the double integral method. $$\int_{0}^{1/2} dy \int_{0}^{\sqrt{1-4y^2}} 16xy \:dx$$ We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit. import scipy.integrate from numpy import exp from math import sqrt f = lambda x, y : 16*x*y g = lambda x : 0 h = lambda y : sqrt(1-4*y**2) i = scipy.integrate.dblquad(f, 0, 0.5, g, h) print i The above program will generate the following output. (0.5, 1.7092350012594845e-14) In addition to the routines described above, scipy.integrate has a number of other integration routines, including nquad, which performs n-fold multiple integration, as well as other routines that implement various integration algorithms. However, quad and dblquad will meet most of our needs for numerical integration.
[ { "code": null, "e": 2359, "s": 2021, "text": "When a function cannot be integrated analytically, or is very difficult to integrate analytically, one generally turns to numerical integration methods. SciPy has a number of routines for performing numerical integration. Most of them are found in the same scipy.integrate library. The following table lists some commonly used functions." }, { "code": null, "e": 2364, "s": 2359, "text": "quad" }, { "code": null, "e": 2383, "s": 2364, "text": "Single integration" }, { "code": null, "e": 2391, "s": 2383, "text": "dblquad" }, { "code": null, "e": 2410, "s": 2391, "text": "Double integration" }, { "code": null, "e": 2418, "s": 2410, "text": "tplquad" }, { "code": null, "e": 2437, "s": 2418, "text": "Triple integration" }, { "code": null, "e": 2443, "s": 2437, "text": "nquad" }, { "code": null, "e": 2471, "s": 2443, "text": "n-fold multiple integration" }, { "code": null, "e": 2482, "s": 2471, "text": "fixed_quad" }, { "code": null, "e": 2511, "s": 2482, "text": "Gaussian quadrature, order n" }, { "code": null, "e": 2522, "s": 2511, "text": "quadrature" }, { "code": null, "e": 2555, "s": 2522, "text": "Gaussian quadrature to tolerance" }, { "code": null, "e": 2563, "s": 2555, "text": "romberg" }, { "code": null, "e": 2583, "s": 2563, "text": "Romberg integration" }, { "code": null, "e": 2589, "s": 2583, "text": "trapz" }, { "code": null, "e": 2606, "s": 2589, "text": "Trapezoidal rule" }, { "code": null, "e": 2615, "s": 2606, "text": "cumtrapz" }, { "code": null, "e": 2665, "s": 2615, "text": "Trapezoidal rule to cumulatively compute integral" }, { "code": null, "e": 2671, "s": 2665, "text": "simps" }, { "code": null, "e": 2686, "s": 2671, "text": "Simpson’s rule" }, { "code": null, "e": 2691, "s": 2686, "text": "romb" }, { "code": null, "e": 2711, "s": 2691, "text": "Romberg integration" }, { "code": null, "e": 2719, "s": 2711, "text": "polyint" }, { "code": null, "e": 2761, "s": 2719, "text": "Analytical polynomial integration (NumPy)" }, { "code": null, "e": 2768, "s": 2761, "text": "poly1d" }, { "code": null, "e": 2804, "s": 2768, "text": "Helper function for polyint (NumPy)" }, { "code": null, "e": 3066, "s": 2804, "text": "The Quad function is the workhorse of SciPy’s integration functions. Numerical integration is sometimes called quadrature, hence the name. It is normally the default choice for performing single integrals of a function f(x) over a given fixed range from a to b." }, { "code": null, "e": 3090, "s": 3066, "text": "$$\\int_{a}^{b} f(x)dx$$" }, { "code": null, "e": 3356, "s": 3090, "text": "The general form of quad is scipy.integrate.quad(f, a, b), Where ‘f’ is the name of the function to be integrated. Whereas, ‘a’ and ‘b’ are the lower and upper limits, respectively. Let us see an example of the Gaussian function, integrated over a range of 0 and 1." }, { "code": null, "e": 3506, "s": 3356, "text": "We first need to define the function → $f(x) = e^{-x^2}$ , this can be done using a lambda expression and then call the quad method on that function." }, { "code": null, "e": 3616, "s": 3506, "text": "import scipy.integrate\nfrom numpy import exp\nf= lambda x:exp(-x**2)\ni = scipy.integrate.quad(f, 0, 1)\nprint i" }, { "code": null, "e": 3670, "s": 3616, "text": "The above program will generate the following output." }, { "code": null, "e": 3715, "s": 3670, "text": "(0.7468241328124271, 8.291413475940725e-15)\n" }, { "code": null, "e": 3893, "s": 3715, "text": "The quad function returns the two values, in which the first number is the value of integral and the second value is the estimate of the absolute error in the value of integral." }, { "code": null, "e": 4185, "s": 3893, "text": "Note − Since quad requires the function as the first argument, we cannot directly pass exp as the argument. The Quad function accepts positive and negative infinity as limits. The Quad function can integrate standard predefined NumPy functions of a single variable, such as exp, sin and cos." }, { "code": null, "e": 4431, "s": 4185, "text": "The mechanics for double and triple integration have been wrapped up into the functions dblquad, tplquad and nquad. These functions integrate four or six arguments, respectively. The limits of all inner integrals need to be defined as functions." }, { "code": null, "e": 4754, "s": 4431, "text": "The general form of dblquad is scipy.integrate.dblquad(func, a, b, gfun, hfun). Where, func is the name of the function to be integrated, ‘a’ and ‘b’ are the lower and upper limits of the x variable, respectively, while gfun and hfun are the names of the functions that define the lower and upper limits of the y variable." }, { "code": null, "e": 4812, "s": 4754, "text": "As an example, let us perform the double integral method." }, { "code": null, "e": 4869, "s": 4812, "text": "$$\\int_{0}^{1/2} dy \\int_{0}^{\\sqrt{1-4y^2}} 16xy \\:dx$$" }, { "code": null, "e": 5084, "s": 4869, "text": "We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit." }, { "code": null, "e": 5276, "s": 5084, "text": "import scipy.integrate\nfrom numpy import exp\nfrom math import sqrt\nf = lambda x, y : 16*x*y\ng = lambda x : 0\nh = lambda y : sqrt(1-4*y**2)\ni = scipy.integrate.dblquad(f, 0, 0.5, g, h)\nprint i" }, { "code": null, "e": 5330, "s": 5276, "text": "The above program will generate the following output." }, { "code": null, "e": 5361, "s": 5330, "text": "(0.5, 1.7092350012594845e-14)\n" } ]
How to reshape Pandas Series?
01 Oct, 2020 In this article, we will see how to reshaping Pandas Series. So, for reshaping the Pandas Series we are using reshape() method of Pandas Series object. Syntax: Pandas.Series.values.reshape((dimension)) Return: return an ndarray with the values shape if the specified shape matches exactly the current shape, then return self (for compat) Let’s see some of the examples: Example 1: Python3 # import pandas libraryimport pandas as pd # make an arrayarray = [2, 4, 6, 8, 10, 12] # create a seriesseries_obj = pd.Series(array) # convert series object into arrayarr = series_obj.values # reshaping series reshaped_arr = arr.reshape((3, 2)) # show reshaped_arr Output: Example 2: Python3 # import pandas libraryimport pandas as pd # make an arrayarray = ["ankit","shaurya", "shivangi", "priya", "jeet","ananya"] # create a seriesseries_obj = pd.Series(array) print("Given Series:\n", series_obj) # convert series object into arrayarr = series_obj.values # reshaping series reshaped_arr = arr.reshape((2, 3)) # show print("After Reshaping: \n", reshaped_arr) Output: Python pandas-series Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 180, "s": 28, "text": "In this article, we will see how to reshaping Pandas Series. So, for reshaping the Pandas Series we are using reshape() method of Pandas Series object." }, { "code": null, "e": 230, "s": 180, "text": "Syntax: Pandas.Series.values.reshape((dimension))" }, { "code": null, "e": 366, "s": 230, "text": "Return: return an ndarray with the values shape if the specified shape matches exactly the current shape, then return self (for compat)" }, { "code": null, "e": 398, "s": 366, "text": "Let’s see some of the examples:" }, { "code": null, "e": 409, "s": 398, "text": "Example 1:" }, { "code": null, "e": 417, "s": 409, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # make an arrayarray = [2, 4, 6, 8, 10, 12] # create a seriesseries_obj = pd.Series(array) # convert series object into arrayarr = series_obj.values # reshaping series reshaped_arr = arr.reshape((3, 2)) # show reshaped_arr", "e": 688, "s": 417, "text": null }, { "code": null, "e": 696, "s": 688, "text": "Output:" }, { "code": null, "e": 707, "s": 696, "text": "Example 2:" }, { "code": null, "e": 715, "s": 707, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # make an arrayarray = [\"ankit\",\"shaurya\", \"shivangi\", \"priya\", \"jeet\",\"ananya\"] # create a seriesseries_obj = pd.Series(array) print(\"Given Series:\\n\", series_obj) # convert series object into arrayarr = series_obj.values # reshaping series reshaped_arr = arr.reshape((2, 3)) # show print(\"After Reshaping: \\n\", reshaped_arr)", "e": 1107, "s": 715, "text": null }, { "code": null, "e": 1115, "s": 1107, "text": "Output:" }, { "code": null, "e": 1136, "s": 1115, "text": "Python pandas-series" }, { "code": null, "e": 1150, "s": 1136, "text": "Python-pandas" }, { "code": null, "e": 1157, "s": 1150, "text": "Python" }, { "code": null, "e": 1255, "s": 1157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1273, "s": 1255, "text": "Python Dictionary" }, { "code": null, "e": 1295, "s": 1273, "text": "Enumerate() in Python" }, { "code": null, "e": 1327, "s": 1295, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1356, "s": 1327, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1383, "s": 1356, "text": "Python Classes and Objects" }, { "code": null, "e": 1404, "s": 1383, "text": "Python OOPs Concepts" }, { "code": null, "e": 1434, "s": 1404, "text": "Iterate over a list in Python" }, { "code": null, "e": 1457, "s": 1434, "text": "Introduction To PYTHON" }, { "code": null, "e": 1493, "s": 1457, "text": "Convert integer to string in Python" } ]
Semantic Web and RDF
12 Sep, 2019 Semantic Web is an extension to the World Wide Web. The purpose of the semantic web is to provide structure to the web and data in general. It emphasizes on representing a web of data instead of web of documents. It allows computers to intelligently search, combine and process the web content based on the meaning that the content has. Three main models of the semantic web are: Building modelsComputing with KnowledgeExchanging Information Building models Computing with Knowledge Exchanging Information Building Models:Model is a simplified version or description of certain aspects of the real-time entities. Model gathers information which is useful for the understanding of the particular domain. Computing Knowledge:Conclusions can be obtained from the knowledge present.Example: If two sentences are given as ‘John is the son of Harry’ and another sentence given is- ‘Hary’s father is Joey’, then the knowledge that can be computed from it is – ‘John is the grandson of Joey’Similarly, another example useful in the understanding of computing knowledge is-‘All A is B’ and ‘All B is C’, then the conclusion that can be drawn from it is – ‘All A are C’ respectively. Exchanging Information:It is an important aspect. Various communication protocols have been implemented for the exchange of information like the TCP/IP, HTML, WWW. Web Services have also been used for the exchange of the data. The technologies associated with the semantic web are: RDF (Resource Description Framework) OWL (Web Ontology Language) DL (Description Language) The query language used is: SPARQL ( SPARQL Protocol and RDF query language). SHACL (Shape Constraint Language). SHACL is used for validating the RDF graphs against a set of conditions. RDF:It is the formal language for describing structured information. The primary goal of RDF is to exchange data on the web while preserving the original meaning of the data. It is a data model that is used to describe resources.For Example Physical Things, Abstract Concepts, Numbers and Strings.RDF allows the processing of information. RDF representation can be in the form of triples and graphs. RDF graph is a directed graph which is used to serve as a description language for data on the world wide web and other electronic networks.Resources are described using triples.Triples capture the relationship between the subject and the object. Triples have a subject, predicate and an object. Triples are enclosed within angular brackets. Example: Delhi is capital of IndiaThe triple generated from this sentence is: <Delhi> <capital of> <India>. , where Delhi is the subject, capital of is the predicate and India is the object.The triples can also be represented in the form of URIs (Uniform Resource Identifier).Example of URI triple: <http://www.abc.org/subject/Delhi> <http://www.abc.org/predicate/capitalOf> <http://www.abc.org/object/India>. Every statement is terminated by a full-stop in RDF triple. Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Sep, 2019" }, { "code": null, "e": 433, "s": 53, "text": "Semantic Web is an extension to the World Wide Web. The purpose of the semantic web is to provide structure to the web and data in general. It emphasizes on representing a web of data instead of web of documents. It allows computers to intelligently search, combine and process the web content based on the meaning that the content has. Three main models of the semantic web are:" }, { "code": null, "e": 495, "s": 433, "text": "Building modelsComputing with KnowledgeExchanging Information" }, { "code": null, "e": 511, "s": 495, "text": "Building models" }, { "code": null, "e": 536, "s": 511, "text": "Computing with Knowledge" }, { "code": null, "e": 559, "s": 536, "text": "Exchanging Information" }, { "code": null, "e": 756, "s": 559, "text": "Building Models:Model is a simplified version or description of certain aspects of the real-time entities. Model gathers information which is useful for the understanding of the particular domain." }, { "code": null, "e": 1227, "s": 756, "text": "Computing Knowledge:Conclusions can be obtained from the knowledge present.Example: If two sentences are given as ‘John is the son of Harry’ and another sentence given is- ‘Hary’s father is Joey’, then the knowledge that can be computed from it is – ‘John is the grandson of Joey’Similarly, another example useful in the understanding of computing knowledge is-‘All A is B’ and ‘All B is C’, then the conclusion that can be drawn from it is – ‘All A are C’ respectively." }, { "code": null, "e": 1454, "s": 1227, "text": "Exchanging Information:It is an important aspect. Various communication protocols have been implemented for the exchange of information like the TCP/IP, HTML, WWW. Web Services have also been used for the exchange of the data." }, { "code": null, "e": 1509, "s": 1454, "text": "The technologies associated with the semantic web are:" }, { "code": null, "e": 1546, "s": 1509, "text": "RDF (Resource Description Framework)" }, { "code": null, "e": 1574, "s": 1546, "text": "OWL (Web Ontology Language)" }, { "code": null, "e": 1600, "s": 1574, "text": "DL (Description Language)" }, { "code": null, "e": 1628, "s": 1600, "text": "The query language used is:" }, { "code": null, "e": 1678, "s": 1628, "text": "SPARQL ( SPARQL Protocol and RDF query language)." }, { "code": null, "e": 1786, "s": 1678, "text": "SHACL (Shape Constraint Language). SHACL is used for validating the RDF graphs against a set of conditions." }, { "code": null, "e": 2528, "s": 1786, "text": "RDF:It is the formal language for describing structured information. The primary goal of RDF is to exchange data on the web while preserving the original meaning of the data. It is a data model that is used to describe resources.For Example Physical Things, Abstract Concepts, Numbers and Strings.RDF allows the processing of information. RDF representation can be in the form of triples and graphs. RDF graph is a directed graph which is used to serve as a description language for data on the world wide web and other electronic networks.Resources are described using triples.Triples capture the relationship between the subject and the object. Triples have a subject, predicate and an object. Triples are enclosed within angular brackets." }, { "code": null, "e": 2606, "s": 2528, "text": "Example: Delhi is capital of IndiaThe triple generated from this sentence is:" }, { "code": "<Delhi> <capital of> <India>.", "e": 2636, "s": 2606, "text": null }, { "code": null, "e": 2827, "s": 2636, "text": ", where Delhi is the subject, capital of is the predicate and India is the object.The triples can also be represented in the form of URIs (Uniform Resource Identifier).Example of URI triple:" }, { "code": "<http://www.abc.org/subject/Delhi> <http://www.abc.org/predicate/capitalOf> <http://www.abc.org/object/India>.", "e": 2938, "s": 2827, "text": null }, { "code": null, "e": 2998, "s": 2938, "text": "Every statement is terminated by a full-stop in RDF triple." }, { "code": null, "e": 3015, "s": 2998, "text": "Web Technologies" } ]
How to create multiple dropdown options as a tag in ReactJS?
24 Jan, 2021 Choosing multiple options and creating your own options from the dropdown means allowing the user to choose more than one option from the dropdown and add his own options. Material UI for React has this component available for us and it is very easy to integrate. We can choose multiple options and create multiple options using the following approach. Creating React Application and Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react'import TextField from '@material-ui/core/TextField';import Chip from '@material-ui/core/Chip';import Autocomplete from '@material-ui/lab/Autocomplete'; const App = () => { // Sample options for dropdown const myOptions = ['One', 'Two', 'Three', 'Four', 'Five']; return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete multiple freeSolo style={{width:500}} options={myOptions} defaultValue={[myOptions[2]]} renderTags={(value: string[], getTagProps) => value.map((option: string, index: number) => ( <Chip variant="outlined" label={option} {...getTagProps({ index })} /> )) } renderInput={(params) => ( <TextField {...params} variant="outlined" label="freeSolo" placeholder="Enter fields" /> )} /> </div> );} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: In the above example, we have selected One and Two from the options available but also added our own options i.e. Random Number. This is how we can choose and create multiple options using Chip in ReactJS. JavaScript ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 381, "s": 28, "text": "Choosing multiple options and creating your own options from the dropdown means allowing the user to choose more than one option from the dropdown and add his own options. Material UI for React has this component available for us and it is very easy to integrate. We can choose multiple options and create multiple options using the following approach." }, { "code": null, "e": 431, "s": 381, "text": "Creating React Application and Installing Module:" }, { "code": null, "e": 495, "s": 431, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 527, "s": 495, "text": "npx create-react-app foldername" }, { "code": null, "e": 627, "s": 527, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 641, "s": 627, "text": "cd foldername" }, { "code": null, "e": 750, "s": 641, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 780, "s": 750, "text": "npm install @material-ui/core" }, { "code": null, "e": 832, "s": 780, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 850, "s": 832, "text": "Project Structure" }, { "code": null, "e": 979, "s": 850, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 990, "s": 979, "text": "Javascript" }, { "code": "import React from 'react'import TextField from '@material-ui/core/TextField';import Chip from '@material-ui/core/Chip';import Autocomplete from '@material-ui/lab/Autocomplete'; const App = () => { // Sample options for dropdown const myOptions = ['One', 'Two', 'Three', 'Four', 'Five']; return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete multiple freeSolo style={{width:500}} options={myOptions} defaultValue={[myOptions[2]]} renderTags={(value: string[], getTagProps) => value.map((option: string, index: number) => ( <Chip variant=\"outlined\" label={option} {...getTagProps({ index })} /> )) } renderInput={(params) => ( <TextField {...params} variant=\"outlined\" label=\"freeSolo\" placeholder=\"Enter fields\" /> )} /> </div> );} export default App", "e": 1994, "s": 990, "text": null }, { "code": null, "e": 2107, "s": 1994, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2117, "s": 2107, "text": "npm start" }, { "code": null, "e": 2216, "s": 2117, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2422, "s": 2216, "text": "In the above example, we have selected One and Two from the options available but also added our own options i.e. Random Number. This is how we can choose and create multiple options using Chip in ReactJS." }, { "code": null, "e": 2433, "s": 2422, "text": "JavaScript" }, { "code": null, "e": 2441, "s": 2433, "text": "ReactJS" }, { "code": null, "e": 2460, "s": 2441, "text": "Technical Scripter" }, { "code": null, "e": 2477, "s": 2460, "text": "Web Technologies" } ]
How to convert pandas DataFrame into JSON in Python?
21 Apr, 2020 Data Analysis is an extremely important tool in today’s world. A key aspect of Data Analytics is an organized representation of data. There are numerous data structures in computer science to achieve this task. In this article, we talk about two such data structures viz. pandas DataFrames and JSON . Further, we see how to convert DataFrames to JSON format. Pandas DataFrames are tabular representations of data where columns represent the various data points in single data entry and each row is unique data entry. Whereas JSON is a text written in JavaScript Object notations. Note: For more information, refer to Python | Pandas DataFrame To convert pandas DataFrames to JSON format we use the function DataFrame.to_json() from the pandas library in Python. There are multiple customizations available in the to_json function to achieve the desired formats of JSON. Let’s look at the parameters accepted by the functions and then explore the customization Parameters: We now look at a few examples to understand the usage of the function DataFrame.to_json. Example 1: Basic usage import numpy as npimport pandas as pd data = np.array([['1', '2'], ['3', '4']]) dataFrame = pd.DataFrame(data, columns = ['col1', 'col2'])json = dataFrame.to_json()print(json) Output : {"col1":{"0":"1", "1":"3"}, "col2":{"0":"2", "1":"4"}} Example 2: Exploring the ‘orient’ attribute of DataFrame.to_json function import numpy as npimport pandas as pd data = np.array([['1', '2'], ['3', '4']]) dataFrame = pd.DataFrame(data, columns = ['col1', 'col2'])json = dataFrame.to_json()print(json) json_split = dataFrame.to_json(orient ='split')print("json_split = ", json_split, "\n") json_records = dataFrame.to_json(orient ='records')print("json_records = ", json_records, "\n") json_index = dataFrame.to_json(orient ='index')print("json_index = ", json_index, "\n") json_columns = dataFrame.to_json(orient ='columns')print("json_columns = ", json_columns, "\n") json_values = dataFrame.to_json(orient ='values')print("json_values = ", json_values, "\n") json_table = dataFrame.to_json(orient ='table')print("json_table = ", json_table, "\n") Output : json_split = {“columns”:[“col1”, “col2”], “index”:[0, 1], “data”:[[“1”, “2”], [“3”, “4”]]} json_records = [{“col1′′:”1”, “col2′′:”2”}, {“col1′′:”3”, “col2′′:”4”}] json_index = {“0”:{“col1′′:”1”, “col2′′:”2”}, “1”:{“col1′′:”3”, “col2′′:”4”}} json_columns = {“col1”:{“0′′:”1”, “1”:”3′′}, “col2”:{“0′′:”2”, “1”:”4′′}} json_values = [[“1”, “2”], [“3”, “4”]] json_table = {“schema”:{“fields”:[{“name”:”index”, “type”:”integer”}, {“name”:”col1′′, “type”:”string”}, {“name”:”col2′′, “type”:”string”}], “primaryKey”:[“index”], “pandas_version”:”0.20.0′′}, “data”:[{“index”:0, “col1′′:”1”, “col2′′:”2”}, {“index”:1, “col1′′:”3”, “col2′′:”4”}]} Python pandas-dataFrame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 387, "s": 28, "text": "Data Analysis is an extremely important tool in today’s world. A key aspect of Data Analytics is an organized representation of data. There are numerous data structures in computer science to achieve this task. In this article, we talk about two such data structures viz. pandas DataFrames and JSON . Further, we see how to convert DataFrames to JSON format." }, { "code": null, "e": 608, "s": 387, "text": "Pandas DataFrames are tabular representations of data where columns represent the various data points in single data entry and each row is unique data entry. Whereas JSON is a text written in JavaScript Object notations." }, { "code": null, "e": 671, "s": 608, "text": "Note: For more information, refer to Python | Pandas DataFrame" }, { "code": null, "e": 988, "s": 671, "text": "To convert pandas DataFrames to JSON format we use the function DataFrame.to_json() from the pandas library in Python. There are multiple customizations available in the to_json function to achieve the desired formats of JSON. Let’s look at the parameters accepted by the functions and then explore the customization" }, { "code": null, "e": 1000, "s": 988, "text": "Parameters:" }, { "code": null, "e": 1089, "s": 1000, "text": "We now look at a few examples to understand the usage of the function DataFrame.to_json." }, { "code": null, "e": 1112, "s": 1089, "text": "Example 1: Basic usage" }, { "code": "import numpy as npimport pandas as pd data = np.array([['1', '2'], ['3', '4']]) dataFrame = pd.DataFrame(data, columns = ['col1', 'col2'])json = dataFrame.to_json()print(json)", "e": 1292, "s": 1112, "text": null }, { "code": null, "e": 1301, "s": 1292, "text": "Output :" }, { "code": null, "e": 1357, "s": 1301, "text": "{\"col1\":{\"0\":\"1\", \"1\":\"3\"}, \"col2\":{\"0\":\"2\", \"1\":\"4\"}}\n" }, { "code": null, "e": 1431, "s": 1357, "text": "Example 2: Exploring the ‘orient’ attribute of DataFrame.to_json function" }, { "code": "import numpy as npimport pandas as pd data = np.array([['1', '2'], ['3', '4']]) dataFrame = pd.DataFrame(data, columns = ['col1', 'col2'])json = dataFrame.to_json()print(json) json_split = dataFrame.to_json(orient ='split')print(\"json_split = \", json_split, \"\\n\") json_records = dataFrame.to_json(orient ='records')print(\"json_records = \", json_records, \"\\n\") json_index = dataFrame.to_json(orient ='index')print(\"json_index = \", json_index, \"\\n\") json_columns = dataFrame.to_json(orient ='columns')print(\"json_columns = \", json_columns, \"\\n\") json_values = dataFrame.to_json(orient ='values')print(\"json_values = \", json_values, \"\\n\") json_table = dataFrame.to_json(orient ='table')print(\"json_table = \", json_table, \"\\n\")", "e": 2171, "s": 1431, "text": null }, { "code": null, "e": 2180, "s": 2171, "text": "Output :" }, { "code": null, "e": 2271, "s": 2180, "text": "json_split = {“columns”:[“col1”, “col2”], “index”:[0, 1], “data”:[[“1”, “2”], [“3”, “4”]]}" }, { "code": null, "e": 2343, "s": 2271, "text": "json_records = [{“col1′′:”1”, “col2′′:”2”}, {“col1′′:”3”, “col2′′:”4”}]" }, { "code": null, "e": 2421, "s": 2343, "text": "json_index = {“0”:{“col1′′:”1”, “col2′′:”2”}, “1”:{“col1′′:”3”, “col2′′:”4”}}" }, { "code": null, "e": 2495, "s": 2421, "text": "json_columns = {“col1”:{“0′′:”1”, “1”:”3′′}, “col2”:{“0′′:”2”, “1”:”4′′}}" }, { "code": null, "e": 2534, "s": 2495, "text": "json_values = [[“1”, “2”], [“3”, “4”]]" }, { "code": null, "e": 2815, "s": 2534, "text": "json_table = {“schema”:{“fields”:[{“name”:”index”, “type”:”integer”}, {“name”:”col1′′, “type”:”string”}, {“name”:”col2′′, “type”:”string”}], “primaryKey”:[“index”], “pandas_version”:”0.20.0′′}, “data”:[{“index”:0, “col1′′:”1”, “col2′′:”2”}, {“index”:1, “col1′′:”3”, “col2′′:”4”}]}" }, { "code": null, "e": 2839, "s": 2815, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2846, "s": 2839, "text": "Python" }, { "code": null, "e": 2944, "s": 2846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2962, "s": 2944, "text": "Python Dictionary" }, { "code": null, "e": 3004, "s": 2962, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3026, "s": 3004, "text": "Enumerate() in Python" }, { "code": null, "e": 3061, "s": 3026, "text": "Read a file line by line in Python" }, { "code": null, "e": 3087, "s": 3061, "text": "Python String | replace()" }, { "code": null, "e": 3119, "s": 3087, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3148, "s": 3119, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3178, "s": 3148, "text": "Iterate over a list in Python" }, { "code": null, "e": 3205, "s": 3178, "text": "Python Classes and Objects" } ]
Python | Pandas Series.keys()
12 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.keys() function is an alias for index. It returns the index labels of the given series object. Syntax: Series.keys() Parameter : None Returns : index Example #1: Use Series.keys() function to return the index labels of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.keys() function to return the index labels of the given series object. # return the keysresult = sr.keys() # Print the resultprint(result) Output : As we can see in the output, the Series.keys() function has returned all the index labels of the given series object. Example #2 : Use Series.keys() function to return the index labels of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.keys() function to return the index labels of the given series object. # return the keysresult = sr.keys() # Print the resultprint(result) Output :As we can see in the output, the Series.keys() function has returned all the index labels of the given series object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 394, "s": 285, "text": "Pandas Series.keys() function is an alias for index. It returns the index labels of the given series object." }, { "code": null, "e": 416, "s": 394, "text": "Syntax: Series.keys()" }, { "code": null, "e": 433, "s": 416, "text": "Parameter : None" }, { "code": null, "e": 449, "s": 433, "text": "Returns : index" }, { "code": null, "e": 543, "s": 449, "text": "Example #1: Use Series.keys() function to return the index labels of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 799, "s": 543, "text": null }, { "code": null, "e": 808, "s": 799, "text": "Output :" }, { "code": null, "e": 902, "s": 808, "text": "Now we will use Series.keys() function to return the index labels of the given series object." }, { "code": "# return the keysresult = sr.keys() # Print the resultprint(result)", "e": 971, "s": 902, "text": null }, { "code": null, "e": 980, "s": 971, "text": "Output :" }, { "code": null, "e": 1193, "s": 980, "text": "As we can see in the output, the Series.keys() function has returned all the index labels of the given series object. Example #2 : Use Series.keys() function to return the index labels of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1462, "s": 1193, "text": null }, { "code": null, "e": 1471, "s": 1462, "text": "Output :" }, { "code": null, "e": 1565, "s": 1471, "text": "Now we will use Series.keys() function to return the index labels of the given series object." }, { "code": "# return the keysresult = sr.keys() # Print the resultprint(result)", "e": 1634, "s": 1565, "text": null }, { "code": null, "e": 1760, "s": 1634, "text": "Output :As we can see in the output, the Series.keys() function has returned all the index labels of the given series object." }, { "code": null, "e": 1781, "s": 1760, "text": "Python pandas-series" }, { "code": null, "e": 1810, "s": 1781, "text": "Python pandas-series-methods" }, { "code": null, "e": 1824, "s": 1810, "text": "Python-pandas" }, { "code": null, "e": 1831, "s": 1824, "text": "Python" } ]
Genetic Algorithm Based Approach for Robotic Controllers | by Anh T. Dang | Towards Data Science
Today, we will solve a real-world problem is to design a robotic controller. There are many techniques that can be used to solve this problem. Some of them include genetic algorithm (GA), particle swarm optimization and neural network (NN). What we need to do is to apply an algorithm to the robotic as a method of designing robotic controllers that enable the robot to perform complex tasks and behaviors. Autonomous robot is a robot that can perform certain work independently without the human help. One of the capabilities of robots is to move from one point to another which called is autonomous navigation. Imagine that we have built a robot that can move goods around a warehouse. In this article, we will implement this capability using the Python language. How the robot can see its local environment? Yes, we would install sensors, which allow the robot can look around and we have given it wheels so it can navigate based on input from its sensors. The biggest problem is how we can link the sensor data to motor actions so that the robot can navigate the warehouse. In general, we frequently use neural networks to successfully map robotic sensors to outputs by using reinforcement learning algorithms to the learning process. But we will use another way today, it is to use genetic algorithms. Typically, a genetic algorithm will evaluate a large population of individuals to find the best individuals for the next generation by using a fitness function that compute the performance of and individual based on certain predefined rules. However, we will be facing a new challenge, physically evaluating each robot controller is not feasible for a large population due to the difficulty in physically testing each robotic controller and the time it would take to do so. For this reason, we will use our knowledge of genetic algorithms to design and implement a robotic controller and apply it to a virtual robot in a virtual environment. Our robot can take four actions: move one step forward, turn left, turn righ and do nothing. The robot also has six sensors in the figure below. three on the front one on the left one on the right one on the back The maze is comprised of walls that the robot can’t cross and will have an outlined route. We are going to design a robotic controller that can use the robot sensors to navigate a robot successfully through a maze. The pseudo code for a basic genetic algorithm is as follows generation = 0;population[generation] = initializePopulation(populationSize); evaluatePopulation(population[generation]);While isTerminationConditionMet() == false do parents = selectParents(population[generation]); population[generation+1] = crossover(parents); population[generation+1] = mutate(population[generation+1]); evaluatePopulation(population[generation]); generation++;End loop; This pseudocode demonstrates the basic process of a genetic algorithm. Next steps, we will implement them in Python. As mentioned in the previous section, the robot will have four actions that can be represented in binary as follows: “00” — do nothing; “01” — move forward; “10” — turn left; and “11” — turn right. We also have six different sensors. To simplify the representation we limit the measurements to binary encoding, that is, values less than a threshold indicate obstacle detection and larger than threshold indicate a clear path. 6 sensors are giving us 26 = 64 possible combinations of sensor inputs. Since an action requires 2 bits, our controller requires 64*2 = 128 bits of storage to represent any possible input. Given that 128 bits are our requirement for representing instructions different combinations. But how should we organize the chromosome so we can encode and decode it? We have a human readable list of inputs and outputs as follows: Sensor #1 (front): on Sensor #2 (front-left): off Sensor #3 (front-right): on Sensor #4 (left): off Sensor #5 (right): off Sensor #6 (back): off We also have an instruction that is “turn left” with a value of 10 in binary. Our next is to take the six sensor values and encode those further. 000101 => 10 If we now convert the sensor values’ bit string to decimal, we get the following: 5 => 10 So, we can use the sensor’s decimal value as the position in the chromosome that represents a combination of sensor inputs as follows. xx xx xx xx xx 10 xx xx xx xx (... 54 more pairs...) As can be seen in the following figure, a combination of sensor values produces a binary output that describes how a typical chromosome can map the robot’s sensor values to actions. This encoding scheme may seem obtuse at first and the chromosome is not human-readable but it has a couple of helpful properties. First, the chromosome can be manipulated as an array of bits which makes crossover, mutation, and other manipulations much easier. Secondly, every 128-bit value is a valid solution. Firstly, we need to create and initialize a maze to run the robot in (world.py file). The maze object we’ve created uses integers to represent different terrain types: 1 defines a wall; 2 is the starting position; 3 traces the best route through the maze; 4 is the goal position; and 0 is an empty position that the robot can travel over but isn’t on the route to the goal. We write a constructor to create a new maze from a double int array and implement public methods to get the start position, score a route through the maze. An individual is represented by a single chromosome composed of multiple genes. Next, we need to create a Robot that can follow instructions and generate a route by executing those instructions. The population refers to a group of chromosomes. We implement methods to calculate fitness, select individuals, crossover and do mutation. Finally, we can write a class that actually executes the algorithm. Create another new file called main.py as follows. The output. Easy, right? [1] An Introduction to Genetic Algorithms
[ { "code": null, "e": 288, "s": 47, "text": "Today, we will solve a real-world problem is to design a robotic controller. There are many techniques that can be used to solve this problem. Some of them include genetic algorithm (GA), particle swarm optimization and neural network (NN)." }, { "code": null, "e": 454, "s": 288, "text": "What we need to do is to apply an algorithm to the robotic as a method of designing robotic controllers that enable the robot to perform complex tasks and behaviors." }, { "code": null, "e": 550, "s": 454, "text": "Autonomous robot is a robot that can perform certain work independently without the human help." }, { "code": null, "e": 1125, "s": 550, "text": "One of the capabilities of robots is to move from one point to another which called is autonomous navigation. Imagine that we have built a robot that can move goods around a warehouse. In this article, we will implement this capability using the Python language. How the robot can see its local environment? Yes, we would install sensors, which allow the robot can look around and we have given it wheels so it can navigate based on input from its sensors. The biggest problem is how we can link the sensor data to motor actions so that the robot can navigate the warehouse." }, { "code": null, "e": 1596, "s": 1125, "text": "In general, we frequently use neural networks to successfully map robotic sensors to outputs by using reinforcement learning algorithms to the learning process. But we will use another way today, it is to use genetic algorithms. Typically, a genetic algorithm will evaluate a large population of individuals to find the best individuals for the next generation by using a fitness function that compute the performance of and individual based on certain predefined rules." }, { "code": null, "e": 1996, "s": 1596, "text": "However, we will be facing a new challenge, physically evaluating each robot controller is not feasible for a large population due to the difficulty in physically testing each robotic controller and the time it would take to do so. For this reason, we will use our knowledge of genetic algorithms to design and implement a robotic controller and apply it to a virtual robot in a virtual environment." }, { "code": null, "e": 2089, "s": 1996, "text": "Our robot can take four actions: move one step forward, turn left, turn righ and do nothing." }, { "code": null, "e": 2141, "s": 2089, "text": "The robot also has six sensors in the figure below." }, { "code": null, "e": 2160, "s": 2141, "text": "three on the front" }, { "code": null, "e": 2176, "s": 2160, "text": "one on the left" }, { "code": null, "e": 2193, "s": 2176, "text": "one on the right" }, { "code": null, "e": 2209, "s": 2193, "text": "one on the back" }, { "code": null, "e": 2424, "s": 2209, "text": "The maze is comprised of walls that the robot can’t cross and will have an outlined route. We are going to design a robotic controller that can use the robot sensors to navigate a robot successfully through a maze." }, { "code": null, "e": 2484, "s": 2424, "text": "The pseudo code for a basic genetic algorithm is as follows" }, { "code": null, "e": 2893, "s": 2484, "text": "generation = 0;population[generation] = initializePopulation(populationSize); evaluatePopulation(population[generation]);While isTerminationConditionMet() == false do parents = selectParents(population[generation]); population[generation+1] = crossover(parents); population[generation+1] = mutate(population[generation+1]); evaluatePopulation(population[generation]); generation++;End loop;" }, { "code": null, "e": 3010, "s": 2893, "text": "This pseudocode demonstrates the basic process of a genetic algorithm. Next steps, we will implement them in Python." }, { "code": null, "e": 3127, "s": 3010, "text": "As mentioned in the previous section, the robot will have four actions that can be represented in binary as follows:" }, { "code": null, "e": 3146, "s": 3127, "text": "“00” — do nothing;" }, { "code": null, "e": 3167, "s": 3146, "text": "“01” — move forward;" }, { "code": null, "e": 3185, "s": 3167, "text": "“10” — turn left;" }, { "code": null, "e": 3208, "s": 3185, "text": "and “11” — turn right." }, { "code": null, "e": 3793, "s": 3208, "text": "We also have six different sensors. To simplify the representation we limit the measurements to binary encoding, that is, values less than a threshold indicate obstacle detection and larger than threshold indicate a clear path. 6 sensors are giving us 26 = 64 possible combinations of sensor inputs. Since an action requires 2 bits, our controller requires 64*2 = 128 bits of storage to represent any possible input. Given that 128 bits are our requirement for representing instructions different combinations. But how should we organize the chromosome so we can encode and decode it?" }, { "code": null, "e": 3857, "s": 3793, "text": "We have a human readable list of inputs and outputs as follows:" }, { "code": null, "e": 3879, "s": 3857, "text": "Sensor #1 (front): on" }, { "code": null, "e": 3907, "s": 3879, "text": "Sensor #2 (front-left): off" }, { "code": null, "e": 3935, "s": 3907, "text": "Sensor #3 (front-right): on" }, { "code": null, "e": 3957, "s": 3935, "text": "Sensor #4 (left): off" }, { "code": null, "e": 3980, "s": 3957, "text": "Sensor #5 (right): off" }, { "code": null, "e": 4002, "s": 3980, "text": "Sensor #6 (back): off" }, { "code": null, "e": 4148, "s": 4002, "text": "We also have an instruction that is “turn left” with a value of 10 in binary. Our next is to take the six sensor values and encode those further." }, { "code": null, "e": 4161, "s": 4148, "text": "000101 => 10" }, { "code": null, "e": 4243, "s": 4161, "text": "If we now convert the sensor values’ bit string to decimal, we get the following:" }, { "code": null, "e": 4251, "s": 4243, "text": "5 => 10" }, { "code": null, "e": 4386, "s": 4251, "text": "So, we can use the sensor’s decimal value as the position in the chromosome that represents a combination of sensor inputs as follows." }, { "code": null, "e": 4439, "s": 4386, "text": "xx xx xx xx xx 10 xx xx xx xx (... 54 more pairs...)" }, { "code": null, "e": 4621, "s": 4439, "text": "As can be seen in the following figure, a combination of sensor values produces a binary output that describes how a typical chromosome can map the robot’s sensor values to actions." }, { "code": null, "e": 4751, "s": 4621, "text": "This encoding scheme may seem obtuse at first and the chromosome is not human-readable but it has a couple of helpful properties." }, { "code": null, "e": 4882, "s": 4751, "text": "First, the chromosome can be manipulated as an array of bits which makes crossover, mutation, and other manipulations much easier." }, { "code": null, "e": 4933, "s": 4882, "text": "Secondly, every 128-bit value is a valid solution." }, { "code": null, "e": 5101, "s": 4933, "text": "Firstly, we need to create and initialize a maze to run the robot in (world.py file). The maze object we’ve created uses integers to represent different terrain types:" }, { "code": null, "e": 5119, "s": 5101, "text": "1 defines a wall;" }, { "code": null, "e": 5147, "s": 5119, "text": "2 is the starting position;" }, { "code": null, "e": 5189, "s": 5147, "text": "3 traces the best route through the maze;" }, { "code": null, "e": 5213, "s": 5189, "text": "4 is the goal position;" }, { "code": null, "e": 5307, "s": 5213, "text": "and 0 is an empty position that the robot can travel over but isn’t on the route to the goal." }, { "code": null, "e": 5463, "s": 5307, "text": "We write a constructor to create a new maze from a double int array and implement public methods to get the start position, score a route through the maze." }, { "code": null, "e": 5543, "s": 5463, "text": "An individual is represented by a single chromosome composed of multiple genes." }, { "code": null, "e": 5658, "s": 5543, "text": "Next, we need to create a Robot that can follow instructions and generate a route by executing those instructions." }, { "code": null, "e": 5707, "s": 5658, "text": "The population refers to a group of chromosomes." }, { "code": null, "e": 5797, "s": 5707, "text": "We implement methods to calculate fitness, select individuals, crossover and do mutation." }, { "code": null, "e": 5916, "s": 5797, "text": "Finally, we can write a class that actually executes the algorithm. Create another new file called main.py as follows." }, { "code": null, "e": 5928, "s": 5916, "text": "The output." }, { "code": null, "e": 5941, "s": 5928, "text": "Easy, right?" } ]
Find the parent node of maximum product Siblings in given Binary Tree - GeeksforGeeks
10 Dec, 2021 Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value. Examples: Input: Tree: 4 / \ 5 2 / \ 3 1 / \6 12Output: 3Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 12 which are the children of node 3. Input: Tree: 1 / \ 3 5 / \ / \ 6 9 4 8Output: 3Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 9 which are the children of node 5. Approach: To solve this problem, level order traversal of the Binary Tree can be used to find the maximum sum of siblings. Follow the following steps: Start level order traversal of the tree from root of the tree. For each node, check if it has both the child.If yes, then find the node with maximum product of children and store this node value in a reference variable.Update the node value in reference variable if any node is found with greater product of children. If yes, then find the node with maximum product of children and store this node value in a reference variable. Update the node value in reference variable if any node is found with greater product of children. If the current node don’t have both children, then skip that node Return the node value in reference variable, as it contains the node with maximum product of children, or the parent of maximum product siblings. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to find the Parent Node// of maximum product Siblings// in given Binary Tree #include <bits/stdc++.h>using namespace std; // Structure for Nodestruct Node { int data; Node *left, *right;}; // Function to get a new nodeNode* getNode(int data){ // Allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // Put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Function to get the parent// of siblings with maximum productint maxproduct(Node* root){ int mproduct = INT_MIN; int ans = 0; // Checking base case if (root == NULL || (root->left == NULL && root->right == NULL)) return 0; // Declaration of queue to run // level order traversal queue<Node*> q; q.push(root); // Loop to implement level order traversal while (!q.empty()) { Node* temp = q.front(); q.pop(); // If both the siblings are present // then take their product if (temp->right && temp->left) { int curr_max = temp->right->data * temp->left->data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp->data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = max(ans, temp->data); } } // pushing childs in the queue if (temp->right) { q.push(temp->right); } if (temp->left) { q.push(temp->left); } } return ans;} // Driver Codeint main(){ /* Binary tree creation 1 / \ 3 5 / \ / \ 6 9 4 8 */ Node* root = getNode(1); root->left = getNode(3); root->right = getNode(5); root->left->left = getNode(6); root->left->right = getNode(9); root->right->left = getNode(4); root->right->right = getNode(8); cout << maxproduct(root) << endl; return 0;} // Java code to find the Parent Node// of maximum product Siblings// in given Binary Treeimport java.util.LinkedList;import java.util.Queue; class GFG { // Structure for Node static class Node { int data; Node left; Node right; public Node(int data) { this.data = data; this.left = null; this.right = null; } }; // Function to get a new node public static Node getNode(int data) { // Allocate space Node newNode = new Node(data); // Put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function to get the parent // of siblings with maximum product public static int maxproduct(Node root) { int mproduct = Integer.MIN_VALUE; int ans = 0; // Checking base case if (root == null || (root.left == null && root.right == null)) return 0; // Declaration of queue to run // level order traversal Queue<Node> q = new LinkedList<Node>(); q.add(root); // Loop to implement level order traversal while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); // If both the siblings are present // then take their product if (temp.right != null && temp.left != null) { int curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp.data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = Math.max(ans, temp.data); } } // pushing childs in the queue if (temp.right != null) { q.add(temp.right); } if (temp.left != null) { q.add(temp.left); } } return ans; } // Driver Code public static void main(String args[]) { /* * Binary tree creation * 1 * / \ * 3 5 * / \ / \ * 6 9 4 8 */ Node root = getNode(1); root.left = getNode(3); root.right = getNode(5); root.left.left = getNode(6); root.left.right = getNode(9); root.right.left = getNode(4); root.right.right = getNode(8); System.out.println(maxproduct(root)); }} // This code is contributed by gfgking. # Python Program to implement# the above approach # Structure of a node of binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to get a new nodedef getNode(data): # Allocate space newNode = Node(data) return newNode # Function to get the parent# of siblings with maximum productdef maxproduct(root): mproduct = 10 ** -9 ans = 0; # Checking base case if (root == None or (root.left == None and root.right == None)): return 0; # Declaration of queue to run # level order traversal q = []; q.append(root); # Loop to implement level order traversal while (len(q)): temp = q[0]; q.pop(0); # If both the siblings are present # then take their product if (temp.right and temp.left): curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max): mproduct = curr_max ans = temp.data elif (mproduct == curr_max): # if max product is equal to # curr_max then consider node # which has maximum value ans = max(ans, temp.data) # pushing childs in the queue if (temp.right): q.append(temp.right) if (temp.left): q.append(temp.left) return ans # Driver Code """ Binary tree creation 1 / \ 3 5 / \ / \ 6 9 4 8"""root = getNode(1);root.left = getNode(3);root.right = getNode(5);root.left.left = getNode(6);root.left.right = getNode(9);root.right.left = getNode(4);root.right.right = getNode(8); print(maxproduct(root)); # This code is contributed by gfgking // C# code to find the Parent Node// of maximum product Siblings// in given Binary Treeusing System;using System.Collections.Generic; public class GFG { // Structure for Node class Node { public int data; public Node left; public Node right; public Node(int data) { this.data = data; this.left = null; this.right = null; } }; // Function to get a new node static Node getNode(int data) { // Allocate space Node newNode = new Node(data); // Put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function to get the parent // of siblings with maximum product static int maxproduct(Node root) { int mproduct = int.MinValue; int ans = 0; // Checking base case if (root == null || (root.left == null && root.right == null)) return 0; // Declaration of queue to run // level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // Loop to implement level order traversal while (q.Count!=0) { Node temp = q.Peek(); q.Dequeue(); // If both the siblings are present // then take their product if (temp.right != null && temp.left != null) { int curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp.data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = Math.Max(ans, temp.data); } } // pushing childs in the queue if (temp.right != null) { q.Enqueue(temp.right); } if (temp.left != null) { q.Enqueue(temp.left); } } return ans; } // Driver Code public static void Main(String []args) { /* * Binary tree creation * 1 * / \ * 3 5 * / \ / \ * 6 9 4 8 */ Node root = getNode(1); root.left = getNode(3); root.right = getNode(5); root.left.left = getNode(6); root.left.right = getNode(9); root.right.left = getNode(4); root.right.right = getNode(8); Console.WriteLine(maxproduct(root)); }} // This code is contributed by shikhasingrajput <script> // JavaScript Program to implement // the above approach // Structure of a node of binary tree class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } }; // Function to get a new node function getNode(data) { // Allocate space let newNode = new Node(data); return newNode; } // Function to get the parent // of siblings with maximum product function maxproduct(root) { let mproduct = Number.MIN_VALUE; let ans = 0; // Checking base case if (root == null || (root.left == null && root.right == null)) return 0; // Declaration of queue to run // level order traversal let q = []; q.push(root); // Loop to implement level order traversal while (!q.length == 0) { let temp = q[0]; q.shift(); // If both the siblings are present // then take their product if (temp.right && temp.left) { let curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp.data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = Math.max(ans, temp.data); } } // pushing childs in the queue if (temp.right) { q.push(temp.right); } if (temp.left) { q.push(temp.left); } } return ans; } // Driver Code /* Binary tree creation 1 / \ 3 5 / \ / \ 6 9 4 8 */ let root = getNode(1); root.left = getNode(3); root.right = getNode(5); root.left.left = getNode(6); root.left.right = getNode(9); root.right.left = getNode(4); root.right.right = getNode(8); document.write(maxproduct(root) + "<br>"); // This code is contributed by Potta Lokesh </script> 3 Time Complexity: O(V) where V is the number of nodes in the tree.Auxiliary Space: O(V). lokeshpotta20 gfgking shikhasingrajput tree-level-order tree-traversal Mathematical Tree Mathematical Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Program to multiply two matrices Fizz Buzz Implementation Modular multiplicative inverse Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24718, "s": 24690, "text": "\n10 Dec, 2021" }, { "code": null, "e": 24917, "s": 24718, "text": "Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value." }, { "code": null, "e": 24927, "s": 24917, "text": "Examples:" }, { "code": null, "e": 25160, "s": 24927, "text": "Input: Tree: 4 / \\ 5 2 / \\ 3 1 / \\6 12Output: 3Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 12 which are the children of node 3." }, { "code": null, "e": 25407, "s": 25160, "text": "Input: Tree: 1 / \\ 3 5 / \\ / \\ 6 9 4 8Output: 3Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 9 which are the children of node 5." }, { "code": null, "e": 25558, "s": 25407, "text": "Approach: To solve this problem, level order traversal of the Binary Tree can be used to find the maximum sum of siblings. Follow the following steps:" }, { "code": null, "e": 25621, "s": 25558, "text": "Start level order traversal of the tree from root of the tree." }, { "code": null, "e": 25876, "s": 25621, "text": "For each node, check if it has both the child.If yes, then find the node with maximum product of children and store this node value in a reference variable.Update the node value in reference variable if any node is found with greater product of children." }, { "code": null, "e": 25987, "s": 25876, "text": "If yes, then find the node with maximum product of children and store this node value in a reference variable." }, { "code": null, "e": 26086, "s": 25987, "text": "Update the node value in reference variable if any node is found with greater product of children." }, { "code": null, "e": 26152, "s": 26086, "text": "If the current node don’t have both children, then skip that node" }, { "code": null, "e": 26298, "s": 26152, "text": "Return the node value in reference variable, as it contains the node with maximum product of children, or the parent of maximum product siblings." }, { "code": null, "e": 26349, "s": 26298, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26353, "s": 26349, "text": "C++" }, { "code": null, "e": 26358, "s": 26353, "text": "Java" }, { "code": null, "e": 26366, "s": 26358, "text": "Python3" }, { "code": null, "e": 26369, "s": 26366, "text": "C#" }, { "code": null, "e": 26380, "s": 26369, "text": "Javascript" }, { "code": "// C++ code to find the Parent Node// of maximum product Siblings// in given Binary Tree #include <bits/stdc++.h>using namespace std; // Structure for Nodestruct Node { int data; Node *left, *right;}; // Function to get a new nodeNode* getNode(int data){ // Allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // Put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Function to get the parent// of siblings with maximum productint maxproduct(Node* root){ int mproduct = INT_MIN; int ans = 0; // Checking base case if (root == NULL || (root->left == NULL && root->right == NULL)) return 0; // Declaration of queue to run // level order traversal queue<Node*> q; q.push(root); // Loop to implement level order traversal while (!q.empty()) { Node* temp = q.front(); q.pop(); // If both the siblings are present // then take their product if (temp->right && temp->left) { int curr_max = temp->right->data * temp->left->data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp->data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = max(ans, temp->data); } } // pushing childs in the queue if (temp->right) { q.push(temp->right); } if (temp->left) { q.push(temp->left); } } return ans;} // Driver Codeint main(){ /* Binary tree creation 1 / \\ 3 5 / \\ / \\ 6 9 4 8 */ Node* root = getNode(1); root->left = getNode(3); root->right = getNode(5); root->left->left = getNode(6); root->left->right = getNode(9); root->right->left = getNode(4); root->right->right = getNode(8); cout << maxproduct(root) << endl; return 0;}", "e": 28498, "s": 26380, "text": null }, { "code": "// Java code to find the Parent Node// of maximum product Siblings// in given Binary Treeimport java.util.LinkedList;import java.util.Queue; class GFG { // Structure for Node static class Node { int data; Node left; Node right; public Node(int data) { this.data = data; this.left = null; this.right = null; } }; // Function to get a new node public static Node getNode(int data) { // Allocate space Node newNode = new Node(data); // Put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function to get the parent // of siblings with maximum product public static int maxproduct(Node root) { int mproduct = Integer.MIN_VALUE; int ans = 0; // Checking base case if (root == null || (root.left == null && root.right == null)) return 0; // Declaration of queue to run // level order traversal Queue<Node> q = new LinkedList<Node>(); q.add(root); // Loop to implement level order traversal while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); // If both the siblings are present // then take their product if (temp.right != null && temp.left != null) { int curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp.data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = Math.max(ans, temp.data); } } // pushing childs in the queue if (temp.right != null) { q.add(temp.right); } if (temp.left != null) { q.add(temp.left); } } return ans; } // Driver Code public static void main(String args[]) { /* * Binary tree creation * 1 * / \\ * 3 5 * / \\ / \\ * 6 9 4 8 */ Node root = getNode(1); root.left = getNode(3); root.right = getNode(5); root.left.left = getNode(6); root.left.right = getNode(9); root.right.left = getNode(4); root.right.right = getNode(8); System.out.println(maxproduct(root)); }} // This code is contributed by gfgking.", "e": 31162, "s": 28498, "text": null }, { "code": "# Python Program to implement# the above approach # Structure of a node of binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to get a new nodedef getNode(data): # Allocate space newNode = Node(data) return newNode # Function to get the parent# of siblings with maximum productdef maxproduct(root): mproduct = 10 ** -9 ans = 0; # Checking base case if (root == None or (root.left == None and root.right == None)): return 0; # Declaration of queue to run # level order traversal q = []; q.append(root); # Loop to implement level order traversal while (len(q)): temp = q[0]; q.pop(0); # If both the siblings are present # then take their product if (temp.right and temp.left): curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max): mproduct = curr_max ans = temp.data elif (mproduct == curr_max): # if max product is equal to # curr_max then consider node # which has maximum value ans = max(ans, temp.data) # pushing childs in the queue if (temp.right): q.append(temp.right) if (temp.left): q.append(temp.left) return ans # Driver Code \"\"\" Binary tree creation 1 / \\ 3 5 / \\ / \\ 6 9 4 8\"\"\"root = getNode(1);root.left = getNode(3);root.right = getNode(5);root.left.left = getNode(6);root.left.right = getNode(9);root.right.left = getNode(4);root.right.right = getNode(8); print(maxproduct(root)); # This code is contributed by gfgking", "e": 32905, "s": 31162, "text": null }, { "code": "// C# code to find the Parent Node// of maximum product Siblings// in given Binary Treeusing System;using System.Collections.Generic; public class GFG { // Structure for Node class Node { public int data; public Node left; public Node right; public Node(int data) { this.data = data; this.left = null; this.right = null; } }; // Function to get a new node static Node getNode(int data) { // Allocate space Node newNode = new Node(data); // Put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function to get the parent // of siblings with maximum product static int maxproduct(Node root) { int mproduct = int.MinValue; int ans = 0; // Checking base case if (root == null || (root.left == null && root.right == null)) return 0; // Declaration of queue to run // level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // Loop to implement level order traversal while (q.Count!=0) { Node temp = q.Peek(); q.Dequeue(); // If both the siblings are present // then take their product if (temp.right != null && temp.left != null) { int curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp.data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = Math.Max(ans, temp.data); } } // pushing childs in the queue if (temp.right != null) { q.Enqueue(temp.right); } if (temp.left != null) { q.Enqueue(temp.left); } } return ans; } // Driver Code public static void Main(String []args) { /* * Binary tree creation * 1 * / \\ * 3 5 * / \\ / \\ * 6 9 4 8 */ Node root = getNode(1); root.left = getNode(3); root.right = getNode(5); root.left.left = getNode(6); root.left.right = getNode(9); root.right.left = getNode(4); root.right.right = getNode(8); Console.WriteLine(maxproduct(root)); }} // This code is contributed by shikhasingrajput", "e": 35577, "s": 32905, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Structure of a node of binary tree class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } }; // Function to get a new node function getNode(data) { // Allocate space let newNode = new Node(data); return newNode; } // Function to get the parent // of siblings with maximum product function maxproduct(root) { let mproduct = Number.MIN_VALUE; let ans = 0; // Checking base case if (root == null || (root.left == null && root.right == null)) return 0; // Declaration of queue to run // level order traversal let q = []; q.push(root); // Loop to implement level order traversal while (!q.length == 0) { let temp = q[0]; q.shift(); // If both the siblings are present // then take their product if (temp.right && temp.left) { let curr_max = temp.right.data * temp.left.data; if (mproduct < curr_max) { mproduct = curr_max; ans = temp.data; } else if (mproduct == curr_max) { // if max product is equal to // curr_max then consider node // which has maximum value ans = Math.max(ans, temp.data); } } // pushing childs in the queue if (temp.right) { q.push(temp.right); } if (temp.left) { q.push(temp.left); } } return ans; } // Driver Code /* Binary tree creation 1 / \\ 3 5 / \\ / \\ 6 9 4 8 */ let root = getNode(1); root.left = getNode(3); root.right = getNode(5); root.left.left = getNode(6); root.left.right = getNode(9); root.right.left = getNode(4); root.right.right = getNode(8); document.write(maxproduct(root) + \"<br>\"); // This code is contributed by Potta Lokesh </script>", "e": 38217, "s": 35577, "text": null }, { "code": null, "e": 38222, "s": 38220, "text": "3" }, { "code": null, "e": 38313, "s": 38224, "text": "Time Complexity: O(V) where V is the number of nodes in the tree.Auxiliary Space: O(V). " }, { "code": null, "e": 38329, "s": 38315, "text": "lokeshpotta20" }, { "code": null, "e": 38337, "s": 38329, "text": "gfgking" }, { "code": null, "e": 38354, "s": 38337, "text": "shikhasingrajput" }, { "code": null, "e": 38371, "s": 38354, "text": "tree-level-order" }, { "code": null, "e": 38386, "s": 38371, "text": "tree-traversal" }, { "code": null, "e": 38399, "s": 38386, "text": "Mathematical" }, { "code": null, "e": 38404, "s": 38399, "text": "Tree" }, { "code": null, "e": 38417, "s": 38404, "text": "Mathematical" }, { "code": null, "e": 38422, "s": 38417, "text": "Tree" }, { "code": null, "e": 38520, "s": 38422, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38552, "s": 38520, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 38596, "s": 38552, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 38629, "s": 38596, "text": "Program to multiply two matrices" }, { "code": null, "e": 38654, "s": 38629, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38685, "s": 38654, "text": "Modular multiplicative inverse" }, { "code": null, "e": 38735, "s": 38685, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 38770, "s": 38735, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 38804, "s": 38770, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 38833, "s": 38804, "text": "AVL Tree | Set 1 (Insertion)" } ]
Your Guide to Web Scrape Quora Q&As | by Yasser Elsedawy | Towards Data Science
In this tutorial, I will show you how to perform web scraping using Anaconda Jupyter notebook and the BeautifulSoup library. We’ll be scraping Questions and Answers from Quora, and then we will export them to Pandas library dataframe and then to a .CSV file. Let us get straight down to business, however, if you’re looking on a guide to understand Web Scraping in general, I advise you of reading this article from Dataquest. Let’s import our libraries import urllibimport requestsfrom bs4 import BeautifulSoupimport pandas as pd Insert your Quora URL, an example is shown. url = ‘https://www.quora.com/Should-I-move-to-London' Then let’s make a GET request to the web server, which will download the HTML contents of a given web page for us. page = requests.get(url) Now, We can use the BeautifulSoup library to parse this page, and extract the text from it. We first have to create an instance of the BeautifulSoup class to parse our document: soup = BeautifulSoup(page.content, ‘html.parser’) Then we will create Pandas DataFrame to contain our Q&As wanted. df = pd.DataFrame({‘question’: [],’answers’:[]}) It’s now time to choose the Q&As classes from the web page, classes are used when scraping to specify specific elements we want to scrape. question = soup.find(‘span’, {‘class’: ‘ui_qtext_rendered_qtext’})answers = soup.find_all(‘div’, attrs={‘class’: ‘ui_qtext_expanded’}) And then we can conclude by adding the results to our DataFrame created before. for answer in answers: df = df.append({‘question’: question.text, ‘answers’: answer.text }, ignore_index=True)df Time to export the results to a CSV file. df.to_csv(‘One_URLs.csv’) This time we will work together to scrape more than one page in the same time. The process is almost identical with relative changes. Start by importing your libraries import urllibimport requestsfrom bs4 import BeautifulSoupimport pandas as pd Add all the URLs that you need, we will have 2 at this time url = [‘https://www.quora.com/What-are-best-places-to-relocate-and-settle-in-UK', ‘https://www.quora.com/Should-I-relocate-to-the-UK'] Create our DataFrame df = pd.DataFrame({‘question’: [],’answers’:[]}) Now, we will do a for loop that will iterate over the two URLs to do the same process and then it can save our results to a DataFrame. for i in url: page = requests.get(i) soup = BeautifulSoup(page.content, “html.parser”) question = soup.find(‘span’, {‘class’: ‘ui_qtext_rendered_qtext’}) answers = soup.find_all(‘div’, attrs={‘class’: ‘ui_qtext_expanded’}) for answer in answers: df = df.append({‘question’: question.text, ‘answers’: answer.text }, ignore_index=True)df Now, let’s export the DataFrame to a CSV file. df.to_csv(‘Two_URLs.csv’) You should now have a good understanding of how to scrape and extract data from Quora. A good next step for you if you are familiar a bit with web scraping it to pick a site and try some web scraping on your own.
[ { "code": null, "e": 297, "s": 172, "text": "In this tutorial, I will show you how to perform web scraping using Anaconda Jupyter notebook and the BeautifulSoup library." }, { "code": null, "e": 431, "s": 297, "text": "We’ll be scraping Questions and Answers from Quora, and then we will export them to Pandas library dataframe and then to a .CSV file." }, { "code": null, "e": 599, "s": 431, "text": "Let us get straight down to business, however, if you’re looking on a guide to understand Web Scraping in general, I advise you of reading this article from Dataquest." }, { "code": null, "e": 626, "s": 599, "text": "Let’s import our libraries" }, { "code": null, "e": 703, "s": 626, "text": "import urllibimport requestsfrom bs4 import BeautifulSoupimport pandas as pd" }, { "code": null, "e": 747, "s": 703, "text": "Insert your Quora URL, an example is shown." }, { "code": null, "e": 801, "s": 747, "text": "url = ‘https://www.quora.com/Should-I-move-to-London'" }, { "code": null, "e": 916, "s": 801, "text": "Then let’s make a GET request to the web server, which will download the HTML contents of a given web page for us." }, { "code": null, "e": 941, "s": 916, "text": "page = requests.get(url)" }, { "code": null, "e": 1119, "s": 941, "text": "Now, We can use the BeautifulSoup library to parse this page, and extract the text from it. We first have to create an instance of the BeautifulSoup class to parse our document:" }, { "code": null, "e": 1169, "s": 1119, "text": "soup = BeautifulSoup(page.content, ‘html.parser’)" }, { "code": null, "e": 1234, "s": 1169, "text": "Then we will create Pandas DataFrame to contain our Q&As wanted." }, { "code": null, "e": 1283, "s": 1234, "text": "df = pd.DataFrame({‘question’: [],’answers’:[]})" }, { "code": null, "e": 1422, "s": 1283, "text": "It’s now time to choose the Q&As classes from the web page, classes are used when scraping to specify specific elements we want to scrape." }, { "code": null, "e": 1557, "s": 1422, "text": "question = soup.find(‘span’, {‘class’: ‘ui_qtext_rendered_qtext’})answers = soup.find_all(‘div’, attrs={‘class’: ‘ui_qtext_expanded’})" }, { "code": null, "e": 1637, "s": 1557, "text": "And then we can conclude by adding the results to our DataFrame created before." }, { "code": null, "e": 1771, "s": 1637, "text": "for answer in answers: df = df.append({‘question’: question.text, ‘answers’: answer.text }, ignore_index=True)df" }, { "code": null, "e": 1813, "s": 1771, "text": "Time to export the results to a CSV file." }, { "code": null, "e": 1839, "s": 1813, "text": "df.to_csv(‘One_URLs.csv’)" }, { "code": null, "e": 1973, "s": 1839, "text": "This time we will work together to scrape more than one page in the same time. The process is almost identical with relative changes." }, { "code": null, "e": 2007, "s": 1973, "text": "Start by importing your libraries" }, { "code": null, "e": 2084, "s": 2007, "text": "import urllibimport requestsfrom bs4 import BeautifulSoupimport pandas as pd" }, { "code": null, "e": 2144, "s": 2084, "text": "Add all the URLs that you need, we will have 2 at this time" }, { "code": null, "e": 2279, "s": 2144, "text": "url = [‘https://www.quora.com/What-are-best-places-to-relocate-and-settle-in-UK', ‘https://www.quora.com/Should-I-relocate-to-the-UK']" }, { "code": null, "e": 2300, "s": 2279, "text": "Create our DataFrame" }, { "code": null, "e": 2349, "s": 2300, "text": "df = pd.DataFrame({‘question’: [],’answers’:[]})" }, { "code": null, "e": 2484, "s": 2349, "text": "Now, we will do a for loop that will iterate over the two URLs to do the same process and then it can save our results to a DataFrame." }, { "code": null, "e": 2893, "s": 2484, "text": "for i in url: page = requests.get(i) soup = BeautifulSoup(page.content, “html.parser”) question = soup.find(‘span’, {‘class’: ‘ui_qtext_rendered_qtext’}) answers = soup.find_all(‘div’, attrs={‘class’: ‘ui_qtext_expanded’}) for answer in answers: df = df.append({‘question’: question.text, ‘answers’: answer.text }, ignore_index=True)df" }, { "code": null, "e": 2940, "s": 2893, "text": "Now, let’s export the DataFrame to a CSV file." }, { "code": null, "e": 2966, "s": 2940, "text": "df.to_csv(‘Two_URLs.csv’)" } ]
How to quit/ exit from MySQL stored procedure?
We can quit/ exit from MySQL stored procedure with the help of the LEAVE command. The following is the syntax. Leave yourLabelName; The following is an example. Here, we are creating a new procedure. mysql> delimiter // mysql> CREATE PROCEDURE ExitQuitDemo2(IN Var1 VARCHAR(20)) -> proc_Exit:BEGIN -> IF Var1 IS NULL THEN -> LEAVE proc_Exit; -> END IF; -> END // Query OK, 0 rows affected (0.16 sec) Above, we have set the following LEAVE command to exit from the procedure. If Var1 is “NULL”, the procedure will exit. LEAVE proc_Exit; To change the delimiter to ‘;’. mysql>delimiter ; mysql> To call stored procedure, we need to use CALL command followed by the procedure name. The following is the syntax. call yourStoredProcedureName;
[ { "code": null, "e": 1144, "s": 1062, "text": "We can quit/ exit from MySQL stored procedure with the help of the LEAVE command." }, { "code": null, "e": 1173, "s": 1144, "text": "The following is the syntax." }, { "code": null, "e": 1195, "s": 1173, "text": "Leave yourLabelName;\n" }, { "code": null, "e": 1263, "s": 1195, "text": "The following is an example. Here, we are creating a new procedure." }, { "code": null, "e": 1478, "s": 1263, "text": "mysql> delimiter //\nmysql> CREATE PROCEDURE ExitQuitDemo2(IN Var1 VARCHAR(20))\n -> proc_Exit:BEGIN\n -> IF Var1 IS NULL THEN\n -> LEAVE proc_Exit;\n -> END IF;\n -> END //\nQuery OK, 0 rows affected (0.16 sec)" }, { "code": null, "e": 1597, "s": 1478, "text": "Above, we have set the following LEAVE command to exit from the procedure. If Var1 is “NULL”, the procedure will exit." }, { "code": null, "e": 1614, "s": 1597, "text": "LEAVE proc_Exit;" }, { "code": null, "e": 1646, "s": 1614, "text": "To change the delimiter to ‘;’." }, { "code": null, "e": 1671, "s": 1646, "text": "mysql>delimiter ;\nmysql>" }, { "code": null, "e": 1757, "s": 1671, "text": "To call stored procedure, we need to use CALL command followed by the procedure name." }, { "code": null, "e": 1786, "s": 1757, "text": "The following is the syntax." }, { "code": null, "e": 1816, "s": 1786, "text": "call yourStoredProcedureName;" } ]
Object Detection with Voice Feedback — YOLO v3 + gTTS | by Jason Yip | Towards Data Science
Final exams are finally over!!! I was fascinated by the idea of object detection in Computer Vision and wanted to start a project on it. I realized that we could probably help the blind “see” better using Image-to-Text and Text-to-Voice, without any complex hardware. Having a complete understanding of every single piece in the whole pipeline is extremely difficult but I have attempted to understand as much as I need to know for this task. is a field of Computer Vision that detects instances of semantic objects in images/videos (by creating bounding boxes around them in our case). We can then convert the annotated text into voice responses and give the basic positions of the objects in the person/camera’s view. Training Data: The model is trained with the Common Objects In Context (COCO) dataset. You can explore the images that they labeled in the link, it’s pretty cool.Model: The model here is the You Only Look Once (YOLO) algorithm that runs through a variation of an extremely complex Convolutional Neural Network architecture called the Darknet. Even though we are using a more enhanced and complex YOLO v3 model, I will explain the original YOLO algorithm. Also, the python cv2 package has a method to setup Darknet from our configurations in the yolov3.cfg file. Training Data: The model is trained with the Common Objects In Context (COCO) dataset. You can explore the images that they labeled in the link, it’s pretty cool. Model: The model here is the You Only Look Once (YOLO) algorithm that runs through a variation of an extremely complex Convolutional Neural Network architecture called the Darknet. Even though we are using a more enhanced and complex YOLO v3 model, I will explain the original YOLO algorithm. Also, the python cv2 package has a method to setup Darknet from our configurations in the yolov3.cfg file. I am more interested in getting something to work as soon as possible this time round so I will be using a pre-trained model. This means that COCO has already been trained on YOLO v3 by others and we have already obtained the weights stored in a 200+mb file. If you are not sure what weights are, think of it as trying to find the Best Fit Line in Linear Regression. We need to find the right values of m and c in y=mx+c such that our line minimizes the error between all points. Now in our more complex prediction task, we have millions of Xs when we feed images into the complex network. These Xs will each have an m and these are the predicted weights stored in our yolov3.weights file. The ms have been constantly readjusted to minimize some loss function. 3. Input Data: We will be using our webcam to feed images at 30 frames-per-second to this trained model and we can set it to only process every other frame to speed things up. 4. API: The class prediction of the objects detected in every frame will be a string e.g. “cat”. We will also obtain the coordinates of the objects in the image and append the position “top”/“mid”/“bottom” & “left”/“center”/“right” to the class prediction “cat”. We can then send the text description to the Google Text-to-Speech API using the gTTS package. 5. Output: We will also obtain the coordinates of the bounding box of every object detected in our frames, overlay the boxes on the objects detected and return the stream of frames as a video playback. We will also schedule to get a voice feedback on the 1st frame of each second (instead of 30 fps) e.g. “bottom left cat” — meaning a cat was detected on the bottom-left of my camera view. Previously, classification-based models were used to detect objects using localization, region-based classification or things such as the sliding window. Only high scoring regions of the image are considered as a detection and they could be very time-consuming. Instead, YOLO is regression-based. We’re predicting classes and bounding boxes for the whole image quickly in one run of the algorithm (just one look of the image’s pixels), so that the predictions are informed by the global context in the image. C represents the class index of the object we are trying to label. A sports ball would mean C=33. The training has already been done on COCO. During training time, we have to manually label the following 5 values for each object in the image in this format C bx by bw bh. We will also normalize each of the 4 b values to lie between 0–1 by representing them as a proportion of W & H (1280 x 720 px). Suppose we have 2 objects labeled in the frame — The sports ball and myself. This is represented by tensors: a general form of a vector, which will be fed into the model during training. [33, 0.21, 0.58, 0.23, 0.42] - sports ball[1, 0.67, 0.5, 0.5, 0.9] - myself Now we are feeding 1280 x 720 frames from our camera into YOLO at Prediction time. YOLO will automatically resize it to 416 x 234 and fit it into a popular standard-sized 416 x 416 network by padding the excess with 0s. YOLO divides each image into S x S cells each with a size of 32 x 32 (reduction factor=32). This creates 416/32 = 13 x 13 cells. There are 5 values in a bounding box — (bx, by, bw, bh, BC) If the center of an object (red dot) falls into a grid cell, only that grid cell (dark green cell) is responsible for detecting that object. Each bounding box has 5 values. The first 4 values bx, by, bw, bh represent the position of the box. The 5th value is BC: the box confidence score. BC = Pr(Object existing in box) * IOU (Intersection Over Union). This measures how likely the box contains an object of any class and how accurate it is in predicting. BC=0 if no object exists in that box and we want BC=1 in predicting the ground truth. There are B bounding boxes predicted in each grid cell There are also C conditional class probabilities in each grid cell There are 80 conditional class probabilities — Pr(Class i | Object) per cell when we use COCO. It is the probability that the predicted object is of Class i given that there is an object in the cell. 1 person 0.012 bicycle 0.004..33 sports ball 0.9..80 toothbrush 0.02 In our example above, Class 33 has the highest probability and it will be used as our prediction of the object to be a sports ball. To sum up the above There are S x S cells and in each of these cells there are 2 things: 1) B bounding boxes each with 5 values (bx, by, bw, bh, BC), 2) C conditional class probabilities. The predictions are encoded as a S x S x (5 * B + C) tensor. Non-Max Suppression There are actually B duplicate detections for the grid cell that is the only one used to predict the object (dark green box). NMS suppresses detections with low box confidence scores: BC, so that we don’t end up predicting 3 sports balls when there is only just one. An implementation of NMS could be: Start with the bounding box that has the highest BC.Remove any remaining bounding boxes that overlap it more than the given threshold amount = 0.5.Go to step 1 until there are no more bounding boxes left. Start with the bounding box that has the highest BC. Remove any remaining bounding boxes that overlap it more than the given threshold amount = 0.5. Go to step 1 until there are no more bounding boxes left. While we already have our predictions, we want to understand how the weights were being adjusted such that our loss function for this model was minimized during Training Time. The function looks complex but it is actually very intuitive when broken down. Difference between the ground-truth box vs the predicted boundary box.Difference between 100% confidence that an object is in the box vs the box confidence.Difference between C actual class probabilities (0, ..., 1, ..., 0) vs C predicted class probabilities (0.01, ..., 0.8, ..., 0.02) Difference between the ground-truth box vs the predicted boundary box. Difference between 100% confidence that an object is in the box vs the box confidence. Difference between C actual class probabilities (0, ..., 1, ..., 0) vs C predicted class probabilities (0.01, ..., 0.8, ..., 0.02) The parameter λcoord is usually =5 to increase the weight of the localization loss to give it more importance. The parameter λnoobj is usually =0.5 to decrease the weight of the confidence loss since boxes that do not contain objects have confidence scores BC=0. This makes the model more stable and easier to converge. Voice Feedback We can use bx & by relative to W & H to determine the position of the objects detected and send it as a text string to gTTS with this simple command. tts = gTTS("mid left sports ball, lang=’en’)tts.save(‘tts.mp3’) I also used pydub and ffmpeg to manipulate the audio files generated. I am unable to return the frames in real-time because it will make the video playback seem very jerky when it processes every 30th frame. I also explored multi-threading, which in theory should create 1 process for processing every 30th frame and another process for the video playback. However, I am only able to produce the verbal description of objects detected in real-time on my webcam which is more important since the blind can’t see bounding boxes anyway. For the video below, I recorded myself before passing it to create the bounding boxes and generate the verbal responses. There it is, YOLO v3 on COCO along with gTTS, doing its magic! I’m enjoying this process of learning, doing and then sharing. I think “learning by applying” is taken to the next level when it comes to sharing. Breaking complex problems into simpler ones and understanding & explaining difficult concepts in layman terms is a skill I’d love to hone further. More to come! Link to project repo Discuss further with me on LinkedIn or via jasonyip184@gmail.com!
[ { "code": null, "e": 439, "s": 171, "text": "Final exams are finally over!!! I was fascinated by the idea of object detection in Computer Vision and wanted to start a project on it. I realized that we could probably help the blind “see” better using Image-to-Text and Text-to-Voice, without any complex hardware." }, { "code": null, "e": 614, "s": 439, "text": "Having a complete understanding of every single piece in the whole pipeline is extremely difficult but I have attempted to understand as much as I need to know for this task." }, { "code": null, "e": 891, "s": 614, "text": "is a field of Computer Vision that detects instances of semantic objects in images/videos (by creating bounding boxes around them in our case). We can then convert the annotated text into voice responses and give the basic positions of the objects in the person/camera’s view." }, { "code": null, "e": 1453, "s": 891, "text": "Training Data: The model is trained with the Common Objects In Context (COCO) dataset. You can explore the images that they labeled in the link, it’s pretty cool.Model: The model here is the You Only Look Once (YOLO) algorithm that runs through a variation of an extremely complex Convolutional Neural Network architecture called the Darknet. Even though we are using a more enhanced and complex YOLO v3 model, I will explain the original YOLO algorithm. Also, the python cv2 package has a method to setup Darknet from our configurations in the yolov3.cfg file." }, { "code": null, "e": 1616, "s": 1453, "text": "Training Data: The model is trained with the Common Objects In Context (COCO) dataset. You can explore the images that they labeled in the link, it’s pretty cool." }, { "code": null, "e": 2016, "s": 1616, "text": "Model: The model here is the You Only Look Once (YOLO) algorithm that runs through a variation of an extremely complex Convolutional Neural Network architecture called the Darknet. Even though we are using a more enhanced and complex YOLO v3 model, I will explain the original YOLO algorithm. Also, the python cv2 package has a method to setup Darknet from our configurations in the yolov3.cfg file." }, { "code": null, "e": 2275, "s": 2016, "text": "I am more interested in getting something to work as soon as possible this time round so I will be using a pre-trained model. This means that COCO has already been trained on YOLO v3 by others and we have already obtained the weights stored in a 200+mb file." }, { "code": null, "e": 2777, "s": 2275, "text": "If you are not sure what weights are, think of it as trying to find the Best Fit Line in Linear Regression. We need to find the right values of m and c in y=mx+c such that our line minimizes the error between all points. Now in our more complex prediction task, we have millions of Xs when we feed images into the complex network. These Xs will each have an m and these are the predicted weights stored in our yolov3.weights file. The ms have been constantly readjusted to minimize some loss function." }, { "code": null, "e": 2953, "s": 2777, "text": "3. Input Data: We will be using our webcam to feed images at 30 frames-per-second to this trained model and we can set it to only process every other frame to speed things up." }, { "code": null, "e": 3311, "s": 2953, "text": "4. API: The class prediction of the objects detected in every frame will be a string e.g. “cat”. We will also obtain the coordinates of the objects in the image and append the position “top”/“mid”/“bottom” & “left”/“center”/“right” to the class prediction “cat”. We can then send the text description to the Google Text-to-Speech API using the gTTS package." }, { "code": null, "e": 3701, "s": 3311, "text": "5. Output: We will also obtain the coordinates of the bounding box of every object detected in our frames, overlay the boxes on the objects detected and return the stream of frames as a video playback. We will also schedule to get a voice feedback on the 1st frame of each second (instead of 30 fps) e.g. “bottom left cat” — meaning a cat was detected on the bottom-left of my camera view." }, { "code": null, "e": 3963, "s": 3701, "text": "Previously, classification-based models were used to detect objects using localization, region-based classification or things such as the sliding window. Only high scoring regions of the image are considered as a detection and they could be very time-consuming." }, { "code": null, "e": 4210, "s": 3963, "text": "Instead, YOLO is regression-based. We’re predicting classes and bounding boxes for the whole image quickly in one run of the algorithm (just one look of the image’s pixels), so that the predictions are informed by the global context in the image." }, { "code": null, "e": 4352, "s": 4210, "text": "C represents the class index of the object we are trying to label. A sports ball would mean C=33. The training has already been done on COCO." }, { "code": null, "e": 4610, "s": 4352, "text": "During training time, we have to manually label the following 5 values for each object in the image in this format C bx by bw bh. We will also normalize each of the 4 b values to lie between 0–1 by representing them as a proportion of W & H (1280 x 720 px)." }, { "code": null, "e": 4797, "s": 4610, "text": "Suppose we have 2 objects labeled in the frame — The sports ball and myself. This is represented by tensors: a general form of a vector, which will be fed into the model during training." }, { "code": null, "e": 4877, "s": 4797, "text": "[33, 0.21, 0.58, 0.23, 0.42] - sports ball[1, 0.67, 0.5, 0.5, 0.9] - myself" }, { "code": null, "e": 5226, "s": 4877, "text": "Now we are feeding 1280 x 720 frames from our camera into YOLO at Prediction time. YOLO will automatically resize it to 416 x 234 and fit it into a popular standard-sized 416 x 416 network by padding the excess with 0s. YOLO divides each image into S x S cells each with a size of 32 x 32 (reduction factor=32). This creates 416/32 = 13 x 13 cells." }, { "code": null, "e": 5286, "s": 5226, "text": "There are 5 values in a bounding box — (bx, by, bw, bh, BC)" }, { "code": null, "e": 5528, "s": 5286, "text": "If the center of an object (red dot) falls into a grid cell, only that grid cell (dark green cell) is responsible for detecting that object. Each bounding box has 5 values. The first 4 values bx, by, bw, bh represent the position of the box." }, { "code": null, "e": 5575, "s": 5528, "text": "The 5th value is BC: the box confidence score." }, { "code": null, "e": 5640, "s": 5575, "text": "BC = Pr(Object existing in box) * IOU (Intersection Over Union)." }, { "code": null, "e": 5829, "s": 5640, "text": "This measures how likely the box contains an object of any class and how accurate it is in predicting. BC=0 if no object exists in that box and we want BC=1 in predicting the ground truth." }, { "code": null, "e": 5884, "s": 5829, "text": "There are B bounding boxes predicted in each grid cell" }, { "code": null, "e": 5951, "s": 5884, "text": "There are also C conditional class probabilities in each grid cell" }, { "code": null, "e": 6151, "s": 5951, "text": "There are 80 conditional class probabilities — Pr(Class i | Object) per cell when we use COCO. It is the probability that the predicted object is of Class i given that there is an object in the cell." }, { "code": null, "e": 6220, "s": 6151, "text": "1 person 0.012 bicycle 0.004..33 sports ball 0.9..80 toothbrush 0.02" }, { "code": null, "e": 6352, "s": 6220, "text": "In our example above, Class 33 has the highest probability and it will be used as our prediction of the object to be a sports ball." }, { "code": null, "e": 6372, "s": 6352, "text": "To sum up the above" }, { "code": null, "e": 6601, "s": 6372, "text": "There are S x S cells and in each of these cells there are 2 things: 1) B bounding boxes each with 5 values (bx, by, bw, bh, BC), 2) C conditional class probabilities. The predictions are encoded as a S x S x (5 * B + C) tensor." }, { "code": null, "e": 6621, "s": 6601, "text": "Non-Max Suppression" }, { "code": null, "e": 6923, "s": 6621, "text": "There are actually B duplicate detections for the grid cell that is the only one used to predict the object (dark green box). NMS suppresses detections with low box confidence scores: BC, so that we don’t end up predicting 3 sports balls when there is only just one. An implementation of NMS could be:" }, { "code": null, "e": 7128, "s": 6923, "text": "Start with the bounding box that has the highest BC.Remove any remaining bounding boxes that overlap it more than the given threshold amount = 0.5.Go to step 1 until there are no more bounding boxes left." }, { "code": null, "e": 7181, "s": 7128, "text": "Start with the bounding box that has the highest BC." }, { "code": null, "e": 7277, "s": 7181, "text": "Remove any remaining bounding boxes that overlap it more than the given threshold amount = 0.5." }, { "code": null, "e": 7335, "s": 7277, "text": "Go to step 1 until there are no more bounding boxes left." }, { "code": null, "e": 7590, "s": 7335, "text": "While we already have our predictions, we want to understand how the weights were being adjusted such that our loss function for this model was minimized during Training Time. The function looks complex but it is actually very intuitive when broken down." }, { "code": null, "e": 7877, "s": 7590, "text": "Difference between the ground-truth box vs the predicted boundary box.Difference between 100% confidence that an object is in the box vs the box confidence.Difference between C actual class probabilities (0, ..., 1, ..., 0) vs C predicted class probabilities (0.01, ..., 0.8, ..., 0.02)" }, { "code": null, "e": 7948, "s": 7877, "text": "Difference between the ground-truth box vs the predicted boundary box." }, { "code": null, "e": 8035, "s": 7948, "text": "Difference between 100% confidence that an object is in the box vs the box confidence." }, { "code": null, "e": 8166, "s": 8035, "text": "Difference between C actual class probabilities (0, ..., 1, ..., 0) vs C predicted class probabilities (0.01, ..., 0.8, ..., 0.02)" }, { "code": null, "e": 8277, "s": 8166, "text": "The parameter λcoord is usually =5 to increase the weight of the localization loss to give it more importance." }, { "code": null, "e": 8486, "s": 8277, "text": "The parameter λnoobj is usually =0.5 to decrease the weight of the confidence loss since boxes that do not contain objects have confidence scores BC=0. This makes the model more stable and easier to converge." }, { "code": null, "e": 8501, "s": 8486, "text": "Voice Feedback" }, { "code": null, "e": 8651, "s": 8501, "text": "We can use bx & by relative to W & H to determine the position of the objects detected and send it as a text string to gTTS with this simple command." }, { "code": null, "e": 8715, "s": 8651, "text": "tts = gTTS(\"mid left sports ball, lang=’en’)tts.save(‘tts.mp3’)" }, { "code": null, "e": 8785, "s": 8715, "text": "I also used pydub and ffmpeg to manipulate the audio files generated." }, { "code": null, "e": 9072, "s": 8785, "text": "I am unable to return the frames in real-time because it will make the video playback seem very jerky when it processes every 30th frame. I also explored multi-threading, which in theory should create 1 process for processing every 30th frame and another process for the video playback." }, { "code": null, "e": 9370, "s": 9072, "text": "However, I am only able to produce the verbal description of objects detected in real-time on my webcam which is more important since the blind can’t see bounding boxes anyway. For the video below, I recorded myself before passing it to create the bounding boxes and generate the verbal responses." }, { "code": null, "e": 9433, "s": 9370, "text": "There it is, YOLO v3 on COCO along with gTTS, doing its magic!" }, { "code": null, "e": 9741, "s": 9433, "text": "I’m enjoying this process of learning, doing and then sharing. I think “learning by applying” is taken to the next level when it comes to sharing. Breaking complex problems into simpler ones and understanding & explaining difficult concepts in layman terms is a skill I’d love to hone further. More to come!" }, { "code": null, "e": 9762, "s": 9741, "text": "Link to project repo" } ]
Java Program to sort String Stream with reversed Comparator
Let us first create a String List: List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor"); Now compare each element for reverse: Comparator<String> comp = (aName, bName) -> aName.compareTo(bName); Now, perform sort: list.stream().sorted(comp.reversed()) The following is an example to sort String Stream with reversed Comparator: import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Demo { public static void main(String[] args) { List<String> list = Arrays.asList("Tom", "Jack", "Ryan", "Kevin", "Loki", "Thor"); System.out.println("Initial List = "+list); System.out.println("Reverse..."); Comparator<String> comp = (aName, bName) -> aName.compareTo(bName); list.stream().sorted(comp.reversed()) .forEach(System.out::println); } } Initial List = [Tom, Jack, Ryan, Kevin, Loki, Thor] Reverse... Tom Thor Ryan Loki Kevin Jack
[ { "code": null, "e": 1097, "s": 1062, "text": "Let us first create a String List:" }, { "code": null, "e": 1180, "s": 1097, "text": "List<String> list = Arrays.asList(\"Tom\", \"Jack\", \"Ryan\", \"Kevin\", \"Loki\", \"Thor\");" }, { "code": null, "e": 1218, "s": 1180, "text": "Now compare each element for reverse:" }, { "code": null, "e": 1286, "s": 1218, "text": "Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);" }, { "code": null, "e": 1305, "s": 1286, "text": "Now, perform sort:" }, { "code": null, "e": 1343, "s": 1305, "text": "list.stream().sorted(comp.reversed())" }, { "code": null, "e": 1419, "s": 1343, "text": "The following is an example to sort String Stream with reversed Comparator:" }, { "code": null, "e": 1895, "s": 1419, "text": "import java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n List<String> list = Arrays.asList(\"Tom\", \"Jack\", \"Ryan\", \"Kevin\", \"Loki\", \"Thor\");\n System.out.println(\"Initial List = \"+list);\n System.out.println(\"Reverse...\");\n Comparator<String> comp = (aName, bName) -> aName.compareTo(bName);\n list.stream().sorted(comp.reversed()) .forEach(System.out::println);\n }\n}" }, { "code": null, "e": 1988, "s": 1895, "text": "Initial List = [Tom, Jack, Ryan, Kevin, Loki, Thor]\nReverse...\nTom\nThor\nRyan\nLoki\nKevin\nJack" } ]
How can we implement a Custom HashSet in Java?
A HashSet implements Set interface which does not allow duplicate values. A HashSet is not synchronized and is not thread-safe. When we can add any duplicate element to a HashSet, the add() method returns false and does not allow to add a duplicate element to HashSet. Syntax public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable In the below example, we can implement a Custom HashSet. import java.util.*; public class CustomHashSetTest extends AbstractSet { private HashMap<Object, Object> map = null; private static final Object tempObject = new Object(); public CustomHashSetTest() { map = new HashMap<>(); } public boolean add(Object object) { return map.put(object, tempObject)==null; } public static void main(String[] args) { CustomHashSetTest test = new CustomHashSetTest(); test.add("India"); test.add("Australia"); test.add("England"); test.add("Australia"); for(Object object : test) { System.out.println(object.toString()); } } @Override public Iterator iterator() { return map.keySet().iterator(); } @Override public int size() { return map.size(); } } England Australia India
[ { "code": null, "e": 1331, "s": 1062, "text": "A HashSet implements Set interface which does not allow duplicate values. A HashSet is not synchronized and is not thread-safe. When we can add any duplicate element to a HashSet, the add() method returns false and does not allow to add a duplicate element to HashSet." }, { "code": null, "e": 1338, "s": 1331, "text": "Syntax" }, { "code": null, "e": 1428, "s": 1338, "text": "public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable" }, { "code": null, "e": 1485, "s": 1428, "text": "In the below example, we can implement a Custom HashSet." }, { "code": null, "e": 2282, "s": 1485, "text": "import java.util.*;\npublic class CustomHashSetTest extends AbstractSet {\n private HashMap<Object, Object> map = null;\n private static final Object tempObject = new Object();\n public CustomHashSetTest() {\n map = new HashMap<>();\n }\n public boolean add(Object object) {\n return map.put(object, tempObject)==null;\n }\n public static void main(String[] args) {\n CustomHashSetTest test = new CustomHashSetTest();\n test.add(\"India\");\n test.add(\"Australia\");\n test.add(\"England\");\n test.add(\"Australia\");\n for(Object object : test) {\n System.out.println(object.toString());\n }\n }\n @Override\n public Iterator iterator() {\n return map.keySet().iterator();\n }\n @Override\n public int size() {\n return map.size();\n }\n}" }, { "code": null, "e": 2306, "s": 2282, "text": "England\nAustralia\nIndia" } ]
BigInteger shiftRight() Method in Java - GeeksforGeeks
04 Dec, 2018 prerequisite : BigInteger Basics The java.math.BigInteger.shiftRight(int n) method returns a BigInteger whose value is (this >> n). The shift distance, n, may be negative, in which case this method performs a left shift. The shiftRight() method will move each digit in a number’s binary representation right by n times and the last bit in the direction of the shift is replaced by 0. This shiftRight() method Computes floor(this / 2^n). Syntax: public BigInteger shiftRight(int n) Parameter: The method takes one parameter n of integer type which refers to the shift distance in bits. Return Value: The method returns the BigInteger after shifting the bits to right by n times. Exceptions: The method might throws an ArithmeticException if the shift distance is an Integer.MIN_VALUE. Examples: Input: BigInteger = 2300, n = 3 Output: 287 Explanation: Binary Representation of 2300 = 100011111100 Shift distance, n = 3. After shifting 100011111100 right 3 times, Binary Representation becomes 100011111 and Decimal equivalent of 100011111 is 287. Input: BigInteger = 35000, n = 5 Output: 1093 Below program illustrates shiftRight(index) method of BigInteger: // Program to demonstrate shiftRight()// method of BigInteger import java.math.*; public class GFG { public static void main(String[] args) { // Create BigInteger object BigInteger biginteger = new BigInteger("2300"); // Create a int i for Shift Distance int i = 3; // Call shiftRight() method on bigInteger at index i // store the return value as BigInteger BigInteger changedvalue = biginteger.shiftRight(i); String result = "After applying shiftRight by Shift Distance " + i + " on " + biginteger + " New Value is " + changedvalue; // Print result System.out.println(result); }} After applying shiftRight by Shift Distance 3 on 2300 New Value is 287 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#shiftRight(int) Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger 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 How to iterate any Map in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java
[ { "code": null, "e": 24456, "s": 24428, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24489, "s": 24456, "text": "prerequisite : BigInteger Basics" }, { "code": null, "e": 24893, "s": 24489, "text": "The java.math.BigInteger.shiftRight(int n) method returns a BigInteger whose value is (this >> n). The shift distance, n, may be negative, in which case this method performs a left shift. The shiftRight() method will move each digit in a number’s binary representation right by n times and the last bit in the direction of the shift is replaced by 0. This shiftRight() method Computes floor(this / 2^n)." }, { "code": null, "e": 24901, "s": 24893, "text": "Syntax:" }, { "code": null, "e": 24937, "s": 24901, "text": "public BigInteger shiftRight(int n)" }, { "code": null, "e": 25041, "s": 24937, "text": "Parameter: The method takes one parameter n of integer type which refers to the shift distance in bits." }, { "code": null, "e": 25134, "s": 25041, "text": "Return Value: The method returns the BigInteger after shifting the bits to right by n times." }, { "code": null, "e": 25240, "s": 25134, "text": "Exceptions: The method might throws an ArithmeticException if the shift distance is an Integer.MIN_VALUE." }, { "code": null, "e": 25250, "s": 25240, "text": "Examples:" }, { "code": null, "e": 25551, "s": 25250, "text": "Input: BigInteger = 2300, n = 3\nOutput: 287\nExplanation:\nBinary Representation of 2300 = 100011111100\nShift distance, n = 3. \nAfter shifting 100011111100 right 3 times,\nBinary Representation becomes 100011111\nand Decimal equivalent of 100011111 is 287.\n\nInput: BigInteger = 35000, n = 5\nOutput: 1093\n" }, { "code": null, "e": 25617, "s": 25551, "text": "Below program illustrates shiftRight(index) method of BigInteger:" }, { "code": "// Program to demonstrate shiftRight()// method of BigInteger import java.math.*; public class GFG { public static void main(String[] args) { // Create BigInteger object BigInteger biginteger = new BigInteger(\"2300\"); // Create a int i for Shift Distance int i = 3; // Call shiftRight() method on bigInteger at index i // store the return value as BigInteger BigInteger changedvalue = biginteger.shiftRight(i); String result = \"After applying shiftRight by Shift Distance \" + i + \" on \" + biginteger + \" New Value is \" + changedvalue; // Print result System.out.println(result); }}", "e": 26301, "s": 25617, "text": null }, { "code": null, "e": 26373, "s": 26301, "text": "After applying shiftRight by Shift Distance 3 on 2300 New Value is 287\n" }, { "code": null, "e": 26468, "s": 26373, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#shiftRight(int)" }, { "code": null, "e": 26484, "s": 26468, "text": "Java-BigInteger" }, { "code": null, "e": 26499, "s": 26484, "text": "Java-Functions" }, { "code": null, "e": 26509, "s": 26499, "text": "java-math" }, { "code": null, "e": 26527, "s": 26509, "text": "Java-math-package" }, { "code": null, "e": 26532, "s": 26527, "text": "Java" }, { "code": null, "e": 26548, "s": 26532, "text": "Java-BigInteger" }, { "code": null, "e": 26553, "s": 26548, "text": "Java" }, { "code": null, "e": 26651, "s": 26553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26683, "s": 26651, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26734, "s": 26683, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26764, "s": 26734, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26783, "s": 26764, "text": "Interfaces in Java" }, { "code": null, "e": 26814, "s": 26783, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26832, "s": 26814, "text": "ArrayList in Java" }, { "code": null, "e": 26864, "s": 26832, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26879, "s": 26864, "text": "Stream In Java" }, { "code": null, "e": 26899, "s": 26879, "text": "Stack Class in Java" } ]
How to create Date Picker in ReactJS? - GeeksforGeeks
20 Jan, 2021 Date pickers provide a simple way to select a single value from a pre-determined set. Material UI for React has this component available for us and it is very easy to integrate. We can create a Date Picker in ReactJS using the following approach: Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import TextField from '@material-ui/core/TextField'; const App = () => { return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to create Date Picker in ReactJS?</h3> <TextField id="date" label="Choose your birthdate" type="date" defaultValue="2017-05-24" InputLabelProps={{ shrink: true, }} /> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 24921, "s": 24893, "text": "\n20 Jan, 2021" }, { "code": null, "e": 25168, "s": 24921, "text": "Date pickers provide a simple way to select a single value from a pre-determined set. Material UI for React has this component available for us and it is very easy to integrate. We can create a Date Picker in ReactJS using the following approach:" }, { "code": null, "e": 25218, "s": 25168, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25282, "s": 25218, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25314, "s": 25282, "text": "npx create-react-app foldername" }, { "code": null, "e": 25414, "s": 25314, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25428, "s": 25414, "text": "cd foldername" }, { "code": null, "e": 25537, "s": 25428, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25567, "s": 25537, "text": "npm install @material-ui/core" }, { "code": null, "e": 25619, "s": 25567, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25637, "s": 25619, "text": "Project Structure" }, { "code": null, "e": 25766, "s": 25637, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 25777, "s": 25766, "text": "Javascript" }, { "code": "import React from 'react';import TextField from '@material-ui/core/TextField'; const App = () => { return ( <div style={{ margin: 'auto', display: 'block', width: 'fit-content' }}> <h3>How to create Date Picker in ReactJS?</h3> <TextField id=\"date\" label=\"Choose your birthdate\" type=\"date\" defaultValue=\"2017-05-24\" InputLabelProps={{ shrink: true, }} /> </div> );} export default App;", "e": 26260, "s": 25777, "text": null }, { "code": null, "e": 26373, "s": 26260, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26383, "s": 26373, "text": "npm start" }, { "code": null, "e": 26482, "s": 26383, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26493, "s": 26482, "text": "JavaScript" }, { "code": null, "e": 26501, "s": 26493, "text": "ReactJS" }, { "code": null, "e": 26518, "s": 26501, "text": "Web Technologies" }, { "code": null, "e": 26616, "s": 26518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26625, "s": 26616, "text": "Comments" }, { "code": null, "e": 26638, "s": 26625, "text": "Old Comments" }, { "code": null, "e": 26699, "s": 26638, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26740, "s": 26699, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26794, "s": 26740, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26834, "s": 26794, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26896, "s": 26834, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 26939, "s": 26896, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26984, "s": 26939, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27049, "s": 26984, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27117, "s": 27049, "text": "How to pass data from one component to other component in ReactJS ?" } ]
VBA - DateAdd Function
A Function, which returns a date to which a specified time interval has been added. DateAdd(interval,number,date) Interval − A required parameter. It can take the following values. d - day of the year m - month of the year y - year of the year yyyy - year w - weekday ww - week q - quarter h - hour m - minute s - second Interval − A required parameter. It can take the following values. d - day of the year d - day of the year m - month of the year m - month of the year y - year of the year y - year of the year yyyy - year yyyy - year w - weekday w - weekday ww - week ww - week q - quarter q - quarter h - hour h - hour m - minute m - minute s - second s - second Number − A required parameter. It can take both positive and negative parameters. Number − A required parameter. It can take both positive and negative parameters. Date − A required parameter. A variant or literal representing the date to which an interval is added. Date − A required parameter. A variant or literal representing the date to which an interval is added. Private Sub Constant_demo_Click() ' Positive Interal date1 = 27-Jun-1894 msgbox("Line 1 : " &DateAdd("yyyy",1,date1)) msgbox("Line 2 : " &DateAdd("q",1,date1)) msgbox("Line 3 : " &DateAdd("m",1,date1)) msgbox("Line 4 : " &DateAdd("y",1,date1)) msgbox("Line 5 : " &DateAdd("d",1,date1)) msgbox("Line 6 : " &DateAdd("w",1,date1)) msgbox("Line 7 : " &DateAdd("ww",1,date1)) msgbox("Line 8 : " &DateAdd("h",1,"01-Jan-2013 12:00:00")) msgbox("Line 9 : " &DateAdd("n",1,"01-Jan-2013 12:00:00")) msgbox("Line 10 : "&DateAdd("s",1,"01-Jan-2013 12:00:00")) ' Negative Interval msgbox("Line 11 : " &DateAdd("yyyy",-1,date1)) msgbox("Line 12 : " &DateAdd("q",-1,date1)) msgbox("Line 13 : " &DateAdd("m",-1,date1)) msgbox("Line 14 : " &DateAdd("y",-1,date1)) msgbox("Line 15 : " &DateAdd("d",-1,date1)) msgbox("Line 16 : " &DateAdd("w",-1,date1)) msgbox("Line 17 : " &DateAdd("ww",-1,date1)) msgbox("Line 18 : " &DateAdd("h",-1,"01-Jan-2013 12:00:00")) msgbox("Line 19 : " &DateAdd("n",-1,"01-Jan-2013 12:00:00")) msgbox("Line 20 : " &DateAdd("s",-1,"01-Jan-2013 12:00:00")) End Sub When you execute the above function, it produces the following output. Line 1 : 27/06/1895 Line 2 : 27/09/1894 Line 3 : 27/07/1894 Line 4 : 28/06/1894 Line 5 : 28/06/1894 Line 6 : 28/06/1894 Line 7 : 4/07/1894 Line 8 : 1/01/2013 1:00:00 PM Line 9 : 1/01/2013 12:01:00 PM Line 10 : 1/01/2013 12:00:01 PM Line 11 : 27/06/1893 Line 12 : 27/03/1894 Line 13 : 27/05/1894 Line 14 : 26/06/1894 Line 15 : 26/06/1894 Line 16 : 26/06/1894 Line 17 : 20/06/1894 Line 18 : 1/01/2013 11:00:00 AM Line 19 : 1/01/2013 11:59:00 AM Line 20 : 1/01/2013 11:59:59 AM 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2019, "s": 1935, "text": "A Function, which returns a date to which a specified time interval has been added." }, { "code": null, "e": 2051, "s": 2019, "text": "DateAdd(interval,number,date) \n" }, { "code": null, "e": 2261, "s": 2051, "text": "Interval − A required parameter. It can take the following values.\n\nd - day of the year\nm - month of the year\ny - year of the year\nyyyy - year\nw - weekday\nww - week\nq - quarter\nh - hour\nm - minute\ns - second\n\n" }, { "code": null, "e": 2328, "s": 2261, "text": "Interval − A required parameter. It can take the following values." }, { "code": null, "e": 2348, "s": 2328, "text": "d - day of the year" }, { "code": null, "e": 2368, "s": 2348, "text": "d - day of the year" }, { "code": null, "e": 2390, "s": 2368, "text": "m - month of the year" }, { "code": null, "e": 2412, "s": 2390, "text": "m - month of the year" }, { "code": null, "e": 2433, "s": 2412, "text": "y - year of the year" }, { "code": null, "e": 2454, "s": 2433, "text": "y - year of the year" }, { "code": null, "e": 2466, "s": 2454, "text": "yyyy - year" }, { "code": null, "e": 2478, "s": 2466, "text": "yyyy - year" }, { "code": null, "e": 2490, "s": 2478, "text": "w - weekday" }, { "code": null, "e": 2502, "s": 2490, "text": "w - weekday" }, { "code": null, "e": 2512, "s": 2502, "text": "ww - week" }, { "code": null, "e": 2522, "s": 2512, "text": "ww - week" }, { "code": null, "e": 2534, "s": 2522, "text": "q - quarter" }, { "code": null, "e": 2546, "s": 2534, "text": "q - quarter" }, { "code": null, "e": 2555, "s": 2546, "text": "h - hour" }, { "code": null, "e": 2564, "s": 2555, "text": "h - hour" }, { "code": null, "e": 2575, "s": 2564, "text": "m - minute" }, { "code": null, "e": 2586, "s": 2575, "text": "m - minute" }, { "code": null, "e": 2597, "s": 2586, "text": "s - second" }, { "code": null, "e": 2608, "s": 2597, "text": "s - second" }, { "code": null, "e": 2690, "s": 2608, "text": "Number − A required parameter. It can take both positive and negative parameters." }, { "code": null, "e": 2772, "s": 2690, "text": "Number − A required parameter. It can take both positive and negative parameters." }, { "code": null, "e": 2875, "s": 2772, "text": "Date − A required parameter. A variant or literal representing the date to which an interval is added." }, { "code": null, "e": 2978, "s": 2875, "text": "Date − A required parameter. A variant or literal representing the date to which an interval is added." }, { "code": null, "e": 4122, "s": 2978, "text": "Private Sub Constant_demo_Click()\n ' Positive Interal\n date1 = 27-Jun-1894\n msgbox(\"Line 1 : \" &DateAdd(\"yyyy\",1,date1))\n msgbox(\"Line 2 : \" &DateAdd(\"q\",1,date1))\n msgbox(\"Line 3 : \" &DateAdd(\"m\",1,date1))\n msgbox(\"Line 4 : \" &DateAdd(\"y\",1,date1))\n msgbox(\"Line 5 : \" &DateAdd(\"d\",1,date1))\n msgbox(\"Line 6 : \" &DateAdd(\"w\",1,date1))\n msgbox(\"Line 7 : \" &DateAdd(\"ww\",1,date1))\n msgbox(\"Line 8 : \" &DateAdd(\"h\",1,\"01-Jan-2013 12:00:00\"))\n msgbox(\"Line 9 : \" &DateAdd(\"n\",1,\"01-Jan-2013 12:00:00\"))\n msgbox(\"Line 10 : \"&DateAdd(\"s\",1,\"01-Jan-2013 12:00:00\"))\n \n ' Negative Interval\n msgbox(\"Line 11 : \" &DateAdd(\"yyyy\",-1,date1))\n msgbox(\"Line 12 : \" &DateAdd(\"q\",-1,date1))\n msgbox(\"Line 13 : \" &DateAdd(\"m\",-1,date1))\n msgbox(\"Line 14 : \" &DateAdd(\"y\",-1,date1))\n msgbox(\"Line 15 : \" &DateAdd(\"d\",-1,date1))\n msgbox(\"Line 16 : \" &DateAdd(\"w\",-1,date1))\n msgbox(\"Line 17 : \" &DateAdd(\"ww\",-1,date1))\n msgbox(\"Line 18 : \" &DateAdd(\"h\",-1,\"01-Jan-2013 12:00:00\"))\n msgbox(\"Line 19 : \" &DateAdd(\"n\",-1,\"01-Jan-2013 12:00:00\"))\n msgbox(\"Line 20 : \" &DateAdd(\"s\",-1,\"01-Jan-2013 12:00:00\")) \nEnd Sub" }, { "code": null, "e": 4193, "s": 4122, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 4669, "s": 4193, "text": "Line 1 : 27/06/1895\nLine 2 : 27/09/1894\nLine 3 : 27/07/1894\nLine 4 : 28/06/1894\nLine 5 : 28/06/1894\nLine 6 : 28/06/1894\nLine 7 : 4/07/1894\nLine 8 : 1/01/2013 1:00:00 PM\nLine 9 : 1/01/2013 12:01:00 PM\nLine 10 : 1/01/2013 12:00:01 PM\nLine 11 : 27/06/1893\nLine 12 : 27/03/1894\nLine 13 : 27/05/1894\nLine 14 : 26/06/1894\nLine 15 : 26/06/1894\nLine 16 : 26/06/1894\nLine 17 : 20/06/1894\nLine 18 : 1/01/2013 11:00:00 AM\nLine 19 : 1/01/2013 11:59:00 AM\nLine 20 : 1/01/2013 11:59:59 AM\n" }, { "code": null, "e": 4703, "s": 4669, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 4718, "s": 4703, "text": " Pavan Lalwani" }, { "code": null, "e": 4751, "s": 4718, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 4766, "s": 4751, "text": " Arnold Higuit" }, { "code": null, "e": 4801, "s": 4766, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4819, "s": 4801, "text": " Prashant Panchal" }, { "code": null, "e": 4852, "s": 4819, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 4870, "s": 4852, "text": " Prashant Panchal" }, { "code": null, "e": 4903, "s": 4870, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4918, "s": 4903, "text": " Arnold Higuit" }, { "code": null, "e": 4954, "s": 4918, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4982, "s": 4954, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4989, "s": 4982, "text": " Print" }, { "code": null, "e": 5000, "s": 4989, "text": " Add Notes" } ]
What are associative Arrays in JavaScript?
Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys. They do not have a length property like normal array and cannot be traversed using normal for loop. Following is the code for associative arrays in JavaScript − Live Demo <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Associative array in JavaScript</h1> <div style="color: green;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to create a associative array and display it </h3> <script> let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { let arr = { Name: "Rohan", Class: 9, Age: 16 }; for (i in arr) { resEle.innerHTML += "Key = " + i + " : Value = " + arr[i] + "<br>"; } }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1266, "s": 1062, "text": "Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys. They do not have a length property like normal array and cannot be traversed using normal for loop." }, { "code": null, "e": 1327, "s": 1266, "text": "Following is the code for associative arrays in JavaScript −" }, { "code": null, "e": 1338, "s": 1327, "text": " Live Demo" }, { "code": null, "e": 2216, "s": 1338, "text": "<!DOCTYPE html>\n<html lang=\"en\" >\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Associative array in JavaScript</h1>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to create a associative array and display it\n</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n let arr = { Name: \"Rohan\", Class: 9, Age: 16 };\n for (i in arr) {\n resEle.innerHTML += \"Key = \" + i + \" : Value = \" + arr[i] + \"<br>\";\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2267, "s": 2216, "text": "The above code will produce the following output −" }, { "code": null, "e": 2305, "s": 2267, "text": "On clicking the ‘CLICK HERE’ button −" } ]
JSF - Edit Data of a DataTable
In this section, we'll showcase the adding editing capability to a row in a dataTable. Let us create a test JSF application to test the above functionality. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> <h:outputStylesheet library = "css" name = "styles.css" /> </h:head> <h:body> <h2>DataTable Example</h2> <h:form> <h:dataTable value = "#{userData.employees}" var = "employee" styleClass = "employeeTable" headerClass = "employeeTableHeader" rowClasses = "employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name = "header">Name</f:facet> <h:inputText value = "#{employee.name}" size = "10" rendered = "#{employee.canEdit}" /> <h:outputText value = "#{employee.name}" rendered = "#{not employee.canEdit}" /> </h:column> <h:column> <f:facet name = "header">Department</f:facet> <h:inputText value = "#{employee.department}" size = "20" rendered = "#{employee.canEdit}" /> <h:outputText value = "#{employee.department}" rendered = "#{not employee.canEdit}" /> </h:column> <h:column> <f:facet name = "header">Age</f:facet> <h:inputText value = "#{employee.age}" size = "5" rendered = "#{employee.canEdit}" /> <h:outputText value = "#{employee.age}" rendered = "#{not employee.canEdit}" /> </h:column> <h:column> <f:facet name = "header">Salary</f:facet> <h:inputText value = "#{employee.salary}" size = "5" rendered = "#{employee.canEdit}" /> <h:outputText value = "#{employee.salary}" rendered = "#{not employee.canEdit}" /> </h:column> <h:column> <f:facet name = "header">Edit</f:facet> <h:commandButton value = "Edit" action = "#{userData.editEmployee}" rendered = "#{not employee.canEdit}"> <f:setPropertyActionListener target = "#{userData.employee}" value = "#{employee}" /> </h:commandButton> </h:column> </h:dataTable> <br/> <h:commandButton value = "Save Employees" action = "#{userData.saveEmployees}" /> </h:form> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. Click the edit button of any row. Following will be the output. Click Save Employees button to save the edit. Following will be the output. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2039, "s": 1952, "text": "In this section, we'll showcase the adding editing capability to a row in a dataTable." }, { "code": null, "e": 2109, "s": 2039, "text": "Let us create a test JSF application to test the above functionality." }, { "code": null, "e": 4918, "s": 2109, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \nxmlns:h = \"http://java.sun.com/jsf/html\"\nxmlns:f = \"http://java.sun.com/jsf/core\">\n \n <h:head>\n <title>JSF tutorial</title>\t\t\n <h:outputStylesheet library = \"css\" name = \"styles.css\" /> \t\n </h:head>\n \n <h:body> \n <h2>DataTable Example</h2>\n \n <h:form>\n <h:dataTable value = \"#{userData.employees}\" var = \"employee\"\n styleClass = \"employeeTable\"\n headerClass = \"employeeTableHeader\"\n rowClasses = \"employeeTableOddRow,employeeTableEvenRow\">\n \n <h:column> \t\t\t\t\n <f:facet name = \"header\">Name</f:facet> \t\t\t\t\n <h:inputText value = \"#{employee.name}\"\n size = \"10\" rendered = \"#{employee.canEdit}\" />\n <h:outputText value = \"#{employee.name}\"\n rendered = \"#{not employee.canEdit}\" />\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Department</f:facet>\n <h:inputText value = \"#{employee.department}\" \n size = \"20\" rendered = \"#{employee.canEdit}\" />\n <h:outputText value = \"#{employee.department}\" \n rendered = \"#{not employee.canEdit}\" />\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Age</f:facet>\n <h:inputText value = \"#{employee.age}\" size = \"5\"\n rendered = \"#{employee.canEdit}\" />\n <h:outputText value = \"#{employee.age}\" \n rendered = \"#{not employee.canEdit}\" />\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Salary</f:facet>\n <h:inputText value = \"#{employee.salary}\" \n size = \"5\" rendered = \"#{employee.canEdit}\" />\n <h:outputText value = \"#{employee.salary}\" \n rendered = \"#{not employee.canEdit}\" />\n </h:column>\n \n <h:column>\n <f:facet name = \"header\">Edit</f:facet>\n <h:commandButton value = \"Edit\" \n action = \"#{userData.editEmployee}\" \n rendered = \"#{not employee.canEdit}\"> \n <f:setPropertyActionListener \n target = \"#{userData.employee}\" value = \"#{employee}\" />\n </h:commandButton>\n </h:column>\n </h:dataTable> \n <br/>\n \n <h:commandButton value = \"Save Employees\"\n action = \"#{userData.saveEmployees}\" />\t \n </h:form>\n \n </h:body>\n</html>" }, { "code": null, "e": 5134, "s": 4918, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 5198, "s": 5134, "text": "Click the edit button of any row. Following will be the output." }, { "code": null, "e": 5274, "s": 5198, "text": "Click Save Employees button to save the edit. Following will be the output." }, { "code": null, "e": 5309, "s": 5274, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5324, "s": 5309, "text": " Chaand Sheikh" }, { "code": null, "e": 5331, "s": 5324, "text": " Print" }, { "code": null, "e": 5342, "s": 5331, "text": " Add Notes" } ]
How to make a redirect in PHP? - GeeksforGeeks
11 Oct, 2021 Redirection from one page to another in PHP is commonly achieved using the following two ways:Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client. Syntax: header( $header, $replace, $http_response_code ) Parameters: This function accepts three parameters as mentioned above and described below: $header: This parameter is used to hold the header string. $replace: This parameter is used to hold the replace parameter which indicates the header should replace a previous similar header, or add a second header of the same type. It is optional parameter. $http_response_code: This parameter hold the HTTP response code. Below program illustrates the header() function in PHP:Program: php <?php // Redirect browserheader("Location: https://www.geeksforgeeks.org"); exit;?> Note: The die() or exit() function after header is mandatory. If die() or exit() is not put after after the header(‘Location: ....’) then script may continue resulting in unexpected behavior. For example, result in content being disclosed that actually wanted to prevent with the redirect (HTTP 301). Using JavaScript via PHP: The windows.location object in JavaScript is used to get the current page address(URL) and to redirect the browser to a new page. The window.location object contains the crucial information about a page such as hostname, href, pathname, port etc.Example: html <html> <head> <title>window.location function</title> </head> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "URL: " + window.location.href +"</br>"; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Hostname: " + window.location.hostname + "</br>"; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Protocol: " + window.location.protocol + "</br>"; </script> </body></html> Output: URL: https://ide.geeksforgeeks.org/tryit.php Hostname: ide.geeksforgeeks.org Protocol: https: 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. kashishsoda Picked Technical Scripter 2018 PHP PHP Programs Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to run JavaScript from PHP? PHP | Converting string to Date and DateTime How to fetch data from localserver database and display on HTML table using PHP ? How to display logged in user information in PHP ? How to run JavaScript from PHP? How to encrypt and decrypt passwords using PHP ? How to pass a PHP array to a JavaScript function? How to fetch data from localserver database and display on HTML table using PHP ? How to declare a global variable in PHP?
[ { "code": null, "e": 24345, "s": 24317, "text": "\n11 Oct, 2021" }, { "code": null, "e": 24618, "s": 24345, "text": "Redirection from one page to another in PHP is commonly achieved using the following two ways:Using Header Function in PHP: The header() function is an inbuilt function in PHP which is used to send the raw HTTP (Hyper Text Transfer Protocol) header to the client. Syntax: " }, { "code": null, "e": 24667, "s": 24618, "text": "header( $header, $replace, $http_response_code )" }, { "code": null, "e": 24760, "s": 24667, "text": "Parameters: This function accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 24819, "s": 24760, "text": "$header: This parameter is used to hold the header string." }, { "code": null, "e": 25018, "s": 24819, "text": "$replace: This parameter is used to hold the replace parameter which indicates the header should replace a previous similar header, or add a second header of the same type. It is optional parameter." }, { "code": null, "e": 25083, "s": 25018, "text": "$http_response_code: This parameter hold the HTTP response code." }, { "code": null, "e": 25148, "s": 25083, "text": "Below program illustrates the header() function in PHP:Program: " }, { "code": null, "e": 25152, "s": 25148, "text": "php" }, { "code": "<?php // Redirect browserheader(\"Location: https://www.geeksforgeeks.org\"); exit;?>", "e": 25236, "s": 25152, "text": null }, { "code": null, "e": 25819, "s": 25236, "text": "Note: The die() or exit() function after header is mandatory. If die() or exit() is not put after after the header(‘Location: ....’) then script may continue resulting in unexpected behavior. For example, result in content being disclosed that actually wanted to prevent with the redirect (HTTP 301). Using JavaScript via PHP: The windows.location object in JavaScript is used to get the current page address(URL) and to redirect the browser to a new page. The window.location object contains the crucial information about a page such as hostname, href, pathname, port etc.Example: " }, { "code": null, "e": 25824, "s": 25819, "text": "html" }, { "code": "<html> <head> <title>window.location function</title> </head> <body> <p id=\"demo\"></p> <script> document.getElementById(\"demo\").innerHTML = \"URL: \" + window.location.href +\"</br>\"; document.getElementById(\"demo\").innerHTML = document.getElementById(\"demo\").innerHTML + \"Hostname: \" + window.location.hostname + \"</br>\"; document.getElementById(\"demo\").innerHTML = document.getElementById(\"demo\").innerHTML + \"Protocol: \" + window.location.protocol + \"</br>\"; </script> </body></html> ", "e": 26416, "s": 25824, "text": null }, { "code": null, "e": 26425, "s": 26416, "text": "Output: " }, { "code": null, "e": 26519, "s": 26425, "text": "URL: https://ide.geeksforgeeks.org/tryit.php\nHostname: ide.geeksforgeeks.org\nProtocol: https:" }, { "code": null, "e": 26688, "s": 26519, "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": 26700, "s": 26688, "text": "kashishsoda" }, { "code": null, "e": 26707, "s": 26700, "text": "Picked" }, { "code": null, "e": 26731, "s": 26707, "text": "Technical Scripter 2018" }, { "code": null, "e": 26735, "s": 26731, "text": "PHP" }, { "code": null, "e": 26748, "s": 26735, "text": "PHP Programs" }, { "code": null, "e": 26767, "s": 26748, "text": "Technical Scripter" }, { "code": null, "e": 26771, "s": 26767, "text": "PHP" }, { "code": null, "e": 26869, "s": 26771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26878, "s": 26869, "text": "Comments" }, { "code": null, "e": 26891, "s": 26878, "text": "Old Comments" }, { "code": null, "e": 26941, "s": 26891, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26973, "s": 26941, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 27018, "s": 26973, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27100, "s": 27018, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27151, "s": 27100, "text": "How to display logged in user information in PHP ?" }, { "code": null, "e": 27183, "s": 27151, "text": "How to run JavaScript from PHP?" }, { "code": null, "e": 27232, "s": 27183, "text": "How to encrypt and decrypt passwords using PHP ?" }, { "code": null, "e": 27282, "s": 27232, "text": "How to pass a PHP array to a JavaScript function?" }, { "code": null, "e": 27364, "s": 27282, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" } ]
Constructor Overloading In Java programming
Similar to method overloading, constructor loading is the creation and usage of constructors with diffrent type of arguments. We can use this operator to refer to constructors.See the example below. Live Demo class A { public int a; public A() { this(-1); } public A(int a) { this.a = a; } public String toString() { return "[ a= " + this.a + "]"; } } public class Tester { public static void main(String args[]) { A a = new A(10); System.out.println(a); A a1 = new A(); System.out.println(a1); } } [ a= 10] [ a= -1]
[ { "code": null, "e": 1261, "s": 1062, "text": "Similar to method overloading, constructor loading is the creation and usage of constructors with diffrent type of arguments. We can use this operator to refer to constructors.See the example below." }, { "code": null, "e": 1272, "s": 1261, "text": " Live Demo" }, { "code": null, "e": 1628, "s": 1272, "text": "class A {\n public int a;\n public A() {\n this(-1);\n }\n public A(int a) {\n this.a = a;\n }\n public String toString() {\n return \"[ a= \" + this.a + \"]\";\n }\n}\npublic class Tester {\n public static void main(String args[]) {\n A a = new A(10);\n System.out.println(a);\n A a1 = new A();\n System.out.println(a1);\n }\n}" }, { "code": null, "e": 1646, "s": 1628, "text": "[ a= 10]\n[ a= -1]" } ]
How to create a subset based on levels of a character column in R?
In R programming, mostly the columns with string values can be either represented by character data type or factor data type. For example, if we have a column Group with four unique values as A, B, C, and D then it can be of character or factor with four levels. If we want to take the subset of these columns then subset function can be used. Check out the example below. Consider the below data frame − set.seed(888) Grp<-sample(c("A","B","C"),20,replace=TRUE)Age<-sample(21:50,20) df1<-data.frame(Grp,Age) df1 Grp Age 1 A 35 2 C 40 3 C 48 4 C 46 5 C 36 6 C 33 7 B 47 8 A 45 9 B 43 10 B 37 11 B 30 12 A 24 13 C 39 14 C 50 15 C 25 16 A 34 17 B 49 18 A 44 19 C 38 20 B 26 str(df1) 'data.frame': 20 obs. of 2 variables: $ Grp: chr "A" "C" "C" "C" ... $ Age: int 35 40 48 46 36 33 47 45 43 37 ... Taking subset of df1 based on Grp column values A and C − subset(df1, Grp %in% c("A","C")) Grp Age 1 A 35 2 C 40 3 C 48 4 C 46 5 C 36 6 C 33 8 A 45 12 A 24 13 C 39 14 C 50 15 C 25 16 A 34 18 A 44 19 C 38 Let’s have a look at another example − Live Demo Class<-sample(c("First","Second","Third","Fourth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) df2 Class Score 1 First 10 2 First 3 3 First 1 4 First 7 5 First 1 6 Third 4 7 First 3 8 First 3 9 Second 2 10 First 8 11 Fourth 1 12 Third 6 13 First 6 14 Second 1 15 First 8 16 Fourth 4 17 Third 7 18 Fourth 4 19 Third 7 20 Fourth 1 str(df2) 'data.frame': 20 obs. of 2 variables: $ Class: chr "First" "Third" "Second" "First" ... $ Score: int 1 4 9 8 9 10 2 8 5 8 ... Taking subset of df2 based on Class column values First and Fourth − subset(df2, Class %in% c("First","Fourth")) Class Score 1 First 1 4 First 8 5 First 9 6 Fourth 10 7 Fourth 2 9 Fourth 5 10 Fourth 8 11 Fourth 8 13 Fourth 7 14 Fourth 10 15 First 7 16 Fourth 10 17 Fourth 4 19 First 2 20 First 10
[ { "code": null, "e": 1435, "s": 1062, "text": "In R programming, mostly the columns with string values can be either represented by character data type or factor data type. For example, if we have a column Group with four unique values as A, B, C, and D then it can be of character or factor with four levels. If we want to take the subset of these columns then subset function can be used. Check out the example below." }, { "code": null, "e": 1467, "s": 1435, "text": "Consider the below data frame −" }, { "code": null, "e": 1575, "s": 1467, "text": "set.seed(888)\nGrp<-sample(c(\"A\",\"B\",\"C\"),20,replace=TRUE)Age<-sample(21:50,20)\ndf1<-data.frame(Grp,Age)\ndf1" }, { "code": null, "e": 1807, "s": 1575, "text": " Grp Age\n1 A 35\n2 C 40\n3 C 48\n4 C 46\n5 C 36\n6 C 33\n7 B 47\n8 A 45\n9 B 43\n10 B 37\n11 B 30\n12 A 24\n13 C 39\n14 C 50\n15 C 25\n16 A 34\n17 B 49\n18 A 44\n19 C 38\n20 B 26" }, { "code": null, "e": 1854, "s": 1807, "text": "str(df1) 'data.frame': 20 obs. of 2 variables:" }, { "code": null, "e": 1930, "s": 1854, "text": "$ Grp: chr \"A\" \"C\" \"C\" \"C\" ...\n$ Age: int 35 40 48 46 36 33 47 45 43 37 ..." }, { "code": null, "e": 1988, "s": 1930, "text": "Taking subset of df1 based on Grp column values A and C −" }, { "code": null, "e": 2021, "s": 1988, "text": "subset(df1, Grp %in% c(\"A\",\"C\"))" }, { "code": null, "e": 2134, "s": 2021, "text": "Grp Age\n1 A 35\n2 C 40\n3 C 48\n4 C 46\n5 C 36\n6 C 33\n8 A 45\n12 A 24\n13 C 39\n14 C 50\n15 C 25\n16 A 34\n18 A 44\n19 C 38" }, { "code": null, "e": 2173, "s": 2134, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2184, "s": 2173, "text": " Live Demo" }, { "code": null, "e": 2321, "s": 2184, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\ndf2" }, { "code": null, "e": 2598, "s": 2321, "text": " Class Score\n1 First 10\n2 First 3\n3 First 1\n4 First 7\n5 First 1\n6 Third 4\n7 First 3\n8 First 3\n9 Second 2\n10 First 8\n11 Fourth 1\n12 Third 6\n13 First 6\n14 Second 1\n15 First 8\n16 Fourth 4\n17 Third 7\n18 Fourth 4\n19 Third 7\n20 Fourth 1" }, { "code": null, "e": 2645, "s": 2598, "text": "str(df2) 'data.frame': 20 obs. of 2 variables:" }, { "code": null, "e": 2733, "s": 2645, "text": "$ Class: chr \"First\" \"Third\" \"Second\" \"First\" ...\n$ Score: int 1 4 9 8 9 10 2 8 5 8 ..." }, { "code": null, "e": 2802, "s": 2733, "text": "Taking subset of df2 based on Class column values First and Fourth −" }, { "code": null, "e": 2846, "s": 2802, "text": "subset(df2, Class %in% c(\"First\",\"Fourth\"))" }, { "code": null, "e": 3030, "s": 2846, "text": "Class Score\n1 First 1\n4 First 8\n5 First 9\n6 Fourth 10\n7 Fourth 2\n9 Fourth 5\n10 Fourth 8\n11 Fourth 8\n13 Fourth 7\n14 Fourth 10\n15 First 7\n16 Fourth 10\n17 Fourth 4\n19 First 2\n20 First 10" } ]
Find all matrix elements which are minimum in their row and maximum in their column - GeeksforGeeks
08 Jun, 2021 Given a matrix mat[][] of size M * N, the task is to find all matrix elements which are minimum in their respective row and maximum in their respective column. If no such element is present, print -1. Examples: Input: mat[][] = {{1, 10, 4}, {9, 3, 8}, {15, 16, 17}}Output: 15Explanation:15 is the only element which is maximum in its column {1, 3, 15} and minimum in its row {15, 16, 17}. Input: m[][] = {{10, 41}, {3, 5}, {16, 2}}Output: -1 Approach: Follow the steps below to solve the problem: Create an unordered_set and store the minimum element of each row of the matrix.Traverse the matrix and find the maximum element of each column. For every column, check if the maximum obtained is already present in the unordered_set or not.If found to be true, print that number. If no such matrix element is found, print -1. Create an unordered_set and store the minimum element of each row of the matrix. Traverse the matrix and find the maximum element of each column. For every column, check if the maximum obtained is already present in the unordered_set or not. If found to be true, print that number. If no such matrix element is found, print -1. 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; // Functionto find all the matrix elements// which are minimum in its row and maximum// in its columnvector<int> minmaxNumbers(vector<vector<int> >& matrix, vector<int>& res){ // Initialize unordered set unordered_set<int> set; // Traverse the matrix for (int i = 0; i < matrix.size(); i++) { int minr = INT_MAX; for (int j = 0; j < matrix[i].size(); j++) { // Update the minimum // element of current row minr = min(minr, matrix[i][j]); } // Insert the minimum // element of the row set.insert(minr); } for (int j = 0; j < matrix[0].size(); j++) { int maxc = INT_MIN; for (int i = 0; i < matrix.size(); i++) { // Update the maximum // element of current column maxc = max(maxc, matrix[i][j]); } // Checking if it is already present // in the unordered_set or not if (set.find(maxc) != set.end()) { res.push_back(maxc); } } return res;} // Driver Codeint main(){ vector<vector<int> > mat = { { 1, 10, 4 }, { 9, 3, 8 }, { 15, 16, 17 } }; vector<int> ans; // Function call minmaxNumbers(mat, ans); // If no such matrix // element is found if (ans.size() == 0) cout << "-1" << endl; for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl; return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Functionto find all the matrix elements// which are minimum in its row and maximum// in its columnpublic static Vector<Integer>minmaxNumbers(int[][] matrix, Vector<Integer> res) { // Initialize unordered set Set<Integer> set = new HashSet<Integer>(); // Traverse the matrix for(int i = 0; i < matrix.length; i++) { int minr = Integer.MAX_VALUE; for(int j = 0; j < matrix[i].length; j++) { // Update the minimum // element of current row minr = Math.min(minr, matrix[i][j]); } // Insert the minimum // element of the row set.add(minr); } for(int j = 0; j < matrix[0].length; j++) { int maxc = Integer.MIN_VALUE; for(int i = 0; i < matrix.length; i++) { // Update the maximum // element of current column maxc = Math.max(maxc, matrix[i][j]); } // Checking if it is already present // in the unordered_set or not if (set.contains(maxc)) { res.add(maxc); } } return res;} // Driver codepublic static void main(String[] args){ int[][] mat = { { 1, 10, 4 }, { 9, 3, 8 }, { 15, 16, 17 } }; Vector<Integer> ans = new Vector<Integer>(); // Function call ans = minmaxNumbers(mat, ans); // If no such matrix // element is found if (ans.size() == 0) System.out.println("-1"); for(int i = 0; i < ans.size(); i++) System.out.println(ans.get(i));}} // This code is contributed by divyeshrabadiya07 # Python3 program for the above approachimport sys # Functionto find all the matrix elements# which are minimum in its row and maximum# in its columndef minmaxNumbers(matrix, res): # Initialize unordered set s = set() # Traverse the matrix for i in range(0, len(matrix), 1): minr = sys.maxsize for j in range(0, len(matrix[i]), 1): # Update the minimum # element of current row minr = min(minr, matrix[i][j]) # Insert the minimum # element of the row s.add(minr) for j in range(0, len(matrix[0]), 1): maxc = -sys.maxsize - 1 for i in range(0, len(matrix), 1): # Update the maximum # element of current column maxc = max(maxc, matrix[i][j]) # Checking if it is already present # in the unordered_set or not if (maxc in s): res.append(maxc) return res # Driver Codeif __name__ == '__main__': mat = [ [ 1, 10, 4 ], [ 9, 3, 8 ], [ 15, 16, 17 ] ] ans = [] # Function call minmaxNumbers(mat, ans) # If no such matrix # element is found if (len(ans) == 0): print("-1") for i in range(len(ans)): print(ans[i]) # This code is contributed by SURENDRA_GANGWAR // C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Functionto find all// the matrix elements// which are minimum// in its row and// maximum in its columnpublic static List<int> minmaxNumbers(int[,] matrix, List<int> res) { // Initialize unordered set HashSet<int> set = new HashSet<int>(); // Traverse the matrix for(int i = 0; i < matrix.GetLength(0); i++) { int minr = int.MaxValue; for(int j = 0; j < matrix.GetLength(1); j++) { // Update the minimum // element of current row minr = Math.Min(minr, matrix[i, j]); } // Insert the minimum // element of the row set.Add(minr); } for(int j = 0; j < matrix.GetLength(0); j++) { int maxc = int.MinValue; for(int i = 0; i < matrix.GetLength(1); i++) { // Update the maximum // element of current column maxc = Math.Max(maxc, matrix[i, j]); } // Checking if it is already present // in the unordered_set or not if (set.Contains(maxc)) { res.Add(maxc); } } return res;} // Driver codepublic static void Main(String[] args){ int[,] mat = {{1, 10, 4}, {9, 3, 8}, {15, 16, 17}}; List<int> ans = new List<int>(); // Function call ans = minmaxNumbers(mat, ans); // If no such matrix // element is found if (ans.Count == 0) Console.WriteLine("-1"); for(int i = 0; i < ans.Count; i++) Console.WriteLine(ans[i]);}} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Functionto find all the matrix elements// which are minimum in its row and maximum// in its columnfunction minmaxNumbers(matrix, res){ // Initialize unordered set var set = new Set(); // Traverse the matrix for (var i = 0; i < matrix.length; i++) { var minr = 1000000000; for (var j = 0; j < matrix[i].length; j++) { // Update the minimum // element of current row minr = Math.min(minr, matrix[i][j]); } // Insert the minimum // element of the row set.add(minr); } for (var j = 0; j < matrix[0].length; j++) { var maxc = -1000000000; for (var i = 0; i < matrix.length; i++) { // Update the maximum // element of current column maxc = Math.max(maxc, matrix[i][j]); } // Checking if it is already present // in the unordered_set or not if (set.has(maxc)) { res.push(maxc); } } return res;} // Driver Codevar mat = [ [ 1, 10, 4 ], [ 9, 3, 8 ], [ 15, 16, 17 ] ];var ans = []; // Function callminmaxNumbers(mat, ans); // If no such matrix// element is foundif (ans.length == 0) document.write( "-1");for (var i = 0; i < ans.length; i++) document.write( ans[i] + "<br>"); // This code is contributed by rrrtnx.</script> 15 Time Complexity: O(M * N) Auxiliary Space: O(M + N) divyeshrabadiya07 29AjayKumar SURENDRA_GANGWAR rrrtnx array-traversal-question cpp-unordered_set Hash Matrix Searching Searching Hash Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most frequent element in an array Counting frequencies of array elements Sorting a Map by value in C++ STL Double Hashing C++ program for hashing with chaining Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
[ { "code": null, "e": 25638, "s": 25610, "text": "\n08 Jun, 2021" }, { "code": null, "e": 25839, "s": 25638, "text": "Given a matrix mat[][] of size M * N, the task is to find all matrix elements which are minimum in their respective row and maximum in their respective column. If no such element is present, print -1." }, { "code": null, "e": 25849, "s": 25839, "text": "Examples:" }, { "code": null, "e": 26027, "s": 25849, "text": "Input: mat[][] = {{1, 10, 4}, {9, 3, 8}, {15, 16, 17}}Output: 15Explanation:15 is the only element which is maximum in its column {1, 3, 15} and minimum in its row {15, 16, 17}." }, { "code": null, "e": 26080, "s": 26027, "text": "Input: m[][] = {{10, 41}, {3, 5}, {16, 2}}Output: -1" }, { "code": null, "e": 26135, "s": 26080, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 26461, "s": 26135, "text": "Create an unordered_set and store the minimum element of each row of the matrix.Traverse the matrix and find the maximum element of each column. For every column, check if the maximum obtained is already present in the unordered_set or not.If found to be true, print that number. If no such matrix element is found, print -1." }, { "code": null, "e": 26542, "s": 26461, "text": "Create an unordered_set and store the minimum element of each row of the matrix." }, { "code": null, "e": 26703, "s": 26542, "text": "Traverse the matrix and find the maximum element of each column. For every column, check if the maximum obtained is already present in the unordered_set or not." }, { "code": null, "e": 26789, "s": 26703, "text": "If found to be true, print that number. If no such matrix element is found, print -1." }, { "code": null, "e": 26840, "s": 26789, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26844, "s": 26840, "text": "C++" }, { "code": null, "e": 26849, "s": 26844, "text": "Java" }, { "code": null, "e": 26857, "s": 26849, "text": "Python3" }, { "code": null, "e": 26860, "s": 26857, "text": "C#" }, { "code": null, "e": 26871, "s": 26860, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Functionto find all the matrix elements// which are minimum in its row and maximum// in its columnvector<int> minmaxNumbers(vector<vector<int> >& matrix, vector<int>& res){ // Initialize unordered set unordered_set<int> set; // Traverse the matrix for (int i = 0; i < matrix.size(); i++) { int minr = INT_MAX; for (int j = 0; j < matrix[i].size(); j++) { // Update the minimum // element of current row minr = min(minr, matrix[i][j]); } // Insert the minimum // element of the row set.insert(minr); } for (int j = 0; j < matrix[0].size(); j++) { int maxc = INT_MIN; for (int i = 0; i < matrix.size(); i++) { // Update the maximum // element of current column maxc = max(maxc, matrix[i][j]); } // Checking if it is already present // in the unordered_set or not if (set.find(maxc) != set.end()) { res.push_back(maxc); } } return res;} // Driver Codeint main(){ vector<vector<int> > mat = { { 1, 10, 4 }, { 9, 3, 8 }, { 15, 16, 17 } }; vector<int> ans; // Function call minmaxNumbers(mat, ans); // If no such matrix // element is found if (ans.size() == 0) cout << \"-1\" << endl; for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl; return 0;}", "e": 28406, "s": 26871, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Functionto find all the matrix elements// which are minimum in its row and maximum// in its columnpublic static Vector<Integer>minmaxNumbers(int[][] matrix, Vector<Integer> res) { // Initialize unordered set Set<Integer> set = new HashSet<Integer>(); // Traverse the matrix for(int i = 0; i < matrix.length; i++) { int minr = Integer.MAX_VALUE; for(int j = 0; j < matrix[i].length; j++) { // Update the minimum // element of current row minr = Math.min(minr, matrix[i][j]); } // Insert the minimum // element of the row set.add(minr); } for(int j = 0; j < matrix[0].length; j++) { int maxc = Integer.MIN_VALUE; for(int i = 0; i < matrix.length; i++) { // Update the maximum // element of current column maxc = Math.max(maxc, matrix[i][j]); } // Checking if it is already present // in the unordered_set or not if (set.contains(maxc)) { res.add(maxc); } } return res;} // Driver codepublic static void main(String[] args){ int[][] mat = { { 1, 10, 4 }, { 9, 3, 8 }, { 15, 16, 17 } }; Vector<Integer> ans = new Vector<Integer>(); // Function call ans = minmaxNumbers(mat, ans); // If no such matrix // element is found if (ans.size() == 0) System.out.println(\"-1\"); for(int i = 0; i < ans.size(); i++) System.out.println(ans.get(i));}} // This code is contributed by divyeshrabadiya07", "e": 30135, "s": 28406, "text": null }, { "code": "# Python3 program for the above approachimport sys # Functionto find all the matrix elements# which are minimum in its row and maximum# in its columndef minmaxNumbers(matrix, res): # Initialize unordered set s = set() # Traverse the matrix for i in range(0, len(matrix), 1): minr = sys.maxsize for j in range(0, len(matrix[i]), 1): # Update the minimum # element of current row minr = min(minr, matrix[i][j]) # Insert the minimum # element of the row s.add(minr) for j in range(0, len(matrix[0]), 1): maxc = -sys.maxsize - 1 for i in range(0, len(matrix), 1): # Update the maximum # element of current column maxc = max(maxc, matrix[i][j]) # Checking if it is already present # in the unordered_set or not if (maxc in s): res.append(maxc) return res # Driver Codeif __name__ == '__main__': mat = [ [ 1, 10, 4 ], [ 9, 3, 8 ], [ 15, 16, 17 ] ] ans = [] # Function call minmaxNumbers(mat, ans) # If no such matrix # element is found if (len(ans) == 0): print(\"-1\") for i in range(len(ans)): print(ans[i]) # This code is contributed by SURENDRA_GANGWAR", "e": 31463, "s": 30135, "text": null }, { "code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Functionto find all// the matrix elements// which are minimum// in its row and// maximum in its columnpublic static List<int> minmaxNumbers(int[,] matrix, List<int> res) { // Initialize unordered set HashSet<int> set = new HashSet<int>(); // Traverse the matrix for(int i = 0; i < matrix.GetLength(0); i++) { int minr = int.MaxValue; for(int j = 0; j < matrix.GetLength(1); j++) { // Update the minimum // element of current row minr = Math.Min(minr, matrix[i, j]); } // Insert the minimum // element of the row set.Add(minr); } for(int j = 0; j < matrix.GetLength(0); j++) { int maxc = int.MinValue; for(int i = 0; i < matrix.GetLength(1); i++) { // Update the maximum // element of current column maxc = Math.Max(maxc, matrix[i, j]); } // Checking if it is already present // in the unordered_set or not if (set.Contains(maxc)) { res.Add(maxc); } } return res;} // Driver codepublic static void Main(String[] args){ int[,] mat = {{1, 10, 4}, {9, 3, 8}, {15, 16, 17}}; List<int> ans = new List<int>(); // Function call ans = minmaxNumbers(mat, ans); // If no such matrix // element is found if (ans.Count == 0) Console.WriteLine(\"-1\"); for(int i = 0; i < ans.Count; i++) Console.WriteLine(ans[i]);}} // This code is contributed by 29AjayKumar", "e": 33005, "s": 31463, "text": null }, { "code": "<script> // Javascript program for the above approach // Functionto find all the matrix elements// which are minimum in its row and maximum// in its columnfunction minmaxNumbers(matrix, res){ // Initialize unordered set var set = new Set(); // Traverse the matrix for (var i = 0; i < matrix.length; i++) { var minr = 1000000000; for (var j = 0; j < matrix[i].length; j++) { // Update the minimum // element of current row minr = Math.min(minr, matrix[i][j]); } // Insert the minimum // element of the row set.add(minr); } for (var j = 0; j < matrix[0].length; j++) { var maxc = -1000000000; for (var i = 0; i < matrix.length; i++) { // Update the maximum // element of current column maxc = Math.max(maxc, matrix[i][j]); } // Checking if it is already present // in the unordered_set or not if (set.has(maxc)) { res.push(maxc); } } return res;} // Driver Codevar mat = [ [ 1, 10, 4 ], [ 9, 3, 8 ], [ 15, 16, 17 ] ];var ans = []; // Function callminmaxNumbers(mat, ans); // If no such matrix// element is foundif (ans.length == 0) document.write( \"-1\");for (var i = 0; i < ans.length; i++) document.write( ans[i] + \"<br>\"); // This code is contributed by rrrtnx.</script>", "e": 34400, "s": 33005, "text": null }, { "code": null, "e": 34403, "s": 34400, "text": "15" }, { "code": null, "e": 34457, "s": 34405, "text": "Time Complexity: O(M * N) Auxiliary Space: O(M + N)" }, { "code": null, "e": 34475, "s": 34457, "text": "divyeshrabadiya07" }, { "code": null, "e": 34487, "s": 34475, "text": "29AjayKumar" }, { "code": null, "e": 34504, "s": 34487, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34511, "s": 34504, "text": "rrrtnx" }, { "code": null, "e": 34536, "s": 34511, "text": "array-traversal-question" }, { "code": null, "e": 34554, "s": 34536, "text": "cpp-unordered_set" }, { "code": null, "e": 34559, "s": 34554, "text": "Hash" }, { "code": null, "e": 34566, "s": 34559, "text": "Matrix" }, { "code": null, "e": 34576, "s": 34566, "text": "Searching" }, { "code": null, "e": 34586, "s": 34576, "text": "Searching" }, { "code": null, "e": 34591, "s": 34586, "text": "Hash" }, { "code": null, "e": 34598, "s": 34591, "text": "Matrix" }, { "code": null, "e": 34696, "s": 34598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34730, "s": 34696, "text": "Most frequent element in an array" }, { "code": null, "e": 34769, "s": 34730, "text": "Counting frequencies of array elements" }, { "code": null, "e": 34803, "s": 34769, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 34818, "s": 34803, "text": "Double Hashing" }, { "code": null, "e": 34856, "s": 34818, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 34891, "s": 34856, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 34935, "s": 34891, "text": "Program to find largest element in an array" }, { "code": null, "e": 34971, "s": 34935, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 35002, "s": 34971, "text": "Rat in a Maze | Backtracking-2" } ]
This Python Library Automates Pandas and Helps You Replace Excel | by Frank Andrade | Towards Data Science
Pandas is the best tool to do data analysis in Python and it has many advantages over tools like Microsoft Excel, but the transition between Excel to Python is challenging for those with little coding experience or that are new to Pandas. Fortunately, that’s no longer the case. A few weeks ago I came across a Python library that helps us work with Pandas as if we were using Excel. In this article, I will show you how to do things like creating pivot tables, joining tables, filtering data, and more using a Python library that allows us to work with a Pandas dataframe using an interface similar to Excel and automatically generates Pandas code for us. Moving from Excel to Python has never been easier! In this guide, the data we’ll use is a “StudentsPerformance” CSV file available on Google Drive, which I generated myself. This is random data that contains marks obtained by students in different subjects and, with the help of Mito, we will easily move from Excel spreadsheets to Python’s dataframes. Make sure that the CSV file and your Python script are located in the same directory. To easily create pivot tables, visualizations, and perform operations you would do in Excel or Pandas, we only need to install the mitosheet library (make sure you have Python 3.6 or above and also JupyterLab) To install mitosheet, first, open a new terminal or command prompt and then run the following command (if possible, install it in a new virtual environment): python -m pip install mitoinstallerpython -m mitoinstaller install That’s everything we need to start working with Mito! For more details about the installation, check the official documentation. To create a dataframe using Python we would need to import pandas and use the .read_csv() method, but with Mito, we only need to import mitosheet and initiate it by typing mitosheet.sheet(). import mitosheetmitosheet.sheet() The code above will create a mitosheet. If the sheet does not render when you call mitosheet.sheet(), relaunch JupyterLab. After this, we can import a dataset by clicking on the + button in the bottom left corner. Then, select the StudentsPerformance.csv file as shown below. Once the CSV is imported, a dataframe is created using the same file name. In addition to that, Mito automatically generates the code in the cell below. from mitosheet import *; register_analysis('UUID-b580825e-1ba5-47fc-851a-612cf52b9543')# Imported StudentsPerformance.csvimport pandas as pdStudentsPerformance_csv = pd.read_csv(r'StudentsPerformance.csv') That’s everything you need to import data with mitosheet. Now let’s automate some common Pandas methods. You can continue reading or watch my video tutorial instead. Adding a new column is a common task we do in Excel/Pandas. With Excel, we only need to right-click to create a new column, and with Pandas, we have to use the .insert() method. With Mito, we can have the best of both worlds. To add a new column, you only need to click on the “Add Col” button. Then double-click on the column name to set the name you want. Let’s do this by creating a new column that we will name “average.” Once you’re done, check the cell below. Mito automatically generates the code that adds and renames a column. Mito can help us sum row values as if we were using Microsoft Excel. We only need to locate the cell where we want to introduce the formula, then press = and select the columns we want to sum and write the + operator between them. To show you better how this works, let’s calculate the average score of the math, reading, and writing exams. Locate a cell in the “average” column that we created in the previous step, write the formula shown in the gif below, press enter, and voilá! In case you’re curious to know what Mito did, here’s a snippet of the code automatically generated by Mito. We can filter data based on 1 or more conditions. Let’s say we only want to show data related to the female gender. With Mito, we only need to select the “gender” column, then click on the funnel icon and choose what we want to filter. In this case, we go to the “filter” section, click on “add filter” and set “is exactly” equal to “female” Now let’s say we want to show data related to the female gender that belongs to the group B. Here we only need to repeat the steps we followed to select the female gender, but now with the group B. Select the “group” column, click on the funnel icon, go to the “filter” section, click on “add filter” and set “is exactly” equal to “group B” The code below corresponds to the previous filters. We can create a pivot table in Python as we would do in Excel using mitosheet. First, click on the “Pivot” button and then select the elements you wish to include in the rows, columns, and values. In our example, we will create a pivot table that shows the mean of the math and reading scores of all the groups inside the race/ethnicity column (group column). To do so, follow the steps shown in the gif below. In case you’re curious to know the code behind the curtains, here’s a snippet. Just like Excel, Mito helps us create basic visualization with a couple of clicks in Python. Let’s create a barplot of the pivot table we created before. To do so, click on the “Graph” button, then make sure the data source is the new pivot table “df2” we created and the chart type is set to “bar” In the X-axis, we should include the “race/ethnicity” column (group column), and in the Y-axis, the “match score mean” column. That’s it! We could do all of this in a couple of minutes with Mito. If you have a lot of experience with Pandas, probably you could get results as fast as Mito, but this library comes in handy, if you’re new to Pandas or Python Merging 2 tables can be easily accomplished with Mito. In this example, we’ll see how to do an inner join. To do so, we need two tables with a column in common, so download the “StudentsPerformance_id” and “LanguageScore” CSV files from my Github. To import this second table, follow the steps shown in the first section of this article “Create a dataframe” Once you have the two tables imported in Mito, click on the “Merge” button to join them. Make sure the “Merge Key” option is set to “id” in both tables (this is the column in common that we need to make an inner join) After this, you will see there’s a new dataframe named “df3.” This is the result after joining the “StudentsPerformance_id_csv” and “LanguageScore_csv” dataframes. Join my email list with 6k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to thousands of Python guides and Data science articles. If you sign up using my link, I’ll earn a small commission with no extra cost to you.
[ { "code": null, "e": 411, "s": 172, "text": "Pandas is the best tool to do data analysis in Python and it has many advantages over tools like Microsoft Excel, but the transition between Excel to Python is challenging for those with little coding experience or that are new to Pandas." }, { "code": null, "e": 556, "s": 411, "text": "Fortunately, that’s no longer the case. A few weeks ago I came across a Python library that helps us work with Pandas as if we were using Excel." }, { "code": null, "e": 829, "s": 556, "text": "In this article, I will show you how to do things like creating pivot tables, joining tables, filtering data, and more using a Python library that allows us to work with a Pandas dataframe using an interface similar to Excel and automatically generates Pandas code for us." }, { "code": null, "e": 880, "s": 829, "text": "Moving from Excel to Python has never been easier!" }, { "code": null, "e": 1182, "s": 880, "text": "In this guide, the data we’ll use is a “StudentsPerformance” CSV file available on Google Drive, which I generated myself. This is random data that contains marks obtained by students in different subjects and, with the help of Mito, we will easily move from Excel spreadsheets to Python’s dataframes." }, { "code": null, "e": 1268, "s": 1182, "text": "Make sure that the CSV file and your Python script are located in the same directory." }, { "code": null, "e": 1478, "s": 1268, "text": "To easily create pivot tables, visualizations, and perform operations you would do in Excel or Pandas, we only need to install the mitosheet library (make sure you have Python 3.6 or above and also JupyterLab)" }, { "code": null, "e": 1636, "s": 1478, "text": "To install mitosheet, first, open a new terminal or command prompt and then run the following command (if possible, install it in a new virtual environment):" }, { "code": null, "e": 1703, "s": 1636, "text": "python -m pip install mitoinstallerpython -m mitoinstaller install" }, { "code": null, "e": 1832, "s": 1703, "text": "That’s everything we need to start working with Mito! For more details about the installation, check the official documentation." }, { "code": null, "e": 2023, "s": 1832, "text": "To create a dataframe using Python we would need to import pandas and use the .read_csv() method, but with Mito, we only need to import mitosheet and initiate it by typing mitosheet.sheet()." }, { "code": null, "e": 2057, "s": 2023, "text": "import mitosheetmitosheet.sheet()" }, { "code": null, "e": 2180, "s": 2057, "text": "The code above will create a mitosheet. If the sheet does not render when you call mitosheet.sheet(), relaunch JupyterLab." }, { "code": null, "e": 2333, "s": 2180, "text": "After this, we can import a dataset by clicking on the + button in the bottom left corner. Then, select the StudentsPerformance.csv file as shown below." }, { "code": null, "e": 2486, "s": 2333, "text": "Once the CSV is imported, a dataframe is created using the same file name. In addition to that, Mito automatically generates the code in the cell below." }, { "code": null, "e": 2692, "s": 2486, "text": "from mitosheet import *; register_analysis('UUID-b580825e-1ba5-47fc-851a-612cf52b9543')# Imported StudentsPerformance.csvimport pandas as pdStudentsPerformance_csv = pd.read_csv(r'StudentsPerformance.csv')" }, { "code": null, "e": 2858, "s": 2692, "text": "That’s everything you need to import data with mitosheet. Now let’s automate some common Pandas methods. You can continue reading or watch my video tutorial instead." }, { "code": null, "e": 3036, "s": 2858, "text": "Adding a new column is a common task we do in Excel/Pandas. With Excel, we only need to right-click to create a new column, and with Pandas, we have to use the .insert() method." }, { "code": null, "e": 3216, "s": 3036, "text": "With Mito, we can have the best of both worlds. To add a new column, you only need to click on the “Add Col” button. Then double-click on the column name to set the name you want." }, { "code": null, "e": 3284, "s": 3216, "text": "Let’s do this by creating a new column that we will name “average.”" }, { "code": null, "e": 3394, "s": 3284, "text": "Once you’re done, check the cell below. Mito automatically generates the code that adds and renames a column." }, { "code": null, "e": 3625, "s": 3394, "text": "Mito can help us sum row values as if we were using Microsoft Excel. We only need to locate the cell where we want to introduce the formula, then press = and select the columns we want to sum and write the + operator between them." }, { "code": null, "e": 3878, "s": 3625, "text": "To show you better how this works, let’s calculate the average score of the math, reading, and writing exams. Locate a cell in the “average” column that we created in the previous step, write the formula shown in the gif below, press enter, and voilá!" }, { "code": null, "e": 3986, "s": 3878, "text": "In case you’re curious to know what Mito did, here’s a snippet of the code automatically generated by Mito." }, { "code": null, "e": 4036, "s": 3986, "text": "We can filter data based on 1 or more conditions." }, { "code": null, "e": 4328, "s": 4036, "text": "Let’s say we only want to show data related to the female gender. With Mito, we only need to select the “gender” column, then click on the funnel icon and choose what we want to filter. In this case, we go to the “filter” section, click on “add filter” and set “is exactly” equal to “female”" }, { "code": null, "e": 4421, "s": 4328, "text": "Now let’s say we want to show data related to the female gender that belongs to the group B." }, { "code": null, "e": 4669, "s": 4421, "text": "Here we only need to repeat the steps we followed to select the female gender, but now with the group B. Select the “group” column, click on the funnel icon, go to the “filter” section, click on “add filter” and set “is exactly” equal to “group B”" }, { "code": null, "e": 4721, "s": 4669, "text": "The code below corresponds to the previous filters." }, { "code": null, "e": 4918, "s": 4721, "text": "We can create a pivot table in Python as we would do in Excel using mitosheet. First, click on the “Pivot” button and then select the elements you wish to include in the rows, columns, and values." }, { "code": null, "e": 5132, "s": 4918, "text": "In our example, we will create a pivot table that shows the mean of the math and reading scores of all the groups inside the race/ethnicity column (group column). To do so, follow the steps shown in the gif below." }, { "code": null, "e": 5211, "s": 5132, "text": "In case you’re curious to know the code behind the curtains, here’s a snippet." }, { "code": null, "e": 5304, "s": 5211, "text": "Just like Excel, Mito helps us create basic visualization with a couple of clicks in Python." }, { "code": null, "e": 5510, "s": 5304, "text": "Let’s create a barplot of the pivot table we created before. To do so, click on the “Graph” button, then make sure the data source is the new pivot table “df2” we created and the chart type is set to “bar”" }, { "code": null, "e": 5637, "s": 5510, "text": "In the X-axis, we should include the “race/ethnicity” column (group column), and in the Y-axis, the “match score mean” column." }, { "code": null, "e": 5866, "s": 5637, "text": "That’s it! We could do all of this in a couple of minutes with Mito. If you have a lot of experience with Pandas, probably you could get results as fast as Mito, but this library comes in handy, if you’re new to Pandas or Python" }, { "code": null, "e": 6224, "s": 5866, "text": "Merging 2 tables can be easily accomplished with Mito. In this example, we’ll see how to do an inner join. To do so, we need two tables with a column in common, so download the “StudentsPerformance_id” and “LanguageScore” CSV files from my Github. To import this second table, follow the steps shown in the first section of this article “Create a dataframe”" }, { "code": null, "e": 6442, "s": 6224, "text": "Once you have the two tables imported in Mito, click on the “Merge” button to join them. Make sure the “Merge Key” option is set to “id” in both tables (this is the column in common that we need to make an inner join)" }, { "code": null, "e": 6606, "s": 6442, "text": "After this, you will see there’s a new dataframe named “df3.” This is the result after joining the “StudentsPerformance_id_csv” and “LanguageScore_csv” dataframes." }, { "code": null, "e": 6724, "s": 6606, "text": "Join my email list with 6k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)" } ]
C library function - clearerr()
The C library function void clearerr(FILE *stream) clears the end-of-file and error indicators for the given stream. Following is the declaration for clearerr() function. void clearerr(FILE *stream) stream − This is the pointer to a FILE object that identifies the stream. stream − This is the pointer to a FILE object that identifies the stream. This should not fail and do not set the external variable errno but in case it detects that its argument is not a valid stream, it must return -1 and set errno to EBADF. The following example shows the usage of clearerr() function. #include <stdio.h> int main () { FILE *fp; char c; fp = fopen("file.txt", "w"); c = fgetc(fp); if( ferror(fp) ) { printf("Error in reading from file : file.txt\n"); } clearerr(fp); if( ferror(fp) ) { printf("Error in reading from file : file.txt\n"); } fclose(fp); return(0); } Assuming we have a text file file.txt, which is an empty file, let us compile and run the above program, this will produce the following result because we try to read a file which we opened in write only mode. Error reading from file "file.txt" 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2124, "s": 2007, "text": "The C library function void clearerr(FILE *stream) clears the end-of-file and error indicators for the given stream." }, { "code": null, "e": 2178, "s": 2124, "text": "Following is the declaration for clearerr() function." }, { "code": null, "e": 2206, "s": 2178, "text": "void clearerr(FILE *stream)" }, { "code": null, "e": 2280, "s": 2206, "text": "stream − This is the pointer to a FILE object that identifies the stream." }, { "code": null, "e": 2354, "s": 2280, "text": "stream − This is the pointer to a FILE object that identifies the stream." }, { "code": null, "e": 2524, "s": 2354, "text": "This should not fail and do not set the external variable errno but in case it detects that its argument is not a valid stream, it must return -1 and set errno to EBADF." }, { "code": null, "e": 2586, "s": 2524, "text": "The following example shows the usage of clearerr() function." }, { "code": null, "e": 2917, "s": 2586, "text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n char c;\n\n fp = fopen(\"file.txt\", \"w\");\n\n c = fgetc(fp);\n if( ferror(fp) ) {\n printf(\"Error in reading from file : file.txt\\n\");\n }\n clearerr(fp);\n \n if( ferror(fp) ) {\n printf(\"Error in reading from file : file.txt\\n\");\n }\n fclose(fp);\n\n return(0);\n}" }, { "code": null, "e": 3127, "s": 2917, "text": "Assuming we have a text file file.txt, which is an empty file, let us compile and run the above program, this will produce the following result because we try to read a file which we opened in write only mode." }, { "code": null, "e": 3163, "s": 3127, "text": "Error reading from file \"file.txt\"\n" }, { "code": null, "e": 3196, "s": 3163, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3211, "s": 3196, "text": " Nishant Malik" }, { "code": null, "e": 3246, "s": 3211, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3261, "s": 3246, "text": " Nishant Malik" }, { "code": null, "e": 3296, "s": 3261, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3310, "s": 3296, "text": " Asif Hussain" }, { "code": null, "e": 3343, "s": 3310, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3361, "s": 3343, "text": " Richa Maheshwari" }, { "code": null, "e": 3396, "s": 3361, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3415, "s": 3396, "text": " Vandana Annavaram" }, { "code": null, "e": 3448, "s": 3415, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3460, "s": 3448, "text": " Amit Diwan" }, { "code": null, "e": 3467, "s": 3460, "text": " Print" }, { "code": null, "e": 3478, "s": 3467, "text": " Add Notes" } ]
How to Create More Efficient Deep Learning Models | by Tudor Surdoiu | Towards Data Science
In this article, I am going to present and discuss several important approaches and techniques that can help improve the efficiency of a deep learning model on different levels. These types of optimizations are becoming even more important now as the new improvements in deep learning models also bring an increase in the number of parameters, resources requirements to train, latency, storage requirements, etc. The main topics that I will tackle are the following: Compressions Techniques Learning Techniques Efficient Architectures Automation These types of techniques are targeting the representational efficiency of the entire model, this is possible mainly because many state of the art models are over-parameterized. Multiple components of the main model can benefit without affecting (within a margin) the scoring results computed on the original version, such as training time, inference latency, memory footprint. By compressing some part of the computation graph of a neural network model we can also improve its generalizability. Multiple ideas have been explored here, some of the most successful are: Pruning — refers to the removal or setting to zero of a set of parameters from a neural network using various strategies to pick the affected weights to obtain a sparse network that would not need as much memory as before. The most popular pruning strategies are based on: saliency, random structured/unstructured, scheduling, distribution of sparsity budget, regrowth. Usually after pruning it is recommended to perform fine-tuning on the resulting model. Example of model pruning in PyTorch: import torch.nn.utils.prune as prunemodel = Model()layers_to_prune = ( (model.conv1, 'weight'), (model.fc1, 'weight'))// This will prune 20% of the parameters with lowest L1-normprune.global_unstructured( layers_to_prune, pruning_method=prune.L1Unstructured, amount=0.2,) Quantization — reduces the precision of the data types that are used for the weights and activations of the model (for example: reduce from 32-bit floating-point values to 8-bit fixed-point). Most of the time we can see improvements both regarding the memory footprint and the latency when we apply quantization. Generally, there are two types of quantization: post-training and quantization aware training; I think that the terms are mostly self-explanatory (at least in a high-level view), the only thing that needs to be mentioned is that the first one could affect the quality of the model for inference. PyTorch has multiple quantization strategies, and here’s the most simple to use: quantized_model= torch.quantization.quantize_dynamic( model, qconfig_spec={torch.nn.Linear}, dtype=torch.qint8)//qconfig_spec specifies the list of submodule names in model to apply quantization to. Matrix-based Compression Techniques: Low-Rank Approximation, Dictionary Learning, Layer Splicing, etc. These types of techniques try to enhance the quality of the model by changing some aspects of the training procedure. By only targeting the training phase the validation/test scoring should remain representative for production. Type of learning techniques: Distillation — for this method we introduce the idea of “student” network and “teacher” network. Basically, we have one or an ensemble of larger networks that are “teaching” the smaller network to reproduce the entire process or just some intermediate representation. We can also use the teacher network to create soft labels that we can use in the loss function alongside ground-truth labels, the idea is that the soft labels might capture some relationship between classes and this can help in the training. Data Augmentation — when working with deep models we usually need a large number of samples to make sure that our model can generalize. However, this can sometimes be a problem due to the high cost or the scarcity of that specific data type. A possible improvement to the dataset size problem comes in the shape of data augmentation, which is basically a set of methods of generating synthetic samples by applying some sort of transformations or interpolation. Most data augmentation techniques target computer vision tasks, some examples of that would be: resize, rotation, flip, crop, etc. In PyTorch we can stack multiple types of transformations and use them directly in our custom Dataset class: train_transforms = A.Compose( [ A.Resize(width=320, height=320), A.RandomCrop(height=728, width=728), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.RandomRotate90(p=0.5), ToTensor(), ]) Self-Supervised Learning — represents one of the most interesting solutions to the “old” problem of not having a large enough labeled dataset. When applying a Self-Supervised Learning method we are creating a “pretext task” using our unlabeled data that allows us to generate good representations that can be later used for more specific tasks. Once we have good enough embeddings we can add a prediction head and fine-tune the model with the labeled data. For example, in NLP it is rather common to apply Self-Supervision to predict a masked word in an unlabeled sentence. In CV there is the concept of Contrastive Learning, where a model is trained to distinguish between images that are different. Due to the low requirements of labeled data, this technique is considered to be data-efficient. One other way of improving the efficiency of a deep learning system is to take a step back and try to tackle the problem at the level of the model’s architecture, some neural networks layer designs being better suited for specific tasks or data types. Next, I will try to show you several examples of model architecture designs that brought several improvements for computer vision and natural language processing: Computer Vision: Convolutional Layers — this type of layer has revolutionized the field of computer vision. It takes advantage of the spatial locality of image features and by stacking them it creates multiple levels of representations thus allowing the detection of more complex features in the later layers. Furthermore, because the operation of convolution reuses the same filter for the whole image this has also considerably reduced the number of parameters of the models. Natural Language Processing: Transformers — have brought enormous improvements to the field of NLP (beginning with Attention Is All You Need, Ashish Vaswani et al.), the main advantage of using this type of neural network is that it removes the bottleneck of having just a single feature vector for representing the context of the entire input sequence. The Transformer architecture uses self-attention and cross-attention to encode a context for each input element of the sequence. Here is a great course that explains the basics and usage of the Transformers. Another approach to finding new avenues to improve the efficiency of machine learning models is to “brute force” the search of different ideas by using different automatic search techniques. The big disadvantage is that the search-based approach requires a large number of computational resources and time. We can split the types of automation by considering the level of search spaces: Hyperparameter Optimization (HO) — as the name suggests this type of automation tries to search for a more efficient model by changing the values of some hyperparameters such as learning rate, number of layers, weight decay, batch size, etc. Even though we use a KFold splitting strategy to iterate over different values of hyperparameters per fold, it would still require a lot of computations to go through them all. There are several search strategies that we can follow: Grid Search, Random Search, Bayesian Search, Coarse-to-Fine Search. Neural Architecture Search (NAS) — this can be considered an extension of hyperparameter optimization, allowing for additional elements in the search space like different operation blocks (Convolutions, Linear Layers, Pooling) and different ways in which to combine them. Furthermore for NAS researchers have also used Reinforcement Learning to search for better architectures. As a final word, the list that I have gone through in this article is by no means comprehensive and many more ongoing research efforts try to improve every bottleneck of a deep learning system. Thank you for reading and if you want to stay up to date with the latest machine learning news and some good quality memes :), you can follow me on Twitter here. https://pytorch.org/blog/introduction-to-quantization-on-pytorch/ https://blog.tensorflow.org/2020/02/matrix-compression-operator-tensorflow.html Gaurav Menghani: Efficient Deep Learning: A Survey on Making Deep Learning Models Smaller, Faster, and Better (https://arxiv.org/abs/2106.08962)
[ { "code": null, "e": 584, "s": 171, "text": "In this article, I am going to present and discuss several important approaches and techniques that can help improve the efficiency of a deep learning model on different levels. These types of optimizations are becoming even more important now as the new improvements in deep learning models also bring an increase in the number of parameters, resources requirements to train, latency, storage requirements, etc." }, { "code": null, "e": 638, "s": 584, "text": "The main topics that I will tackle are the following:" }, { "code": null, "e": 662, "s": 638, "text": "Compressions Techniques" }, { "code": null, "e": 682, "s": 662, "text": "Learning Techniques" }, { "code": null, "e": 706, "s": 682, "text": "Efficient Architectures" }, { "code": null, "e": 717, "s": 706, "text": "Automation" }, { "code": null, "e": 1213, "s": 717, "text": "These types of techniques are targeting the representational efficiency of the entire model, this is possible mainly because many state of the art models are over-parameterized. Multiple components of the main model can benefit without affecting (within a margin) the scoring results computed on the original version, such as training time, inference latency, memory footprint. By compressing some part of the computation graph of a neural network model we can also improve its generalizability." }, { "code": null, "e": 1286, "s": 1213, "text": "Multiple ideas have been explored here, some of the most successful are:" }, { "code": null, "e": 1743, "s": 1286, "text": "Pruning — refers to the removal or setting to zero of a set of parameters from a neural network using various strategies to pick the affected weights to obtain a sparse network that would not need as much memory as before. The most popular pruning strategies are based on: saliency, random structured/unstructured, scheduling, distribution of sparsity budget, regrowth. Usually after pruning it is recommended to perform fine-tuning on the resulting model." }, { "code": null, "e": 1780, "s": 1743, "text": "Example of model pruning in PyTorch:" }, { "code": null, "e": 2067, "s": 1780, "text": "import torch.nn.utils.prune as prunemodel = Model()layers_to_prune = ( (model.conv1, 'weight'), (model.fc1, 'weight'))// This will prune 20% of the parameters with lowest L1-normprune.global_unstructured( layers_to_prune, pruning_method=prune.L1Unstructured, amount=0.2,)" }, { "code": null, "e": 2676, "s": 2067, "text": "Quantization — reduces the precision of the data types that are used for the weights and activations of the model (for example: reduce from 32-bit floating-point values to 8-bit fixed-point). Most of the time we can see improvements both regarding the memory footprint and the latency when we apply quantization. Generally, there are two types of quantization: post-training and quantization aware training; I think that the terms are mostly self-explanatory (at least in a high-level view), the only thing that needs to be mentioned is that the first one could affect the quality of the model for inference." }, { "code": null, "e": 2757, "s": 2676, "text": "PyTorch has multiple quantization strategies, and here’s the most simple to use:" }, { "code": null, "e": 2967, "s": 2757, "text": "quantized_model= torch.quantization.quantize_dynamic( model, qconfig_spec={torch.nn.Linear}, dtype=torch.qint8)//qconfig_spec specifies the list of submodule names in model to apply quantization to." }, { "code": null, "e": 3070, "s": 2967, "text": "Matrix-based Compression Techniques: Low-Rank Approximation, Dictionary Learning, Layer Splicing, etc." }, { "code": null, "e": 3298, "s": 3070, "text": "These types of techniques try to enhance the quality of the model by changing some aspects of the training procedure. By only targeting the training phase the validation/test scoring should remain representative for production." }, { "code": null, "e": 3327, "s": 3298, "text": "Type of learning techniques:" }, { "code": null, "e": 3837, "s": 3327, "text": "Distillation — for this method we introduce the idea of “student” network and “teacher” network. Basically, we have one or an ensemble of larger networks that are “teaching” the smaller network to reproduce the entire process or just some intermediate representation. We can also use the teacher network to create soft labels that we can use in the loss function alongside ground-truth labels, the idea is that the soft labels might capture some relationship between classes and this can help in the training." }, { "code": null, "e": 4429, "s": 3837, "text": "Data Augmentation — when working with deep models we usually need a large number of samples to make sure that our model can generalize. However, this can sometimes be a problem due to the high cost or the scarcity of that specific data type. A possible improvement to the dataset size problem comes in the shape of data augmentation, which is basically a set of methods of generating synthetic samples by applying some sort of transformations or interpolation. Most data augmentation techniques target computer vision tasks, some examples of that would be: resize, rotation, flip, crop, etc." }, { "code": null, "e": 4538, "s": 4429, "text": "In PyTorch we can stack multiple types of transformations and use them directly in our custom Dataset class:" }, { "code": null, "e": 4776, "s": 4538, "text": "train_transforms = A.Compose( [ A.Resize(width=320, height=320), A.RandomCrop(height=728, width=728), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.RandomRotate90(p=0.5), ToTensor(), ])" }, { "code": null, "e": 5573, "s": 4776, "text": "Self-Supervised Learning — represents one of the most interesting solutions to the “old” problem of not having a large enough labeled dataset. When applying a Self-Supervised Learning method we are creating a “pretext task” using our unlabeled data that allows us to generate good representations that can be later used for more specific tasks. Once we have good enough embeddings we can add a prediction head and fine-tune the model with the labeled data. For example, in NLP it is rather common to apply Self-Supervision to predict a masked word in an unlabeled sentence. In CV there is the concept of Contrastive Learning, where a model is trained to distinguish between images that are different. Due to the low requirements of labeled data, this technique is considered to be data-efficient." }, { "code": null, "e": 5825, "s": 5573, "text": "One other way of improving the efficiency of a deep learning system is to take a step back and try to tackle the problem at the level of the model’s architecture, some neural networks layer designs being better suited for specific tasks or data types." }, { "code": null, "e": 5988, "s": 5825, "text": "Next, I will try to show you several examples of model architecture designs that brought several improvements for computer vision and natural language processing:" }, { "code": null, "e": 6466, "s": 5988, "text": "Computer Vision: Convolutional Layers — this type of layer has revolutionized the field of computer vision. It takes advantage of the spatial locality of image features and by stacking them it creates multiple levels of representations thus allowing the detection of more complex features in the later layers. Furthermore, because the operation of convolution reuses the same filter for the whole image this has also considerably reduced the number of parameters of the models." }, { "code": null, "e": 7028, "s": 6466, "text": "Natural Language Processing: Transformers — have brought enormous improvements to the field of NLP (beginning with Attention Is All You Need, Ashish Vaswani et al.), the main advantage of using this type of neural network is that it removes the bottleneck of having just a single feature vector for representing the context of the entire input sequence. The Transformer architecture uses self-attention and cross-attention to encode a context for each input element of the sequence. Here is a great course that explains the basics and usage of the Transformers." }, { "code": null, "e": 7335, "s": 7028, "text": "Another approach to finding new avenues to improve the efficiency of machine learning models is to “brute force” the search of different ideas by using different automatic search techniques. The big disadvantage is that the search-based approach requires a large number of computational resources and time." }, { "code": null, "e": 7415, "s": 7335, "text": "We can split the types of automation by considering the level of search spaces:" }, { "code": null, "e": 7958, "s": 7415, "text": "Hyperparameter Optimization (HO) — as the name suggests this type of automation tries to search for a more efficient model by changing the values of some hyperparameters such as learning rate, number of layers, weight decay, batch size, etc. Even though we use a KFold splitting strategy to iterate over different values of hyperparameters per fold, it would still require a lot of computations to go through them all. There are several search strategies that we can follow: Grid Search, Random Search, Bayesian Search, Coarse-to-Fine Search." }, { "code": null, "e": 8336, "s": 7958, "text": "Neural Architecture Search (NAS) — this can be considered an extension of hyperparameter optimization, allowing for additional elements in the search space like different operation blocks (Convolutions, Linear Layers, Pooling) and different ways in which to combine them. Furthermore for NAS researchers have also used Reinforcement Learning to search for better architectures." }, { "code": null, "e": 8530, "s": 8336, "text": "As a final word, the list that I have gone through in this article is by no means comprehensive and many more ongoing research efforts try to improve every bottleneck of a deep learning system." }, { "code": null, "e": 8692, "s": 8530, "text": "Thank you for reading and if you want to stay up to date with the latest machine learning news and some good quality memes :), you can follow me on Twitter here." }, { "code": null, "e": 8758, "s": 8692, "text": "https://pytorch.org/blog/introduction-to-quantization-on-pytorch/" }, { "code": null, "e": 8838, "s": 8758, "text": "https://blog.tensorflow.org/2020/02/matrix-compression-operator-tensorflow.html" } ]
p5.js | Constants | HALF_PI - GeeksforGeeks
12 Apr, 2019 The HALF_PI is a mathematical constant and its value is 1.57079632679489661923. The HALF_PI is the half ratio of the circumference of a circle to its diameter. Syntax: HALF_PI Below program illustrates the usage of HALF_PI in p5.js: Example: function setup() { // Create Canvas of size 300*200 createCanvas(300, 200);} function draw() { // Set the background Color background(220); // Set the stroke color stroke(255, 204, 0); // Set the stroke weight strokeWeight(4); // Use of constant HALF_PI arc(50, 50, 280, 280, 0, HALF_PI/2); noStroke(); // Set the font size textSize(20); // Display result text("Value of HALF_PI is " + HALF_PI, 30, 180);} Output: Reference: https://p5js.org/reference/#/p5/HALF_PI JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 43301, "s": 43273, "text": "\n12 Apr, 2019" }, { "code": null, "e": 43461, "s": 43301, "text": "The HALF_PI is a mathematical constant and its value is 1.57079632679489661923. The HALF_PI is the half ratio of the circumference of a circle to its diameter." }, { "code": null, "e": 43469, "s": 43461, "text": "Syntax:" }, { "code": null, "e": 43477, "s": 43469, "text": "HALF_PI" }, { "code": null, "e": 43534, "s": 43477, "text": "Below program illustrates the usage of HALF_PI in p5.js:" }, { "code": null, "e": 43543, "s": 43534, "text": "Example:" }, { "code": "function setup() { // Create Canvas of size 300*200 createCanvas(300, 200);} function draw() { // Set the background Color background(220); // Set the stroke color stroke(255, 204, 0); // Set the stroke weight strokeWeight(4); // Use of constant HALF_PI arc(50, 50, 280, 280, 0, HALF_PI/2); noStroke(); // Set the font size textSize(20); // Display result text(\"Value of HALF_PI is \" + HALF_PI, 30, 180);}", "e": 44051, "s": 43543, "text": null }, { "code": null, "e": 44059, "s": 44051, "text": "Output:" }, { "code": null, "e": 44110, "s": 44059, "text": "Reference: https://p5js.org/reference/#/p5/HALF_PI" }, { "code": null, "e": 44127, "s": 44110, "text": "JavaScript-p5.js" }, { "code": null, "e": 44138, "s": 44127, "text": "JavaScript" }, { "code": null, "e": 44155, "s": 44138, "text": "Web Technologies" }, { "code": null, "e": 44253, "s": 44155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44262, "s": 44253, "text": "Comments" }, { "code": null, "e": 44275, "s": 44262, "text": "Old Comments" }, { "code": null, "e": 44336, "s": 44275, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 44381, "s": 44336, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 44453, "s": 44381, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 44522, "s": 44453, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 44549, "s": 44522, "text": "File uploading in React.js" }, { "code": null, "e": 44605, "s": 44549, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 44638, "s": 44605, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 44700, "s": 44638, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 44743, "s": 44700, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript while Loop
Loops can execute a block of code as long as a specified condition is true. The while loop loops through a block of code as long as a specified condition is true. In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10: If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser. The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. The example below uses a do while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: Do not forget to increase the variable used in the condition, otherwise the loop will never end! If you have read the previous chapter, about the for loop, you will discover that a while loop is much the same as a for loop, with statement 1 and statement 3 omitted. The loop in this example uses a for loop to collect the car names from the cars array: The loop in this example uses a while loop to collect the car names from the cars array: Create a loop that runs as long as i is less than 10. let i = 0; (i 10) { console.log(i); i++ } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 76, "s": 0, "text": "Loops can execute a block of code\nas long as a specified condition is true." }, { "code": null, "e": 163, "s": 76, "text": "The while loop loops through a block of code as long as a specified condition is true." }, { "code": null, "e": 285, "s": 163, "text": "In the following example, the code in the loop will run, over and over again, as long as \na variable (i) is less than 10:" }, { "code": null, "e": 402, "s": 285, "text": "If you forget to increase the variable used in the condition, the loop will never end.\nThis will crash your browser." }, { "code": null, "e": 602, "s": 402, "text": "The do while loop is a variant of the while loop. This loop will \nexecute the code block once, before checking if the condition is true, then it will\nrepeat the loop as long as the condition is true." }, { "code": null, "e": 791, "s": 602, "text": "The example below uses a do while loop. The loop will always be \nexecuted at least once, even if the condition is false, because the code block \nis executed before the condition is tested:" }, { "code": null, "e": 889, "s": 791, "text": "Do not forget to increase the variable used in the condition, otherwise \nthe loop will never end!" }, { "code": null, "e": 1059, "s": 889, "text": "If you have read the previous chapter, about the for loop, you will discover that a while loop is \nmuch the same as a for loop, with statement 1 and statement 3 omitted." }, { "code": null, "e": 1147, "s": 1059, "text": "The loop in this example uses a for loop to collect the car \nnames from the cars array:" }, { "code": null, "e": 1237, "s": 1147, "text": "The loop in this example uses a while loop to collect the \ncar names from the cars array:" }, { "code": null, "e": 1291, "s": 1237, "text": "Create a loop that runs as long as i is less than 10." }, { "code": null, "e": 1340, "s": 1291, "text": "let i = 0;\n (i 10) {\n console.log(i);\n i++\n}\n" }, { "code": null, "e": 1359, "s": 1340, "text": "Start the Exercise" }, { "code": null, "e": 1392, "s": 1359, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1434, "s": 1392, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1541, "s": 1434, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1560, "s": 1541, "text": "help@w3schools.com" } ]
Impala - Distinct Operator
The distinct operator in Impala is used to get the unique values by removing duplicates. Following is the syntax of the distinct operator. select distinct columns... from table_name; Assume that we have a table named customers in Impala and its contents are as follows − [quickstart.cloudera:21000] > select distinct id, name, age, salary from customers; Query: select distinct id, name, age, salary from customers Here you can observe the salary of the customers Ramesh and Chaitali entered twice and using the distinct operator, we can select the unique values as shown below. [quickstart.cloudera:21000] > select distinct name, age, address from customers; On executing, the above query gives the following output. Query: select distinct id, name from customers +----------+-----+-----------+ | name | age | address | +----------+-----+-----------+ | Ramesh | 32 | Ahmedabad | | Khilan | 25 | Delhi | | kaushik | 23 | Kota | | Chaitali | 25 | Mumbai | | Hardik | 27 | Bhopal | | Komal | 22 | MP | +----------+-----+-----------+ Fetched 9 row(s) in 1.46s Print Add Notes Bookmark this page
[ { "code": null, "e": 2374, "s": 2285, "text": "The distinct operator in Impala is used to get the unique values by removing duplicates." }, { "code": null, "e": 2424, "s": 2374, "text": "Following is the syntax of the distinct operator." }, { "code": null, "e": 2469, "s": 2424, "text": "select distinct columns... from table_name;\n" }, { "code": null, "e": 2557, "s": 2469, "text": "Assume that we have a table named customers in Impala and its contents are as follows −" }, { "code": null, "e": 2703, "s": 2557, "text": "[quickstart.cloudera:21000] > select distinct id, name, age, salary from customers; \nQuery: select distinct id, name, age, salary from customers\n" }, { "code": null, "e": 2867, "s": 2703, "text": "Here you can observe the salary of the customers Ramesh and Chaitali entered twice and using the distinct operator, we can select the unique values as shown below." }, { "code": null, "e": 2949, "s": 2867, "text": "[quickstart.cloudera:21000] > select distinct name, age, address from customers;\n" }, { "code": null, "e": 3007, "s": 2949, "text": "On executing, the above query gives the following output." }, { "code": null, "e": 3397, "s": 3007, "text": "Query: select distinct id, name from customers\n+----------+-----+-----------+ \n| name | age | address | \n+----------+-----+-----------+ \n| Ramesh | 32 | Ahmedabad |\n| Khilan | 25 | Delhi | \n| kaushik | 23 | Kota | \n| Chaitali | 25 | Mumbai |\n| Hardik | 27 | Bhopal |\n| Komal | 22 | MP | \n+----------+-----+-----------+\nFetched 9 row(s) in 1.46s\n" }, { "code": null, "e": 3404, "s": 3397, "text": " Print" }, { "code": null, "e": 3415, "s": 3404, "text": " Add Notes" } ]
Cl0neMast3r - Cloning Tool in Kali Linux - GeeksforGeeks
05 Aug, 2021 Cl0neMast3r is a Python script that was coded to add, update, delete tools easier. It allows the user to choose tools from GitHub and install them on their system with the help of just two-three clicks. Also, one can ensure that he has the latest version of his favorite tool. Python3 Requests BeautifulSoup4 Step 1: First, we need to clone this tool. git clone https://github.com/Abdulraheem30042/Cl0neMast3r.git Step 2: After cloning, change the directory to Cl0neMast3r. cd Cl0neMast3r/ Also, there are some requirements that need to be installed, so execute the following command: pip install -r requirements.txt Fig 1: Successfully installed Cl0neMast3r. Step 3: We need to change the permissions of the file. chmod +x Cl0neMast3r.py Step 4: Now to start the tool, type the following command. python Cl0neMast3r.py Fig 2: Cl0neMast3r. As we can see, cl0neMast3r provides us many options such as finding a tool on GitHub, Updating tools, Adding a tool, etc. Let’s start by using it’s finding a tool on GitHub option, type F, and enter the tool name you want to download. Fig 3: Find a tool on GitHub. Cl0neMast3r has found 4 pages, now we need to tell the tool that if we want to see all the pages found or only 1, let’s display all the pages, type 4. Fig 4: Tool number and author shown by the Cl0neMast3r. As we can see almost 40 tools were found, and now we need to tell the tool number which we need to get installed. Fig 5: After providing the tool no., specified tool gets installed. Let’s use the update your tool option, type u, and then type 1 or 2 depending upon your requirement that whether you want to update all tools or just old tools. Let’s select 2, type 2. Fig 6: Update your tool. After selecting 2, our most recent tool gets updated. Fig 7: Tool gets updated. Let’s display our tools, type S. Fig 8: Displaying our tools and their status. In conclusion, Cl0neMast3r gives us the flexibility not only to add, delete tools, but also one can update them with the help of two-three clicks which in turn helps us to achieve our pen testing tasks in an efficient and convenient way. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24292, "s": 24015, "text": "Cl0neMast3r is a Python script that was coded to add, update, delete tools easier. It allows the user to choose tools from GitHub and install them on their system with the help of just two-three clicks. Also, one can ensure that he has the latest version of his favorite tool." }, { "code": null, "e": 24300, "s": 24292, "text": "Python3" }, { "code": null, "e": 24309, "s": 24300, "text": "Requests" }, { "code": null, "e": 24324, "s": 24309, "text": "BeautifulSoup4" }, { "code": null, "e": 24367, "s": 24324, "text": "Step 1: First, we need to clone this tool." }, { "code": null, "e": 24429, "s": 24367, "text": "git clone https://github.com/Abdulraheem30042/Cl0neMast3r.git" }, { "code": null, "e": 24489, "s": 24429, "text": "Step 2: After cloning, change the directory to Cl0neMast3r." }, { "code": null, "e": 24505, "s": 24489, "text": "cd Cl0neMast3r/" }, { "code": null, "e": 24600, "s": 24505, "text": "Also, there are some requirements that need to be installed, so execute the following command:" }, { "code": null, "e": 24632, "s": 24600, "text": "pip install -r requirements.txt" }, { "code": null, "e": 24675, "s": 24632, "text": "Fig 1: Successfully installed Cl0neMast3r." }, { "code": null, "e": 24730, "s": 24675, "text": "Step 3: We need to change the permissions of the file." }, { "code": null, "e": 24754, "s": 24730, "text": "chmod +x Cl0neMast3r.py" }, { "code": null, "e": 24813, "s": 24754, "text": "Step 4: Now to start the tool, type the following command." }, { "code": null, "e": 24835, "s": 24813, "text": "python Cl0neMast3r.py" }, { "code": null, "e": 24855, "s": 24835, "text": "Fig 2: Cl0neMast3r." }, { "code": null, "e": 24977, "s": 24855, "text": "As we can see, cl0neMast3r provides us many options such as finding a tool on GitHub, Updating tools, Adding a tool, etc." }, { "code": null, "e": 25090, "s": 24977, "text": "Let’s start by using it’s finding a tool on GitHub option, type F, and enter the tool name you want to download." }, { "code": null, "e": 25120, "s": 25090, "text": "Fig 3: Find a tool on GitHub." }, { "code": null, "e": 25271, "s": 25120, "text": "Cl0neMast3r has found 4 pages, now we need to tell the tool that if we want to see all the pages found or only 1, let’s display all the pages, type 4." }, { "code": null, "e": 25327, "s": 25271, "text": "Fig 4: Tool number and author shown by the Cl0neMast3r." }, { "code": null, "e": 25441, "s": 25327, "text": "As we can see almost 40 tools were found, and now we need to tell the tool number which we need to get installed." }, { "code": null, "e": 25509, "s": 25441, "text": "Fig 5: After providing the tool no., specified tool gets installed." }, { "code": null, "e": 25694, "s": 25509, "text": "Let’s use the update your tool option, type u, and then type 1 or 2 depending upon your requirement that whether you want to update all tools or just old tools. Let’s select 2, type 2." }, { "code": null, "e": 25719, "s": 25694, "text": "Fig 6: Update your tool." }, { "code": null, "e": 25773, "s": 25719, "text": "After selecting 2, our most recent tool gets updated." }, { "code": null, "e": 25799, "s": 25773, "text": "Fig 7: Tool gets updated." }, { "code": null, "e": 25832, "s": 25799, "text": "Let’s display our tools, type S." }, { "code": null, "e": 25878, "s": 25832, "text": "Fig 8: Displaying our tools and their status." }, { "code": null, "e": 26116, "s": 25878, "text": "In conclusion, Cl0neMast3r gives us the flexibility not only to add, delete tools, but also one can update them with the help of two-three clicks which in turn helps us to achieve our pen testing tasks in an efficient and convenient way." }, { "code": null, "e": 26127, "s": 26116, "text": "Kali-Linux" }, { "code": null, "e": 26139, "s": 26127, "text": "Linux-Tools" }, { "code": null, "e": 26150, "s": 26139, "text": "Linux-Unix" }, { "code": null, "e": 26248, "s": 26150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26257, "s": 26248, "text": "Comments" }, { "code": null, "e": 26270, "s": 26257, "text": "Old Comments" }, { "code": null, "e": 26305, "s": 26270, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26342, "s": 26305, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26376, "s": 26342, "text": "mv command in Linux with examples" }, { "code": null, "e": 26402, "s": 26376, "text": "Thread functions in C/C++" }, { "code": null, "e": 26428, "s": 26402, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26465, "s": 26428, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26505, "s": 26465, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 26534, "s": 26505, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26576, "s": 26534, "text": "Named Pipe or FIFO with example C program" } ]
CNN - Image data pre-processing with generators - GeeksforGeeks
16 Jul, 2020 The article aims to learn how to pre-processing the input image data to convert it into meaningful floating-point tensors for feeding into Convolutional Neural Networks. Just for the knowledge tensors are used to store data, they can be assumed as multidimensional arrays. A tensor representing a 64 X 64 image having 3 channels will have its dimensions (64, 64, 3). Currently, the data is stored on a drive as JPEG files, So let’s see the steps taken to achieve it. Algorithm: Read the picture files (stored in data folder). Decode the JPEG content to RGB grids of pixels with channels. Convert these into floating-point tensors for input to neural nets. Rescale the pixel values (between 0 and 255) to the [0, 1] interval (as training neural networks with this range gets efficient). It may seem a bit fussy, but Keras has utilities to take over this whole algorithm and do the heavy lifting for you. Keras has a module with image-processing helping tools, located at keras.preprocessing.image. It contains the class ImageDataGenerator, which lets you quickly set up Python generators that can automatically turn image files on disk into batches of preprocessed tensors. # Importing the ImageDataGenerator for pre-processing from keras.preprocessing.image import ImageDataGenerator # Initialising the generators for train and test data# The rescale parameter ensures the input range in [0, 1] train_datagen = ImageDataGenerator(rescale = 1./255)test_datagen = ImageDataGenerator(rescale = 1./255) # Creating the generators with each batch of size = 20 images# The train_dir is the path to train folder which contains input classes# Here it is 'cat' and 'dog' so class_mode is binary train_generator = train_datagen.flow_from_directory( train_dir, target_size =(150, 150), # target_size = input image size batch_size = 20, class_mode ='binary') test_generator = test_datagen.flow_from_directory( test_dir, target_size =(150, 150), batch_size = 20, class_mode ='binary') Output: It yields batches of 150 × 150 RGB images of shape (20, 150, 150, 3) and binary labels of shape (20, ). Fitting the model:Let’s fit the model to the data using the generator, it is done using the fit_generator method, the equivalent of fit for data generators like given below. Its first argument is a Python generator that will yield batches of inputs and targets indefinitely because the data is being generated endlessly, the Keras model needs to know how many samples to draw from the generator before declaring an epoch over. This is the role of the steps_per_epoch argument.Now deciding the steps_per_epoch parameter, as we have total of 2000 training images and each batch is of size 20, hence, the steps_per_epoch will be 2000 / 20 = 100.Code: # Your compiled model being trained with fit_generatorhistory = model.fit_generator( train_generator, steps_per_epoch = 100, epochs = 30, validation_data = test_generator, validation_steps = 50) # Note: here the validation steps are necessary because# the test_genrator also yield batches indefinitely in loops Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 23978, "s": 23950, "text": "\n16 Jul, 2020" }, { "code": null, "e": 24445, "s": 23978, "text": "The article aims to learn how to pre-processing the input image data to convert it into meaningful floating-point tensors for feeding into Convolutional Neural Networks. Just for the knowledge tensors are used to store data, they can be assumed as multidimensional arrays. A tensor representing a 64 X 64 image having 3 channels will have its dimensions (64, 64, 3). Currently, the data is stored on a drive as JPEG files, So let’s see the steps taken to achieve it." }, { "code": null, "e": 24456, "s": 24445, "text": "Algorithm:" }, { "code": null, "e": 24504, "s": 24456, "text": "Read the picture files (stored in data folder)." }, { "code": null, "e": 24566, "s": 24504, "text": "Decode the JPEG content to RGB grids of pixels with channels." }, { "code": null, "e": 24634, "s": 24566, "text": "Convert these into floating-point tensors for input to neural nets." }, { "code": null, "e": 24764, "s": 24634, "text": "Rescale the pixel values (between 0 and 255) to the [0, 1] interval (as training neural networks with this range gets efficient)." }, { "code": null, "e": 25151, "s": 24764, "text": "It may seem a bit fussy, but Keras has utilities to take over this whole algorithm and do the heavy lifting for you. Keras has a module with image-processing helping tools, located at keras.preprocessing.image. It contains the class ImageDataGenerator, which lets you quickly set up Python generators that can automatically turn image files on disk into batches of preprocessed tensors." }, { "code": "# Importing the ImageDataGenerator for pre-processing from keras.preprocessing.image import ImageDataGenerator # Initialising the generators for train and test data# The rescale parameter ensures the input range in [0, 1] train_datagen = ImageDataGenerator(rescale = 1./255)test_datagen = ImageDataGenerator(rescale = 1./255) # Creating the generators with each batch of size = 20 images# The train_dir is the path to train folder which contains input classes# Here it is 'cat' and 'dog' so class_mode is binary train_generator = train_datagen.flow_from_directory( train_dir, target_size =(150, 150), # target_size = input image size batch_size = 20, class_mode ='binary') test_generator = test_datagen.flow_from_directory( test_dir, target_size =(150, 150), batch_size = 20, class_mode ='binary')", "e": 26100, "s": 25151, "text": null }, { "code": null, "e": 26108, "s": 26100, "text": "Output:" }, { "code": null, "e": 26213, "s": 26108, "text": "It yields batches of 150 × 150 RGB images of shape (20, 150, 150, 3) \nand binary labels of shape (20, )." }, { "code": null, "e": 26861, "s": 26213, "text": "Fitting the model:Let’s fit the model to the data using the generator, it is done using the fit_generator method, the equivalent of fit for data generators like given below. Its first argument is a Python generator that will yield batches of inputs and targets indefinitely because the data is being generated endlessly, the Keras model needs to know how many samples to draw from the generator before declaring an epoch over. This is the role of the steps_per_epoch argument.Now deciding the steps_per_epoch parameter, as we have total of 2000 training images and each batch is of size 20, hence, the steps_per_epoch will be 2000 / 20 = 100.Code:" }, { "code": "# Your compiled model being trained with fit_generatorhistory = model.fit_generator( train_generator, steps_per_epoch = 100, epochs = 30, validation_data = test_generator, validation_steps = 50) # Note: here the validation steps are necessary because# the test_genrator also yield batches indefinitely in loops", "e": 27233, "s": 26861, "text": null }, { "code": null, "e": 27250, "s": 27233, "text": "Machine Learning" }, { "code": null, "e": 27257, "s": 27250, "text": "Python" }, { "code": null, "e": 27274, "s": 27257, "text": "Machine Learning" }, { "code": null, "e": 27372, "s": 27274, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27381, "s": 27372, "text": "Comments" }, { "code": null, "e": 27394, "s": 27381, "text": "Old Comments" }, { "code": null, "e": 27450, "s": 27394, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 27492, "s": 27450, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 27525, "s": 27492, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 27553, "s": 27525, "text": "Types of Environments in AI" }, { "code": null, "e": 27592, "s": 27553, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 27620, "s": 27592, "text": "Read JSON file using Python" }, { "code": null, "e": 27670, "s": 27620, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27692, "s": 27670, "text": "Python map() function" } ]
How to remove all child nodes from a parent in jQuery?
To remove all child nodes from a parent in jQuery, use the empty() method. The jQuery empty() method removes all child nodes of the set of matched elements from the DOM. Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function() { $("#demo").empty(); }); }); </script> </head> <body> <ul id='demo'> <li>India</li> <li>US</li> <li>UK</li> </ul> <button>Remove all child nodes</button> </body> </html>
[ { "code": null, "e": 1137, "s": 1062, "text": "To remove all child nodes from a parent in jQuery, use the empty() method." }, { "code": null, "e": 1232, "s": 1137, "text": "The jQuery empty() method removes all child nodes of the set of matched elements from the DOM." }, { "code": null, "e": 1242, "s": 1232, "text": "Live Demo" }, { "code": null, "e": 1617, "s": 1242, "text": "<!DOCTYPE html>\n<html>\n<head>\n\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"button\").click(function() {\n $(\"#demo\").empty();\n });\n});\n</script>\n</head>\n<body>\n\n<ul id='demo'>\n <li>India</li>\n <li>US</li>\n <li>UK</li>\n</ul>\n<button>Remove all child nodes</button>\n\n</body>\n</html>" } ]
Difference Between String and StringBuffer Class in Java
In this post, we will understand the difference between String and StringBuffer class in Java. It is an immutable class. It is an immutable class. This means changes can’t be made to elements of the class. This means changes can’t be made to elements of the class. It is slow. It is slow. It consumes less memory when strings are concatenated. It consumes less memory when strings are concatenated. This is because every time, a new instance is created. This is because every time, a new instance is created. It overrides the equals() method of Object class. It overrides the equals() method of Object class. Hence, the ‘equals’ method can be used to compare two strings. Hence, the ‘equals’ method can be used to compare two strings. Following is an example of the String class − public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); } } It is a mutable class. It is a mutable class. This means changes can be made to the elements in this class. This means changes can be made to the elements in this class. It is fast. It is fast. It uses less memory when strings are concatenated. It uses less memory when strings are concatenated. It class doesn't override the equals() method of Object class. It class doesn't override the equals() method of Object class. Following is an example of the StringBuffer class − public class Demo { public static void main(String args[]) { StringBuffer sBuffer = new StringBuffer("test"); sBuffer.append(" String Buffer"); System.out.println(sBuffer); } }
[ { "code": null, "e": 1157, "s": 1062, "text": "In this post, we will understand the difference between String and StringBuffer class in Java." }, { "code": null, "e": 1183, "s": 1157, "text": "It is an immutable class." }, { "code": null, "e": 1209, "s": 1183, "text": "It is an immutable class." }, { "code": null, "e": 1268, "s": 1209, "text": "This means changes can’t be made to elements of the class." }, { "code": null, "e": 1327, "s": 1268, "text": "This means changes can’t be made to elements of the class." }, { "code": null, "e": 1339, "s": 1327, "text": "It is slow." }, { "code": null, "e": 1351, "s": 1339, "text": "It is slow." }, { "code": null, "e": 1406, "s": 1351, "text": "It consumes less memory when strings are concatenated." }, { "code": null, "e": 1461, "s": 1406, "text": "It consumes less memory when strings are concatenated." }, { "code": null, "e": 1516, "s": 1461, "text": "This is because every time, a new instance is created." }, { "code": null, "e": 1571, "s": 1516, "text": "This is because every time, a new instance is created." }, { "code": null, "e": 1621, "s": 1571, "text": "It overrides the equals() method of Object class." }, { "code": null, "e": 1671, "s": 1621, "text": "It overrides the equals() method of Object class." }, { "code": null, "e": 1734, "s": 1671, "text": "Hence, the ‘equals’ method can be used to compare two strings." }, { "code": null, "e": 1797, "s": 1734, "text": "Hence, the ‘equals’ method can be used to compare two strings." }, { "code": null, "e": 1843, "s": 1797, "text": "Following is an example of the String class −" }, { "code": null, "e": 2061, "s": 1843, "text": "public class StringDemo {\n public static void main(String args[]) {\n String palindrome = \"Dot saw I was Tod\";\n int len = palindrome.length();\n System.out.println( \"String Length is : \" + len );\n }\n}" }, { "code": null, "e": 2084, "s": 2061, "text": "It is a mutable class." }, { "code": null, "e": 2107, "s": 2084, "text": "It is a mutable class." }, { "code": null, "e": 2169, "s": 2107, "text": "This means changes can be made to the elements in this class." }, { "code": null, "e": 2231, "s": 2169, "text": "This means changes can be made to the elements in this class." }, { "code": null, "e": 2243, "s": 2231, "text": "It is fast." }, { "code": null, "e": 2255, "s": 2243, "text": "It is fast." }, { "code": null, "e": 2306, "s": 2255, "text": "It uses less memory when strings are concatenated." }, { "code": null, "e": 2357, "s": 2306, "text": "It uses less memory when strings are concatenated." }, { "code": null, "e": 2420, "s": 2357, "text": "It class doesn't override the equals() method of Object class." }, { "code": null, "e": 2483, "s": 2420, "text": "It class doesn't override the equals() method of Object class." }, { "code": null, "e": 2535, "s": 2483, "text": "Following is an example of the StringBuffer class −" }, { "code": null, "e": 2736, "s": 2535, "text": "public class Demo {\n public static void main(String args[]) {\n StringBuffer sBuffer = new StringBuffer(\"test\");\n sBuffer.append(\" String Buffer\");\n System.out.println(sBuffer);\n }\n}" } ]
What is a Global Object in JavaScript?
Objects in JavaScript are different from the Global Object. Using the new operator, you cannot create global objects. It comes into existence when the scripting engine is initialized. After it is initialized, the functions and constants are available for use. A global object allows you to do the following − It gives access to built-in functions and values. Call alert directly like the below code snippet, with window − It gives access to built-in functions and values. Call alert directly like the below code snippet, with window − alert("Demo Text"); // or window.alert("Demo Text"); It also gives access to global function declarations and var variables − It also gives access to global function declarations and var variables − <html> <head> <script> var str = "Demo Text"; // using window alert( window.str ); </script> </head> <body> </body> </html>
[ { "code": null, "e": 1322, "s": 1062, "text": "Objects in JavaScript are different from the Global Object. Using the new operator, you cannot create global objects. It comes into existence when the scripting engine is initialized. After it is initialized, the functions and constants are available for use." }, { "code": null, "e": 1371, "s": 1322, "text": "A global object allows you to do the following −" }, { "code": null, "e": 1484, "s": 1371, "text": "It gives access to built-in functions and values. Call alert directly like the below code snippet, with window −" }, { "code": null, "e": 1597, "s": 1484, "text": "It gives access to built-in functions and values. Call alert directly like the below code snippet, with window −" }, { "code": null, "e": 1650, "s": 1597, "text": "alert(\"Demo Text\");\n// or\nwindow.alert(\"Demo Text\");" }, { "code": null, "e": 1723, "s": 1650, "text": "It also gives access to global function declarations and var variables −" }, { "code": null, "e": 1796, "s": 1723, "text": "It also gives access to global function declarations and var variables −" }, { "code": null, "e": 1975, "s": 1796, "text": "<html>\n <head>\n <script>\n var str = \"Demo Text\";\n // using window\n alert( window.str );\n </script>\n </head>\n \n <body>\n </body>\n</html>" } ]
HTML DOM createElement() method
The HTML DOM createElement() method is used for creating an HTML element dynamically using JavaScript. It takes the element name as the parameter and creates that element node. You need to use the appendChild() method to have the newly created element as part of DOM . Following is the syntax for createElement() method − document.createElement(nodename) Let us look at an example for the createElement() method − Live Demo <!DOCTYPE html> <html> <body> <h1>createElement() example</h1> <p>Click the below button to create more buttons</p> <button onclick="createButton()">CREATE</button> <br><br> <script> var i=0; function createButton() { i++; var btn = document.createElement("BUTTON"); btn.innerHTML="BUTTON"+i; var br= document.createElement("BR"); document.body.appendChild(btn); document.body.appendChild(br); } </script> </body> </html> This will produce the following output − On clicking the CREATE button three times. One click for one button − In the above example − We have created a button CREATE that will execute the createButton() method on being clicked by the user. <button onclick="createButton()">CREATE</button> The createButton() function creates a <button> element using the createElement() method of the document object. Using the innerHTML, we set the text that will be displayed on the top of the button. We create another element <br> using the createElement() method of the document object. The <button> element and the <br> element are then appended to the document body using the appendChild() method − var i=0; function createButton() { i++; var btn = document.createElement("BUTTON"); btn.innerHTML="BUTTON"+i; var br= document.createElement("BR"); document.body.appendChild(btn); document.body.appendChild(br); }
[ { "code": null, "e": 1331, "s": 1062, "text": "The HTML DOM createElement() method is used for creating an HTML element dynamically using JavaScript. It takes the element name as the parameter and creates that element node. You need to use the appendChild() method to have the newly created element as part of DOM ." }, { "code": null, "e": 1384, "s": 1331, "text": "Following is the syntax for createElement() method −" }, { "code": null, "e": 1417, "s": 1384, "text": "document.createElement(nodename)" }, { "code": null, "e": 1476, "s": 1417, "text": "Let us look at an example for the createElement() method −" }, { "code": null, "e": 1486, "s": 1476, "text": "Live Demo" }, { "code": null, "e": 1953, "s": 1486, "text": "<!DOCTYPE html>\n<html>\n<body>\n<h1>createElement() example</h1>\n<p>Click the below button to create more buttons</p>\n<button onclick=\"createButton()\">CREATE</button>\n<br><br>\n<script>\n var i=0;\n function createButton() {\n i++;\n var btn = document.createElement(\"BUTTON\");\n btn.innerHTML=\"BUTTON\"+i;\n var br= document.createElement(\"BR\");\n document.body.appendChild(btn);\n document.body.appendChild(br);\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 1994, "s": 1953, "text": "This will produce the following output −" }, { "code": null, "e": 2064, "s": 1994, "text": "On clicking the CREATE button three times. One click for one button −" }, { "code": null, "e": 2087, "s": 2064, "text": "In the above example −" }, { "code": null, "e": 2193, "s": 2087, "text": "We have created a button CREATE that will execute the createButton() method on being clicked by the user." }, { "code": null, "e": 2242, "s": 2193, "text": "<button onclick=\"createButton()\">CREATE</button>" }, { "code": null, "e": 2642, "s": 2242, "text": "The createButton() function creates a <button> element using the createElement() method of the document object. Using the innerHTML, we set the text that will be displayed on the top of the button. We create another element <br> using the createElement() method of the document object. The <button> element and the <br> element are then appended to the document body using the appendChild() method −" }, { "code": null, "e": 2873, "s": 2642, "text": "var i=0;\nfunction createButton() {\n i++;\n var btn = document.createElement(\"BUTTON\");\n btn.innerHTML=\"BUTTON\"+i;\n var br= document.createElement(\"BR\");\n document.body.appendChild(btn);\n document.body.appendChild(br);\n}" } ]
How to read the pixel value from the multichannel image in OpenCV using C++?
We have declared three variables named-'blue_Channel','green_channel' and 'red_channel'. The goals of these variables is to save the pixel values. We have used these variables inside the 'for loops'. Then we declared a matrix named 'color_Image_Matrix'. The syntax of this method is: blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0]; We used a BGR image. It has three channels. These channels maintain specific sequence, color_image_Matrix.at<Vec3b> (i, j) represents the pixel values located at (i,i) and [0] represents the first channel. For example, if we write the line as follows: blue_Channel=color_image_Matrix.at<Vec3b> (30, 35) [0]; It means the variable 'blue_Channel' will have the first channel's pixel value located at(30, 35). This is how we can access the pixel values using OpenCV. The following program reads pixel values of different RGB images and displays the different channel pixel's value in a console window. #include<iostream> #include<opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; int main() { int blue_Channel; int green_Channel; int red_Channel; Mat color_image_Matrix; //Declaring a matrix to load the image// color_image_Matrix = imread("colors.jpg"); //loading image in the matrix// //Beginning of for loop to read pixel values of blue channel// for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// { for (int j = 0; j < color_image_Matrix.cols; j++) { //loop for columns// blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0]; //To read the value of first channel.Here the blue channel is first channel// cout << "Value of pixel of blue channel" << "(" << i << "," << j << ")" << "=" << blue_Channel << endl; //showing the values in console window// } } //End of for loop to read pixel values of blue channel// //Beginning of for loop to read pixel values of green channel// for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// { for (int j = 0; j < color_image_Matrix.cols; j++)//loop for columns// { green_Channel = color_image_Matrix.at<Vec3b>(i, j)[1]; //To read the value of first channel.Here the green channel is first channel// cout << "Value of pixel of green channel" << "(" << i << "," << j << ")" << "=" << blue_Channel << endl;//showing the values in console window// } } //End of for loop to read pixel values of green channel// //Beginning of for loop to read pixel values of red channel// for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// { for (int j = 0; j < color_image_Matrix.cols; j++)//loop for columns// { red_Channel = color_image_Matrix.at<Vec3b>(i, j)[2]; //To read the value of first channel.Here the red channel is first channel// cout << "Value of pixel of red channel" << "(" << i << "," << j << ")" << "=" << blue_Channel << endl; //showing the values in console window// } } //End of for loop to read pixel values of red channel// if (waitKey(0)==27); cout << "Image read successfully...!"; return 0; } Image read successfully... This program takes several minutes to run. It reads each pixel values from different channels. That's why it takes a few minutes to show the complete result.
[ { "code": null, "e": 1316, "s": 1062, "text": "We have declared three variables named-'blue_Channel','green_channel' and 'red_channel'. The goals of these variables is to save the pixel values. We have used these variables inside the 'for loops'. Then we declared a matrix named 'color_Image_Matrix'." }, { "code": null, "e": 1346, "s": 1316, "text": "The syntax of this method is:" }, { "code": null, "e": 1400, "s": 1346, "text": "blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0];" }, { "code": null, "e": 1652, "s": 1400, "text": "We used a BGR image. It has three channels. These channels maintain specific sequence, color_image_Matrix.at<Vec3b> (i, j) represents the pixel values located at (i,i) and [0] represents the first channel. For example, if we write the line as follows:" }, { "code": null, "e": 1708, "s": 1652, "text": "blue_Channel=color_image_Matrix.at<Vec3b> (30, 35) [0];" }, { "code": null, "e": 1864, "s": 1708, "text": "It means the variable 'blue_Channel' will have the first channel's pixel value located at(30, 35). This is how we can access the pixel values using OpenCV." }, { "code": null, "e": 1999, "s": 1864, "text": "The following program reads pixel values of different RGB images and displays the different channel pixel's value in a console window." }, { "code": null, "e": 4230, "s": 1999, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\nusing namespace std;\nusing namespace cv;\nint main() {\n int blue_Channel;\n int green_Channel;\n int red_Channel;\n Mat color_image_Matrix; //Declaring a matrix to load the image//\n color_image_Matrix = imread(\"colors.jpg\"); //loading image in the matrix//\n //Beginning of for loop to read pixel values of blue channel//\n for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// {\n for (int j = 0; j < color_image_Matrix.cols; j++) {\n //loop for columns//\n blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0];\n //To read the value of first channel.Here the blue channel is first channel//\n cout << \"Value of pixel of blue channel\" << \"(\" << i << \",\" << j << \")\" << \"=\"\n << blue_Channel << endl; //showing the values in console window//\n }\n }\n //End of for loop to read pixel values of blue channel//\n //Beginning of for loop to read pixel values of green channel//\n for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// {\n for (int j = 0; j < color_image_Matrix.cols; j++)//loop for columns// {\n green_Channel = color_image_Matrix.at<Vec3b>(i, j)[1];\n //To read the value of first channel.Here the green channel is first channel//\n cout << \"Value of pixel of green channel\" << \"(\" << i << \",\"\n << j << \")\" << \"=\" << blue_Channel << endl;//showing the values in console window//\n }\n }\n //End of for loop to read pixel values of green channel//\n //Beginning of for loop to read pixel values of red channel//\n for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// {\n for (int j = 0; j < color_image_Matrix.cols; j++)//loop for columns// {\n red_Channel = color_image_Matrix.at<Vec3b>(i, j)[2];\n //To read the value of first channel.Here the red channel is first channel//\n cout << \"Value of pixel of red channel\" << \"(\" << i << \",\" <<\n j << \")\" << \"=\" << blue_Channel << endl; //showing the values in console window//\n }\n }\n //End of for loop to read pixel values of red channel//\n if (waitKey(0)==27);\n cout << \"Image read successfully...!\";\n return 0;\n}" }, { "code": null, "e": 4257, "s": 4230, "text": "Image read successfully..." }, { "code": null, "e": 4415, "s": 4257, "text": "This program takes several minutes to run. It reads each pixel values from different channels. That's why it takes a few minutes to show the complete result." } ]
C library function - fmod()
The C library function double fmod(double x, double y) returns the remainder of x divided by y. Following is the declaration for fmod() function. double fmod(double x, double y) x − This is the floating point value with the division numerator i.e. x. x − This is the floating point value with the division numerator i.e. x. y − This is the floating point value with the division denominator i.e. y. y − This is the floating point value with the division denominator i.e. y. This function returns the remainder of dividing x/y. The following example shows the usage of fmod() function. #include <stdio.h> #include <math.h> int main () { float a, b; int c; a = 9.2; b = 3.7; c = 2; printf("Remainder of %f / %d is %lf\n", a, c, fmod(a,c)); printf("Remainder of %f / %f is %lf\n", a, b, fmod(a,b)); return(0); } Let us compile and run the above program that will produce the following result − Remainder of 9.200000 / 2 is 1.200000 Remainder of 9.200000 / 3.700000 is 1.800000 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2103, "s": 2007, "text": "The C library function double fmod(double x, double y) returns the remainder of x divided by y." }, { "code": null, "e": 2153, "s": 2103, "text": "Following is the declaration for fmod() function." }, { "code": null, "e": 2185, "s": 2153, "text": "double fmod(double x, double y)" }, { "code": null, "e": 2258, "s": 2185, "text": "x − This is the floating point value with the division numerator i.e. x." }, { "code": null, "e": 2331, "s": 2258, "text": "x − This is the floating point value with the division numerator i.e. x." }, { "code": null, "e": 2406, "s": 2331, "text": "y − This is the floating point value with the division denominator i.e. y." }, { "code": null, "e": 2481, "s": 2406, "text": "y − This is the floating point value with the division denominator i.e. y." }, { "code": null, "e": 2534, "s": 2481, "text": "This function returns the remainder of dividing x/y." }, { "code": null, "e": 2592, "s": 2534, "text": "The following example shows the usage of fmod() function." }, { "code": null, "e": 2845, "s": 2592, "text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n float a, b;\n int c;\n a = 9.2;\n b = 3.7;\n c = 2;\n printf(\"Remainder of %f / %d is %lf\\n\", a, c, fmod(a,c));\n printf(\"Remainder of %f / %f is %lf\\n\", a, b, fmod(a,b));\n \n return(0);\n}" }, { "code": null, "e": 2927, "s": 2845, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3011, "s": 2927, "text": "Remainder of 9.200000 / 2 is 1.200000\nRemainder of 9.200000 / 3.700000 is 1.800000\n" }, { "code": null, "e": 3044, "s": 3011, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3059, "s": 3044, "text": " Nishant Malik" }, { "code": null, "e": 3094, "s": 3059, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3109, "s": 3094, "text": " Nishant Malik" }, { "code": null, "e": 3144, "s": 3109, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3158, "s": 3144, "text": " Asif Hussain" }, { "code": null, "e": 3191, "s": 3158, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3209, "s": 3191, "text": " Richa Maheshwari" }, { "code": null, "e": 3244, "s": 3209, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3263, "s": 3244, "text": " Vandana Annavaram" }, { "code": null, "e": 3296, "s": 3263, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3308, "s": 3296, "text": " Amit Diwan" }, { "code": null, "e": 3315, "s": 3308, "text": " Print" }, { "code": null, "e": 3326, "s": 3315, "text": " Add Notes" } ]
Sum of rows based on column value in R dataframe - GeeksforGeeks
01 Apr, 2021 In this article, we will be discussing how we can sum up row values based on column value in a data frame in R Programming Language. Suppose you have a data frame like this: fruits shop_1 shop_2 1. Apple 1 13 2. Mango 9 5 3. Strawberry 2 14 4. Apple 10 6 5. Apple 3 15 6. Strawberry 11 7 7. Mango 4 16 8. Strawberry 12 8 This dataset consists of fruits name and shop_1, shop_2 as a column name. Here shop_1 and shop_2 show the number of fruits available in shops. Now you want to find the aggregate sum of all the rows in shope_1 that have the same fruit value. So our dataset looks like this : fruits shop_1 shop_2 1. Apple 14 34 2. Mango 13 21 3. Strawberry 25 29 The aggregate function creates a subset of the original data and computes the statistical function for each subset and returns the result. Syntax: aggregate(.~fruit,data=df,FUN=sum) Example: R # Sum of rows based on column values # Creating dataset # creating fuits columnx <- c("Apple","Mango","Strawberry", "Apple","Apple","Strawberry", "Mango","Strawberry") # creating shop_1 columny <- c(1,9,2,10,3,11,4,12) # creating shop_2 columnz <- c(13,5,14,6,15,7,16,8) # creating dataframedf <- data.frame(fruits=x,shop_1=y,shop_2=z) # applying aggregate functionaggregate(.~fruits,data=df,FUN=sum) Output: Using aggregate function ddply simply split the given data frame and perform any operation on it (probably apply a function) and return the data frame. colwise is a function from the famous plyr package. colwise function is used to compute a function on each column in data frame, it computes column wise. Example: R # Sum of rows based on column values # loading librarylibrary(plyr) # Creating dataset # creating fuits columnx <- c("toy1","toy2","toy3", "toy1","toy1","toy3", "toy2","toy3") # creating stock_1 columny <- c(1,2,3,4,5,6,4,8) # creating stock_2 columnz <- c(9,1,10,5,2,6,4,8) # creating dataframedf <- data.frame(toys=x,stock_1=y,stock_2=z) # using sum function colwiseddply(df,"toys",numcolwise(sum)) Output: Using ddply Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr Logistic Regression in R Programming How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Merge DataFrames by Column Names in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n01 Apr, 2021" }, { "code": null, "e": 25336, "s": 25162, "text": "In this article, we will be discussing how we can sum up row values based on column value in a data frame in R Programming Language. Suppose you have a data frame like this:" }, { "code": null, "e": 25345, "s": 25338, "text": "fruits" }, { "code": null, "e": 25352, "s": 25345, "text": "shop_1" }, { "code": null, "e": 25359, "s": 25352, "text": "shop_2" }, { "code": null, "e": 25362, "s": 25359, "text": "1." }, { "code": null, "e": 25368, "s": 25362, "text": "Apple" }, { "code": null, "e": 25370, "s": 25368, "text": "1" }, { "code": null, "e": 25373, "s": 25370, "text": "13" }, { "code": null, "e": 25376, "s": 25373, "text": "2." }, { "code": null, "e": 25382, "s": 25376, "text": "Mango" }, { "code": null, "e": 25384, "s": 25382, "text": "9" }, { "code": null, "e": 25386, "s": 25384, "text": "5" }, { "code": null, "e": 25389, "s": 25386, "text": "3." }, { "code": null, "e": 25400, "s": 25389, "text": "Strawberry" }, { "code": null, "e": 25402, "s": 25400, "text": "2" }, { "code": null, "e": 25405, "s": 25402, "text": "14" }, { "code": null, "e": 25408, "s": 25405, "text": "4." }, { "code": null, "e": 25414, "s": 25408, "text": "Apple" }, { "code": null, "e": 25417, "s": 25414, "text": "10" }, { "code": null, "e": 25419, "s": 25417, "text": "6" }, { "code": null, "e": 25422, "s": 25419, "text": "5." }, { "code": null, "e": 25428, "s": 25422, "text": "Apple" }, { "code": null, "e": 25430, "s": 25428, "text": "3" }, { "code": null, "e": 25433, "s": 25430, "text": "15" }, { "code": null, "e": 25436, "s": 25433, "text": "6." }, { "code": null, "e": 25447, "s": 25436, "text": "Strawberry" }, { "code": null, "e": 25450, "s": 25447, "text": "11" }, { "code": null, "e": 25452, "s": 25450, "text": "7" }, { "code": null, "e": 25455, "s": 25452, "text": "7." }, { "code": null, "e": 25461, "s": 25455, "text": "Mango" }, { "code": null, "e": 25463, "s": 25461, "text": "4" }, { "code": null, "e": 25466, "s": 25463, "text": "16" }, { "code": null, "e": 25469, "s": 25466, "text": "8." }, { "code": null, "e": 25480, "s": 25469, "text": "Strawberry" }, { "code": null, "e": 25483, "s": 25480, "text": "12" }, { "code": null, "e": 25485, "s": 25483, "text": "8" }, { "code": null, "e": 25759, "s": 25485, "text": "This dataset consists of fruits name and shop_1, shop_2 as a column name. Here shop_1 and shop_2 show the number of fruits available in shops. Now you want to find the aggregate sum of all the rows in shope_1 that have the same fruit value. So our dataset looks like this :" }, { "code": null, "e": 25768, "s": 25761, "text": "fruits" }, { "code": null, "e": 25775, "s": 25768, "text": "shop_1" }, { "code": null, "e": 25782, "s": 25775, "text": "shop_2" }, { "code": null, "e": 25785, "s": 25782, "text": "1." }, { "code": null, "e": 25791, "s": 25785, "text": "Apple" }, { "code": null, "e": 25794, "s": 25791, "text": "14" }, { "code": null, "e": 25797, "s": 25794, "text": "34" }, { "code": null, "e": 25800, "s": 25797, "text": "2." }, { "code": null, "e": 25806, "s": 25800, "text": "Mango" }, { "code": null, "e": 25809, "s": 25806, "text": "13" }, { "code": null, "e": 25812, "s": 25809, "text": "21" }, { "code": null, "e": 25815, "s": 25812, "text": "3." }, { "code": null, "e": 25826, "s": 25815, "text": "Strawberry" }, { "code": null, "e": 25829, "s": 25826, "text": "25" }, { "code": null, "e": 25832, "s": 25829, "text": "29" }, { "code": null, "e": 25971, "s": 25832, "text": "The aggregate function creates a subset of the original data and computes the statistical function for each subset and returns the result." }, { "code": null, "e": 25979, "s": 25971, "text": "Syntax:" }, { "code": null, "e": 26014, "s": 25979, "text": "aggregate(.~fruit,data=df,FUN=sum)" }, { "code": null, "e": 26023, "s": 26014, "text": "Example:" }, { "code": null, "e": 26025, "s": 26023, "text": "R" }, { "code": "# Sum of rows based on column values # Creating dataset # creating fuits columnx <- c(\"Apple\",\"Mango\",\"Strawberry\", \"Apple\",\"Apple\",\"Strawberry\", \"Mango\",\"Strawberry\") # creating shop_1 columny <- c(1,9,2,10,3,11,4,12) # creating shop_2 columnz <- c(13,5,14,6,15,7,16,8) # creating dataframedf <- data.frame(fruits=x,shop_1=y,shop_2=z) # applying aggregate functionaggregate(.~fruits,data=df,FUN=sum)", "e": 26443, "s": 26025, "text": null }, { "code": null, "e": 26451, "s": 26443, "text": "Output:" }, { "code": null, "e": 26476, "s": 26451, "text": "Using aggregate function" }, { "code": null, "e": 26606, "s": 26476, "text": "ddply simply split the given data frame and perform any operation on it (probably apply a function) and return the data frame." }, { "code": null, "e": 26760, "s": 26606, "text": "colwise is a function from the famous plyr package. colwise function is used to compute a function on each column in data frame, it computes column wise." }, { "code": null, "e": 26769, "s": 26760, "text": "Example:" }, { "code": null, "e": 26771, "s": 26769, "text": "R" }, { "code": "# Sum of rows based on column values # loading librarylibrary(plyr) # Creating dataset # creating fuits columnx <- c(\"toy1\",\"toy2\",\"toy3\", \"toy1\",\"toy1\",\"toy3\", \"toy2\",\"toy3\") # creating stock_1 columny <- c(1,2,3,4,5,6,4,8) # creating stock_2 columnz <- c(9,1,10,5,2,6,4,8) # creating dataframedf <- data.frame(toys=x,stock_1=y,stock_2=z) # using sum function colwiseddply(df,\"toys\",numcolwise(sum))", "e": 27190, "s": 26771, "text": null }, { "code": null, "e": 27199, "s": 27190, "text": "Output: " }, { "code": null, "e": 27211, "s": 27199, "text": "Using ddply" }, { "code": null, "e": 27218, "s": 27211, "text": "Picked" }, { "code": null, "e": 27239, "s": 27218, "text": "R DataFrame-Programs" }, { "code": null, "e": 27251, "s": 27239, "text": "R-DataFrame" }, { "code": null, "e": 27262, "s": 27251, "text": "R Language" }, { "code": null, "e": 27273, "s": 27262, "text": "R Programs" }, { "code": null, "e": 27371, "s": 27273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27380, "s": 27371, "text": "Comments" }, { "code": null, "e": 27393, "s": 27380, "text": "Old Comments" }, { "code": null, "e": 27445, "s": 27393, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27469, "s": 27445, "text": "Data Visualization in R" }, { "code": null, "e": 27507, "s": 27469, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27542, "s": 27507, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27579, "s": 27542, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27637, "s": 27579, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27680, "s": 27637, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27729, "s": 27680, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27779, "s": 27729, "text": "How to filter R dataframe by multiple conditions?" } ]
Java program to calculate mean of given numbers
Mean is an average value of given set of numbers. It is calculated similarly to that of the average value. Adding all given number together and then dividing them by the total number of values produces mean. For Example Mean of 3, 5, 2, 7, 3 is (3 + 5 + 2 + 7 + 3) / 5 = 4 Take an integer set A of n values. Add all values of A together. Divide result of Step 2 by n. The result is mean of A's values. public class CaculatingMean { public static void main(String args[]){ float mean; int sum, i; int n = 5; int a[] = {2,6,7,4,9}; sum = 0; for(i = 0; i < n; i++) { sum+=a[i]; } System.out.println("Mean ::"+ sum/(float)n); } } Mean::5.6
[ { "code": null, "e": 1270, "s": 1062, "text": "Mean is an average value of given set of numbers. It is calculated similarly to that of the average value. Adding all given number together and then dividing them by the total number of values produces mean." }, { "code": null, "e": 1283, "s": 1270, "text": "For Example " }, { "code": null, "e": 1336, "s": 1283, "text": "Mean of 3, 5, 2, 7, 3 is (3 + 5 + 2 + 7 + 3) / 5 = 4" }, { "code": null, "e": 1371, "s": 1336, "text": "Take an integer set A of n values." }, { "code": null, "e": 1401, "s": 1371, "text": "Add all values of A together." }, { "code": null, "e": 1431, "s": 1401, "text": "Divide result of Step 2 by n." }, { "code": null, "e": 1465, "s": 1431, "text": "The result is mean of A's values." }, { "code": null, "e": 1753, "s": 1465, "text": "public class CaculatingMean {\n public static void main(String args[]){\n float mean;\n int sum, i;\n int n = 5;\n int a[] = {2,6,7,4,9};\n sum = 0;\n\n for(i = 0; i < n; i++) {\n sum+=a[i];\n }\n System.out.println(\"Mean ::\"+ sum/(float)n);\n }\n}" }, { "code": null, "e": 1763, "s": 1753, "text": "Mean::5.6" } ]
How to call private method from another class in Java with help of Reflection API? - GeeksforGeeks
17 Jun, 2019 We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API. To call the private method, we will use following methods of Java.lang.class and Java.lang.reflect.Method Method[] getDeclaredMethods(): This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object. setAccessible(): Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks. invoke():It invokes the underlying method represented by this Method object, on the specified object with the specified parameters.Below programs demonstrates calling of private method in Java:Example 1: When the name of private function is known already.// Java program to call// private method of a// class from another class import Java.lang.reflect.Method; // The class containing// a private method and// a public methodclass Check { // Private method private void private_Method() { System.out.println("Private Method " + "called from outside"); } // Public method public void printData() { System.out.println("Public Method"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); // Using getDeclareMethod() method Method m = Check.class .getDeclaredMethod("private_Method"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); }}Output:Example 2: When the name of private function is not known but class name is known.// Java program to call private method// of a class from another class import Java.lang.reflect.Method; // The class contains a private methodclass Check { // Private method private void Demo_private_Method() { System.out.println("Private Method " + "called from outside"); } // Public method public void printData() { System.out.println("Public Method"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); Method m; // Using getDeclareMethod() method Method method[] = Check.class.getDeclaredMethods(); for (int i = 0; i < method.length; i++) { String meth = new String(method[i].toString()); if (meth.startsWith("private")) { String s = method[i].toString(); int a = s.indexOf("."); int b = s.indexOf("("); // Method name retrieved String method_name = s.substring(a + 1, b); // Print method name System.out.println("Method Name = " + method_name); // Using getDeclareMethod() method m = Check.class.getDeclaredMethod(method_name); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); } } }}Output:My Personal Notes arrow_drop_upSave Below programs demonstrates calling of private method in Java: Example 1: When the name of private function is known already.// Java program to call// private method of a// class from another class import Java.lang.reflect.Method; // The class containing// a private method and// a public methodclass Check { // Private method private void private_Method() { System.out.println("Private Method " + "called from outside"); } // Public method public void printData() { System.out.println("Public Method"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); // Using getDeclareMethod() method Method m = Check.class .getDeclaredMethod("private_Method"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); }}Output: // Java program to call// private method of a// class from another class import Java.lang.reflect.Method; // The class containing// a private method and// a public methodclass Check { // Private method private void private_Method() { System.out.println("Private Method " + "called from outside"); } // Public method public void printData() { System.out.println("Public Method"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); // Using getDeclareMethod() method Method m = Check.class .getDeclaredMethod("private_Method"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); }} Example 2: When the name of private function is not known but class name is known.// Java program to call private method// of a class from another class import Java.lang.reflect.Method; // The class contains a private methodclass Check { // Private method private void Demo_private_Method() { System.out.println("Private Method " + "called from outside"); } // Public method public void printData() { System.out.println("Public Method"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); Method m; // Using getDeclareMethod() method Method method[] = Check.class.getDeclaredMethods(); for (int i = 0; i < method.length; i++) { String meth = new String(method[i].toString()); if (meth.startsWith("private")) { String s = method[i].toString(); int a = s.indexOf("."); int b = s.indexOf("("); // Method name retrieved String method_name = s.substring(a + 1, b); // Print method name System.out.println("Method Name = " + method_name); // Using getDeclareMethod() method m = Check.class.getDeclaredMethod(method_name); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); } } }}Output: // Java program to call private method// of a class from another class import Java.lang.reflect.Method; // The class contains a private methodclass Check { // Private method private void Demo_private_Method() { System.out.println("Private Method " + "called from outside"); } // Public method public void printData() { System.out.println("Public Method"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); Method m; // Using getDeclareMethod() method Method method[] = Check.class.getDeclaredMethods(); for (int i = 0; i < method.length; i++) { String meth = new String(method[i].toString()); if (meth.startsWith("private")) { String s = method[i].toString(); int a = s.indexOf("."); int b = s.indexOf("("); // Method name retrieved String method_name = s.substring(a + 1, b); // Print method name System.out.println("Method Name = " + method_name); // Using getDeclareMethod() method m = Check.class.getDeclaredMethod(method_name); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); } } }} access modifiers Java-Functions java-lang-reflect-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26429, "s": 26401, "text": "\n17 Jun, 2019" }, { "code": null, "e": 26561, "s": 26429, "text": "We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java)." }, { "code": null, "e": 26740, "s": 26561, "text": "We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API." }, { "code": null, "e": 26846, "s": 26740, "text": "To call the private method, we will use following methods of Java.lang.class and Java.lang.reflect.Method" }, { "code": null, "e": 27017, "s": 26846, "text": "Method[] getDeclaredMethods(): This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object." }, { "code": null, "e": 27318, "s": 27017, "text": "setAccessible(): Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks." }, { "code": null, "e": 30080, "s": 27318, "text": "invoke():It invokes the underlying method represented by this Method object, on the specified object with the specified parameters.Below programs demonstrates calling of private method in Java:Example 1: When the name of private function is known already.// Java program to call// private method of a// class from another class import Java.lang.reflect.Method; // The class containing// a private method and// a public methodclass Check { // Private method private void private_Method() { System.out.println(\"Private Method \" + \"called from outside\"); } // Public method public void printData() { System.out.println(\"Public Method\"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); // Using getDeclareMethod() method Method m = Check.class .getDeclaredMethod(\"private_Method\"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); }}Output:Example 2: When the name of private function is not known but class name is known.// Java program to call private method// of a class from another class import Java.lang.reflect.Method; // The class contains a private methodclass Check { // Private method private void Demo_private_Method() { System.out.println(\"Private Method \" + \"called from outside\"); } // Public method public void printData() { System.out.println(\"Public Method\"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); Method m; // Using getDeclareMethod() method Method method[] = Check.class.getDeclaredMethods(); for (int i = 0; i < method.length; i++) { String meth = new String(method[i].toString()); if (meth.startsWith(\"private\")) { String s = method[i].toString(); int a = s.indexOf(\".\"); int b = s.indexOf(\"(\"); // Method name retrieved String method_name = s.substring(a + 1, b); // Print method name System.out.println(\"Method Name = \" + method_name); // Using getDeclareMethod() method m = Check.class.getDeclaredMethod(method_name); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); } } }}Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30143, "s": 30080, "text": "Below programs demonstrates calling of private method in Java:" }, { "code": null, "e": 31059, "s": 30143, "text": "Example 1: When the name of private function is known already.// Java program to call// private method of a// class from another class import Java.lang.reflect.Method; // The class containing// a private method and// a public methodclass Check { // Private method private void private_Method() { System.out.println(\"Private Method \" + \"called from outside\"); } // Public method public void printData() { System.out.println(\"Public Method\"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); // Using getDeclareMethod() method Method m = Check.class .getDeclaredMethod(\"private_Method\"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); }}Output:" }, { "code": "// Java program to call// private method of a// class from another class import Java.lang.reflect.Method; // The class containing// a private method and// a public methodclass Check { // Private method private void private_Method() { System.out.println(\"Private Method \" + \"called from outside\"); } // Public method public void printData() { System.out.println(\"Public Method\"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); // Using getDeclareMethod() method Method m = Check.class .getDeclaredMethod(\"private_Method\"); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); }}", "e": 31906, "s": 31059, "text": null }, { "code": null, "e": 33525, "s": 31906, "text": "Example 2: When the name of private function is not known but class name is known.// Java program to call private method// of a class from another class import Java.lang.reflect.Method; // The class contains a private methodclass Check { // Private method private void Demo_private_Method() { System.out.println(\"Private Method \" + \"called from outside\"); } // Public method public void printData() { System.out.println(\"Public Method\"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); Method m; // Using getDeclareMethod() method Method method[] = Check.class.getDeclaredMethods(); for (int i = 0; i < method.length; i++) { String meth = new String(method[i].toString()); if (meth.startsWith(\"private\")) { String s = method[i].toString(); int a = s.indexOf(\".\"); int b = s.indexOf(\"(\"); // Method name retrieved String method_name = s.substring(a + 1, b); // Print method name System.out.println(\"Method Name = \" + method_name); // Using getDeclareMethod() method m = Check.class.getDeclaredMethod(method_name); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); } } }}Output:" }, { "code": "// Java program to call private method// of a class from another class import Java.lang.reflect.Method; // The class contains a private methodclass Check { // Private method private void Demo_private_Method() { System.out.println(\"Private Method \" + \"called from outside\"); } // Public method public void printData() { System.out.println(\"Public Method\"); }} // Driver codeclass GFG { public static void main(String[] args) throws Exception { Check c = new Check(); Method m; // Using getDeclareMethod() method Method method[] = Check.class.getDeclaredMethods(); for (int i = 0; i < method.length; i++) { String meth = new String(method[i].toString()); if (meth.startsWith(\"private\")) { String s = method[i].toString(); int a = s.indexOf(\".\"); int b = s.indexOf(\"(\"); // Method name retrieved String method_name = s.substring(a + 1, b); // Print method name System.out.println(\"Method Name = \" + method_name); // Using getDeclareMethod() method m = Check.class.getDeclaredMethod(method_name); // Using setAccessible() method m.setAccessible(true); // Using invoke() method m.invoke(c); } } }}", "e": 35055, "s": 33525, "text": null }, { "code": null, "e": 35072, "s": 35055, "text": "access modifiers" }, { "code": null, "e": 35087, "s": 35072, "text": "Java-Functions" }, { "code": null, "e": 35113, "s": 35087, "text": "java-lang-reflect-package" }, { "code": null, "e": 35118, "s": 35113, "text": "Java" }, { "code": null, "e": 35123, "s": 35118, "text": "Java" }, { "code": null, "e": 35221, "s": 35123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35272, "s": 35221, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 35302, "s": 35272, "text": "HashMap in Java with Examples" }, { "code": null, "e": 35317, "s": 35302, "text": "Stream In Java" }, { "code": null, "e": 35336, "s": 35317, "text": "Interfaces in Java" }, { "code": null, "e": 35367, "s": 35336, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35399, "s": 35367, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 35417, "s": 35399, "text": "ArrayList in Java" }, { "code": null, "e": 35437, "s": 35417, "text": "Stack Class in Java" }, { "code": null, "e": 35461, "s": 35437, "text": "Singleton Class in Java" } ]
A Practical Guide to ARIMA Models using PyCaret — Part 2 | by Nikhil Gupta | Towards Data Science
In the previous article, we saw a brief overview of the ARIMA model and its various hyperparameters. We started with a very simple ARIMA model, one that does not exhibit and temporal dependence. This article will look at the “trend” component of the ARIMA model and see how this is modeled and what it represents. The previous article in this series can be found below. I would recommend that readers go through it first before continuing with this article. This article builds upon the concepts described in the previous one as well as reuses some work done in it. A Practical Guide to ARIMA Models using PyCaret — Part 1 As the name suggests, a trend determines how a time series changes over time. In ARIMA models, this can be modeled using the following underlying equation [1]. “a” is called the “intercept” and “b” is called the “drift” term. “Drift” is nothing but the slope of a straight line. There are several ways in which the trend can be modeled using this equation. (1) A trend component that does not change with time. In this case, drift “b” = 0. (2) A trend component that starts from 0 and linearly changes with time (zero intercept “a” and non-zero slope/drift “b”). (3) A trend component that does not start from 0 and linearly change with time (non-zero intercept “a” and non-zero slope/drift “b”). To understand this concept better, we will use the same dataset that we used in the last part of this series. As a refresher, this dataset was a “white noise” dataset. Details can be found in the Jupyter notebook for this article (available at the end of the article). 👉 Step 1 & 2: Setup PyCaret Time Series Experiment and Perform EDA Since we have already performed these steps in the previous article, we will not go over them again. Please refer to the previous article for details. 👉 Step 3: Theoretical Calculations As mentioned above, “trend” in ARIMA models can be calculated in 3 ways. (1) The first method where the trend component is fixed is the same as the model that was covered in the previous article. Hence the same theoretical calculations apply in this case as well. As a refresher, the estimate of the predictions (both in-sample and out-of-sample) was the mean of the training dataset (i.e. “a” = 176.02). The estimate of the prediction interval was 174.08–177.96. (2) The second method models the trend component as a straight line with intercept “a”= 0. In order to model this theoretically, we can recreate this using scikit-learn’s Linear Regression model. When we eventually model this using an ARIMA model, we would expect to see the same results. X_train = np.arange(len(y_train)).reshape(-1, 1)reg = LinearRegression(fit_intercept=False).fit(X_train, y_train)print(f"Expected Intercept: {reg.intercept_}")print(f"Expected Slope: {reg.coef_}")>>> Expected Intercept: 0.0>>> Expected Slope: [0.85317393] (3) The third method models the trend component as a straight line with intercept “a” which is not 0. We can again recreate this using scikit-learn as follows. X_train = np.arange(len(y_train)).reshape(-1, 1)reg = LinearRegression(fit_intercept=True).fit(X_train, y_train)print(f"Expected Intercept: {reg.intercept_}")print(f"Expected Slope: {reg.coef_}")>>> Expected Intercept: 175.95815015173943>>> Expected Slope: [0.00038807] 👉 Step 4: Build the Models Now, that we have covered the theoretical calculations, let’s see these models in practice. # Trend with method 1 ----model2a = exp.create_model( "arima", order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend="c")# Trend with method 2 ----model2b = exp.create_model( "arima", order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend="t")# Trend with method 3 ----model2c = exp.create_model( "arima", order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend="ct") 👉 Step 5: Analyze the Results We will reuse the same helper functions that we created in the previous article to analyze the results. Method 1: trend = “c” summarize_model(model2a)get_residual_properties(model2a) These results match with our theoretical calculations and are exactly same as those in the previous article. We will not cover them in detail again. You can refer to the underlying Jupyter Notebook at the end of this article for more details. Method 2: trend = “t” summarize_model(model2b)get_residual_properties(model2b) As we can see the drift from the model (0.8532) matches with theoretical calculation using scikit-learn. Similarly, the residual Sigma2 (~ 7777) manual calculation matches the calculations in the model. One thing to note is that this is not a good model for this dataset since the unexplained variance (sigma2) is much higher than before). Let’s also look at the forecasts. plot_predictions(model2b) We can see that the forecast (in-sample) starts from close to 0 and increases linearly. PyCaret provides interactive plots so users can zoom into sections of the forecasts to analyze them in greater detail. For example, one could hover over consecutive points and notice that they differ by exactly the drift value of 0.8532. The out-of-sample forecasts are a continuation of the in-sample forecasts and again rise linearly with a slope/drift of 0.8532. A slight nuance for the sharp eyed observer. The first in-sample forecast is not 0. It starts at the value of 0.8532 (the drift value). Could you explain why? Method 3: trend = “ct” summarize_model(model2c)get_residual_properties(model2c) As we can see the intercept (175.9578) and drift (0.0004) from the model matches with theoretical calculation using scikit-learn. The drift being so close to 0 is expected since this is white noise data. Also, we can see that there is almost no difference in the “goodness of fit” (lower sigma2 = better fit) between this model and the model from Method 1. Let’s also look at the forecasts. They should look very much like the ones from method 1 with the exception of the small slope/drift component. Again, the interactive plots in PyCaret allow for easy examination of the results as shown in the zoomed results below. Also, it may be obvious, but it is worth noting explicitly that although both Method 1 and Method 3 gave similar fit in this case (given that the data was white noise), this is not always the case. When the data exhibits a linear trend, Method 3 will generally give a better fit compared to Method 1. I would encourage the readers to create a dummy linear dataset and try this out. Hopefully this simple model has laid a good foundation for us to understand the inner workings of the trend component of an ARIMA model. In the next set of articles, we will start covering the other parameters one by one and see the impact that they have on the model’s behavior. Until then, if you would like to connect with me on my social channels (I post about Time Series Analysis frequently), you can find me below. That’s it for now. Happy forecasting! 🔗 LinkedIn 🐦 Twitter 📘 GitHub Jupyter Notebook containing the code for this article Jupyter Notebook containing the code for this article [1] Constants and ARIMA models in R, Hyndsight [2] Chapter 8 ARIMA Models, Forecasting: Principles and Practice, Rob J Hyndman and George Athanasopoulos
[ { "code": null, "e": 361, "s": 47, "text": "In the previous article, we saw a brief overview of the ARIMA model and its various hyperparameters. We started with a very simple ARIMA model, one that does not exhibit and temporal dependence. This article will look at the “trend” component of the ARIMA model and see how this is modeled and what it represents." }, { "code": null, "e": 613, "s": 361, "text": "The previous article in this series can be found below. I would recommend that readers go through it first before continuing with this article. This article builds upon the concepts described in the previous one as well as reuses some work done in it." }, { "code": null, "e": 670, "s": 613, "text": "A Practical Guide to ARIMA Models using PyCaret — Part 1" }, { "code": null, "e": 949, "s": 670, "text": "As the name suggests, a trend determines how a time series changes over time. In ARIMA models, this can be modeled using the following underlying equation [1]. “a” is called the “intercept” and “b” is called the “drift” term. “Drift” is nothing but the slope of a straight line." }, { "code": null, "e": 1027, "s": 949, "text": "There are several ways in which the trend can be modeled using this equation." }, { "code": null, "e": 1110, "s": 1027, "text": "(1) A trend component that does not change with time. In this case, drift “b” = 0." }, { "code": null, "e": 1233, "s": 1110, "text": "(2) A trend component that starts from 0 and linearly changes with time (zero intercept “a” and non-zero slope/drift “b”)." }, { "code": null, "e": 1367, "s": 1233, "text": "(3) A trend component that does not start from 0 and linearly change with time (non-zero intercept “a” and non-zero slope/drift “b”)." }, { "code": null, "e": 1636, "s": 1367, "text": "To understand this concept better, we will use the same dataset that we used in the last part of this series. As a refresher, this dataset was a “white noise” dataset. Details can be found in the Jupyter notebook for this article (available at the end of the article)." }, { "code": null, "e": 1703, "s": 1636, "text": "👉 Step 1 & 2: Setup PyCaret Time Series Experiment and Perform EDA" }, { "code": null, "e": 1854, "s": 1703, "text": "Since we have already performed these steps in the previous article, we will not go over them again. Please refer to the previous article for details." }, { "code": null, "e": 1889, "s": 1854, "text": "👉 Step 3: Theoretical Calculations" }, { "code": null, "e": 1962, "s": 1889, "text": "As mentioned above, “trend” in ARIMA models can be calculated in 3 ways." }, { "code": null, "e": 2353, "s": 1962, "text": "(1) The first method where the trend component is fixed is the same as the model that was covered in the previous article. Hence the same theoretical calculations apply in this case as well. As a refresher, the estimate of the predictions (both in-sample and out-of-sample) was the mean of the training dataset (i.e. “a” = 176.02). The estimate of the prediction interval was 174.08–177.96." }, { "code": null, "e": 2642, "s": 2353, "text": "(2) The second method models the trend component as a straight line with intercept “a”= 0. In order to model this theoretically, we can recreate this using scikit-learn’s Linear Regression model. When we eventually model this using an ARIMA model, we would expect to see the same results." }, { "code": null, "e": 2898, "s": 2642, "text": "X_train = np.arange(len(y_train)).reshape(-1, 1)reg = LinearRegression(fit_intercept=False).fit(X_train, y_train)print(f\"Expected Intercept: {reg.intercept_}\")print(f\"Expected Slope: {reg.coef_}\")>>> Expected Intercept: 0.0>>> Expected Slope: [0.85317393]" }, { "code": null, "e": 3058, "s": 2898, "text": "(3) The third method models the trend component as a straight line with intercept “a” which is not 0. We can again recreate this using scikit-learn as follows." }, { "code": null, "e": 3328, "s": 3058, "text": "X_train = np.arange(len(y_train)).reshape(-1, 1)reg = LinearRegression(fit_intercept=True).fit(X_train, y_train)print(f\"Expected Intercept: {reg.intercept_}\")print(f\"Expected Slope: {reg.coef_}\")>>> Expected Intercept: 175.95815015173943>>> Expected Slope: [0.00038807]" }, { "code": null, "e": 3355, "s": 3328, "text": "👉 Step 4: Build the Models" }, { "code": null, "e": 3447, "s": 3355, "text": "Now, that we have covered the theoretical calculations, let’s see these models in practice." }, { "code": null, "e": 3842, "s": 3447, "text": "# Trend with method 1 ----model2a = exp.create_model( \"arima\", order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend=\"c\")# Trend with method 2 ----model2b = exp.create_model( \"arima\", order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend=\"t\")# Trend with method 3 ----model2c = exp.create_model( \"arima\", order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend=\"ct\")" }, { "code": null, "e": 3872, "s": 3842, "text": "👉 Step 5: Analyze the Results" }, { "code": null, "e": 3976, "s": 3872, "text": "We will reuse the same helper functions that we created in the previous article to analyze the results." }, { "code": null, "e": 3998, "s": 3976, "text": "Method 1: trend = “c”" }, { "code": null, "e": 4055, "s": 3998, "text": "summarize_model(model2a)get_residual_properties(model2a)" }, { "code": null, "e": 4298, "s": 4055, "text": "These results match with our theoretical calculations and are exactly same as those in the previous article. We will not cover them in detail again. You can refer to the underlying Jupyter Notebook at the end of this article for more details." }, { "code": null, "e": 4320, "s": 4298, "text": "Method 2: trend = “t”" }, { "code": null, "e": 4377, "s": 4320, "text": "summarize_model(model2b)get_residual_properties(model2b)" }, { "code": null, "e": 4482, "s": 4377, "text": "As we can see the drift from the model (0.8532) matches with theoretical calculation using scikit-learn." }, { "code": null, "e": 4751, "s": 4482, "text": "Similarly, the residual Sigma2 (~ 7777) manual calculation matches the calculations in the model. One thing to note is that this is not a good model for this dataset since the unexplained variance (sigma2) is much higher than before). Let’s also look at the forecasts." }, { "code": null, "e": 4777, "s": 4751, "text": "plot_predictions(model2b)" }, { "code": null, "e": 5103, "s": 4777, "text": "We can see that the forecast (in-sample) starts from close to 0 and increases linearly. PyCaret provides interactive plots so users can zoom into sections of the forecasts to analyze them in greater detail. For example, one could hover over consecutive points and notice that they differ by exactly the drift value of 0.8532." }, { "code": null, "e": 5231, "s": 5103, "text": "The out-of-sample forecasts are a continuation of the in-sample forecasts and again rise linearly with a slope/drift of 0.8532." }, { "code": null, "e": 5390, "s": 5231, "text": "A slight nuance for the sharp eyed observer. The first in-sample forecast is not 0. It starts at the value of 0.8532 (the drift value). Could you explain why?" }, { "code": null, "e": 5413, "s": 5390, "text": "Method 3: trend = “ct”" }, { "code": null, "e": 5470, "s": 5413, "text": "summarize_model(model2c)get_residual_properties(model2c)" }, { "code": null, "e": 5827, "s": 5470, "text": "As we can see the intercept (175.9578) and drift (0.0004) from the model matches with theoretical calculation using scikit-learn. The drift being so close to 0 is expected since this is white noise data. Also, we can see that there is almost no difference in the “goodness of fit” (lower sigma2 = better fit) between this model and the model from Method 1." }, { "code": null, "e": 6091, "s": 5827, "text": "Let’s also look at the forecasts. They should look very much like the ones from method 1 with the exception of the small slope/drift component. Again, the interactive plots in PyCaret allow for easy examination of the results as shown in the zoomed results below." }, { "code": null, "e": 6473, "s": 6091, "text": "Also, it may be obvious, but it is worth noting explicitly that although both Method 1 and Method 3 gave similar fit in this case (given that the data was white noise), this is not always the case. When the data exhibits a linear trend, Method 3 will generally give a better fit compared to Method 1. I would encourage the readers to create a dummy linear dataset and try this out." }, { "code": null, "e": 6933, "s": 6473, "text": "Hopefully this simple model has laid a good foundation for us to understand the inner workings of the trend component of an ARIMA model. In the next set of articles, we will start covering the other parameters one by one and see the impact that they have on the model’s behavior. Until then, if you would like to connect with me on my social channels (I post about Time Series Analysis frequently), you can find me below. That’s it for now. Happy forecasting!" }, { "code": null, "e": 6944, "s": 6933, "text": "🔗 LinkedIn" }, { "code": null, "e": 6954, "s": 6944, "text": "🐦 Twitter" }, { "code": null, "e": 6963, "s": 6954, "text": "📘 GitHub" }, { "code": null, "e": 7017, "s": 6963, "text": "Jupyter Notebook containing the code for this article" }, { "code": null, "e": 7071, "s": 7017, "text": "Jupyter Notebook containing the code for this article" }, { "code": null, "e": 7118, "s": 7071, "text": "[1] Constants and ARIMA models in R, Hyndsight" } ]
C++ program to Reverse a Sentence Using Recursion
A string is a one dimensional character array that is terminated by a null character. The reverse of a string is the same string in opposite order. For example. Original String: Apple is red Reversed String: der si elppA A program that reverses a sentence in the form of a string using recursion is given as follows. Live Demo #include <iostream> using namespace std; void reverse(char *str) { if(*str == '\0') return; else { reverse(str+1); cout<<*str; } } int main() { char str[] = "C++ is fun"; cout<<"Original String: "<<str<<endl; cout<<"Reversed String: "; reverse(str); return 0; } Original String: C++ is fun Reversed String: nuf si ++C In the above program, the function reverse() is a recursive function that reverses a string. Initially reverse() accepts *str which is a pointer that points to the start of the string. If the value is null, then the function returns. If not, then the function recursively calls itself with the value str+1 i.e the next element in the string. Eventually, when str is null, the values of str are printed for back to front. So, the reversed string is printed. This is shown by the following code snippet. if(*str == '\0') return; else { reverse(str+1); cout<<*str; } In the main() function, the string is initialized. Also, the original string and the reversed string are displayed. This is shown as follows − char str[] = "C++ is fun"; cout<<"Original String: "<<str<<endl; cout<<"Reversed String: "; reverse(str);
[ { "code": null, "e": 1223, "s": 1062, "text": "A string is a one dimensional character array that is terminated by a null character. The reverse of a string is the same string in opposite order. For example." }, { "code": null, "e": 1283, "s": 1223, "text": "Original String: Apple is red\nReversed String: der si elppA" }, { "code": null, "e": 1379, "s": 1283, "text": "A program that reverses a sentence in the form of a string using recursion is given as follows." }, { "code": null, "e": 1390, "s": 1379, "text": " Live Demo" }, { "code": null, "e": 1691, "s": 1390, "text": "#include <iostream>\nusing namespace std;\nvoid reverse(char *str) {\n if(*str == '\\0')\n return;\n else {\n reverse(str+1);\n cout<<*str;\n }\n}\nint main() {\n char str[] = \"C++ is fun\";\n cout<<\"Original String: \"<<str<<endl;\n cout<<\"Reversed String: \";\n reverse(str);\n return 0;\n}" }, { "code": null, "e": 1747, "s": 1691, "text": "Original String: C++ is fun\nReversed String: nuf si ++C" }, { "code": null, "e": 1840, "s": 1747, "text": "In the above program, the function reverse() is a recursive function that reverses a string." }, { "code": null, "e": 2249, "s": 1840, "text": "Initially reverse() accepts *str which is a pointer that points to the start of the string. If the value is null, then the function returns. If not, then the function recursively calls itself with the value str+1 i.e the next element in the string. Eventually, when str is null, the values of str are printed for back to front. So, the reversed string is printed. This is shown by the following code snippet." }, { "code": null, "e": 2332, "s": 2249, "text": "if(*str == '\\0')\n return;\n else {\n reverse(str+1);\n cout<<*str;\n }" }, { "code": null, "e": 2475, "s": 2332, "text": "In the main() function, the string is initialized. Also, the original string and the reversed string are displayed. This is shown as follows −" }, { "code": null, "e": 2581, "s": 2475, "text": "char str[] = \"C++ is fun\";\ncout<<\"Original String: \"<<str<<endl;\ncout<<\"Reversed String: \";\nreverse(str);" } ]
How to dynamically create new elements in JavaScript ? - GeeksforGeeks
05 Jun, 2020 New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method. The examples given below would demonstrate this approach. Example 1: In this example, a newly created element is added as a child to the parent element. The type of the element to be created is specified and its value or text node for the specified element is added. HTML <!DOCTYPE HTML><html> <head> <title> How to dynamically create new elements in JavaScript? </title></head> <body> <h1 style="text-align:center; color:green;"> GeeksForGeeks </h1> <!-- Form to add item --> <form action="#" style="text-align:center;"> <!-- Type of Element --> <label for="type"> Add Element Type </label> <input type="text" id="type" placeholder="Like: div, h1, li...." value="li" /> <br /><br /> <!-- Text/Value for the element ---> <label for="value"> Add Element Value </label> <input type="text" id="value" placeholder="Like: Hello GeeksForGeeks" value="CHILD 2" /> <br /><br /> <!-- Submit the Form --> <button type="button" onClick="addItem()"> Add </button> </form> <!-- Parent tag where we add item as child --> <ol id="parent"> <li>List Item 1</li> </ol> <script> // Define the addItem() function // to be called through onclick function addItem() { // Get type of element from form let type = document. getElementById("type").value; // Get the text/value for the tag // from the form let value = document. getElementById("value").value; // createElement() is used for // creating a new element type = document.createElement(type); // Use value as textnode in this example type.appendChild( document.createTextNode(value)); // Append as child to the parent // tag i.e. ol document.getElementById( "parent").appendChild(type); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, a newly created element along with its attributes is added to the body element of the page. The attributes can only be entered using two arguments i.e. type of attribute and the value of the attribute. The CSS for the “child” item is added for convenience. html <!DOCTYPE HTML><html> <head> <title> How to dynamically create new elements in JavaScript? </title> <style> /* CSS for child item */ .child { color: white; background-color: green; } </style></head> <body id="body"> <h1 style="text-align:center; color:green;"> GeeksForGeeks </h1> <!-- Form to add item --> <form action="#" style="text-align: center;"> <!-- Type of element --> <label for="type"> Add Element Type </label> <input type="text" id="type" placeholder="Like: div, h1, li...." value="h3" /> <br /><br /> <!-- Text/value for element ---> <label for="value"> Add Element Value</label> <input type="text" id="value" placeholder="Like: Hello GeeksForGeeks" value="Hello GeeksForGeeks" /> <br /><br /> <!-- Add attributes for element ---> <label for="attr"> Add Attributes</label> <form id="attr"> <label for="attrType">Add Attribute Type</label> <input type="text" style="width:240px;" placeholder="forexample: enter 'class' without quotes" id="attrType" value="class" /> <br /> <br /> <label for="attrValue"> Add Attribute Value </label> <input style="width:240px;" type="text" placeholder="for example: enter 'child' without quotes" id="attrValue" value="child" /> </form> <br /><br /> <!-- Submit the form --> <button type="button" onClick="addItem()"> Add </button> </form> <div> <p>CHILD 1</p> </div> <script> // Define the addItem function // to be called through onclick() function addItem() { // Get Elements by id of the form inputs let parent = document.getElementById("body"); let attrType = document.getElementById("attrType"); let attrValue = document.getElementById("attrValue"); let type = document.getElementById("type"); let value = document.getElementById("value"); if (type.value == "" || value.value == "") { window.alert( "There is an error in form input"); window.reload(); } // createElement() method is used // to create a new element type = document.createElement(type.value); // Append a text node for this example type.appendChild( document.createTextNode(value.value)); if (attrValue.value == "" || attrType.value == "") { attr = null; } else { // setAttribute() is used to set // the attributes of the element type.setAttribute( attrType.value, attrValue.value); } // Append as child to the parent // i.e. body parent.appendChild(type); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26081, "s": 26053, "text": "\n05 Jun, 2020" }, { "code": null, "e": 26316, "s": 26081, "text": "New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method. The examples given below would demonstrate this approach." }, { "code": null, "e": 26526, "s": 26316, "text": "Example 1: In this example, a newly created element is added as a child to the parent element. The type of the element to be created is specified and its value or text node for the specified element is added. " }, { "code": null, "e": 26531, "s": 26526, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to dynamically create new elements in JavaScript? </title></head> <body> <h1 style=\"text-align:center; color:green;\"> GeeksForGeeks </h1> <!-- Form to add item --> <form action=\"#\" style=\"text-align:center;\"> <!-- Type of Element --> <label for=\"type\"> Add Element Type </label> <input type=\"text\" id=\"type\" placeholder=\"Like: div, h1, li....\" value=\"li\" /> <br /><br /> <!-- Text/Value for the element ---> <label for=\"value\"> Add Element Value </label> <input type=\"text\" id=\"value\" placeholder=\"Like: Hello GeeksForGeeks\" value=\"CHILD 2\" /> <br /><br /> <!-- Submit the Form --> <button type=\"button\" onClick=\"addItem()\"> Add </button> </form> <!-- Parent tag where we add item as child --> <ol id=\"parent\"> <li>List Item 1</li> </ol> <script> // Define the addItem() function // to be called through onclick function addItem() { // Get type of element from form let type = document. getElementById(\"type\").value; // Get the text/value for the tag // from the form let value = document. getElementById(\"value\").value; // createElement() is used for // creating a new element type = document.createElement(type); // Use value as textnode in this example type.appendChild( document.createTextNode(value)); // Append as child to the parent // tag i.e. ol document.getElementById( \"parent\").appendChild(type); } </script></body> </html>", "e": 28442, "s": 26531, "text": null }, { "code": null, "e": 28451, "s": 28442, "text": "Output: " }, { "code": null, "e": 28483, "s": 28451, "text": "Before clicking on the button: " }, { "code": null, "e": 28514, "s": 28483, "text": "After clicking on the button: " }, { "code": null, "e": 28800, "s": 28514, "text": "Example 2: In this example, a newly created element along with its attributes is added to the body element of the page. The attributes can only be entered using two arguments i.e. type of attribute and the value of the attribute. The CSS for the “child” item is added for convenience. " }, { "code": null, "e": 28805, "s": 28800, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to dynamically create new elements in JavaScript? </title> <style> /* CSS for child item */ .child { color: white; background-color: green; } </style></head> <body id=\"body\"> <h1 style=\"text-align:center; color:green;\"> GeeksForGeeks </h1> <!-- Form to add item --> <form action=\"#\" style=\"text-align: center;\"> <!-- Type of element --> <label for=\"type\"> Add Element Type </label> <input type=\"text\" id=\"type\" placeholder=\"Like: div, h1, li....\" value=\"h3\" /> <br /><br /> <!-- Text/value for element ---> <label for=\"value\"> Add Element Value</label> <input type=\"text\" id=\"value\" placeholder=\"Like: Hello GeeksForGeeks\" value=\"Hello GeeksForGeeks\" /> <br /><br /> <!-- Add attributes for element ---> <label for=\"attr\"> Add Attributes</label> <form id=\"attr\"> <label for=\"attrType\">Add Attribute Type</label> <input type=\"text\" style=\"width:240px;\" placeholder=\"forexample: enter 'class' without quotes\" id=\"attrType\" value=\"class\" /> <br /> <br /> <label for=\"attrValue\"> Add Attribute Value </label> <input style=\"width:240px;\" type=\"text\" placeholder=\"for example: enter 'child' without quotes\" id=\"attrValue\" value=\"child\" /> </form> <br /><br /> <!-- Submit the form --> <button type=\"button\" onClick=\"addItem()\"> Add </button> </form> <div> <p>CHILD 1</p> </div> <script> // Define the addItem function // to be called through onclick() function addItem() { // Get Elements by id of the form inputs let parent = document.getElementById(\"body\"); let attrType = document.getElementById(\"attrType\"); let attrValue = document.getElementById(\"attrValue\"); let type = document.getElementById(\"type\"); let value = document.getElementById(\"value\"); if (type.value == \"\" || value.value == \"\") { window.alert( \"There is an error in form input\"); window.reload(); } // createElement() method is used // to create a new element type = document.createElement(type.value); // Append a text node for this example type.appendChild( document.createTextNode(value.value)); if (attrValue.value == \"\" || attrType.value == \"\") { attr = null; } else { // setAttribute() is used to set // the attributes of the element type.setAttribute( attrType.value, attrValue.value); } // Append as child to the parent // i.e. body parent.appendChild(type); } </script></body> </html>", "e": 32131, "s": 28805, "text": null }, { "code": null, "e": 32171, "s": 32131, "text": "Output: Before clicking on the button: " }, { "code": null, "e": 32202, "s": 32171, "text": "After clicking on the button: " }, { "code": null, "e": 32211, "s": 32202, "text": "CSS-Misc" }, { "code": null, "e": 32221, "s": 32211, "text": "HTML-Misc" }, { "code": null, "e": 32237, "s": 32221, "text": "JavaScript-Misc" }, { "code": null, "e": 32244, "s": 32237, "text": "Picked" }, { "code": null, "e": 32248, "s": 32244, "text": "CSS" }, { "code": null, "e": 32253, "s": 32248, "text": "HTML" }, { "code": null, "e": 32264, "s": 32253, "text": "JavaScript" }, { "code": null, "e": 32281, "s": 32264, "text": "Web Technologies" }, { "code": null, "e": 32297, "s": 32281, "text": "Write From Home" }, { "code": null, "e": 32302, "s": 32297, "text": "HTML" }, { "code": null, "e": 32400, "s": 32302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32455, "s": 32400, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32494, "s": 32455, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32531, "s": 32494, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32572, "s": 32531, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 32601, "s": 32572, "text": "Form validation using jQuery" }, { "code": null, "e": 32661, "s": 32601, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32714, "s": 32661, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32775, "s": 32714, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32799, "s": 32775, "text": "REST API (Introduction)" } ]
Calling a method using null in Java - GeeksforGeeks
29 Oct, 2017 Prerequisite: null in Java, Static in Java Can you predict the output of the following program??Before answering, please observe the fact that in given code, fun() is a static member that belongs to the class and not to any instance. // Java program to illustrate calling// static method using Nullpublic class GFG { public static void fun() { System.out.println("Welcome to GeeksforGeeks!!"); } public static void main(String[] args) { ((GFG)null).fun(); }} Output: Welcome to GeeksforGeeks!! Explanation:This program looks as though it is ought to throw a NullPointerException. However, the main method invokes the greet method (fun) on the constant null, and you can’t invoke a method on null.But, when you run the program, it prints “Welcome to GeeksforGeeks!!”. Let’s see how: The key to understanding this puzzle is that GFG.fun is a static method. Although, it is a bad idea to use an expression as the qualifier in a static method invocation, but that is exactly what this program does. Not only does the run-time type of the object referenced by the expression’s value play no role in determining which method gets invoked, but also the identity of the object, if any, plays no role. In this case, there is no object, but that makes no difference. A qualifying expression for a static method invocation is evaluated, but its value is ignored. There is no requirement that the value be non-null. This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Functions Static Keyword Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples StringBuilder Class in Java with Examples HashMap get() Method in Java Functional Interfaces in Java Strings in Java
[ { "code": null, "e": 23892, "s": 23864, "text": "\n29 Oct, 2017" }, { "code": null, "e": 23935, "s": 23892, "text": "Prerequisite: null in Java, Static in Java" }, { "code": null, "e": 24126, "s": 23935, "text": "Can you predict the output of the following program??Before answering, please observe the fact that in given code, fun() is a static member that belongs to the class and not to any instance." }, { "code": "// Java program to illustrate calling// static method using Nullpublic class GFG { public static void fun() { System.out.println(\"Welcome to GeeksforGeeks!!\"); } public static void main(String[] args) { ((GFG)null).fun(); }}", "e": 24385, "s": 24126, "text": null }, { "code": null, "e": 24393, "s": 24385, "text": "Output:" }, { "code": null, "e": 24420, "s": 24393, "text": "Welcome to GeeksforGeeks!!" }, { "code": null, "e": 24708, "s": 24420, "text": "Explanation:This program looks as though it is ought to throw a NullPointerException. However, the main method invokes the greet method (fun) on the constant null, and you can’t invoke a method on null.But, when you run the program, it prints “Welcome to GeeksforGeeks!!”. Let’s see how:" }, { "code": null, "e": 24781, "s": 24708, "text": "The key to understanding this puzzle is that GFG.fun is a static method." }, { "code": null, "e": 24921, "s": 24781, "text": "Although, it is a bad idea to use an expression as the qualifier in a static method invocation, but that is exactly what this program does." }, { "code": null, "e": 25119, "s": 24921, "text": "Not only does the run-time type of the object referenced by the expression’s value play no role in determining which method gets invoked, but also the identity of the object, if any, plays no role." }, { "code": null, "e": 25330, "s": 25119, "text": "In this case, there is no object, but that makes no difference. A qualifying expression for a static method invocation is evaluated, but its value is ignored. There is no requirement that the value be non-null." }, { "code": null, "e": 25632, "s": 25330, "text": "This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 25757, "s": 25632, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25772, "s": 25757, "text": "Java-Functions" }, { "code": null, "e": 25787, "s": 25772, "text": "Static Keyword" }, { "code": null, "e": 25792, "s": 25787, "text": "Java" }, { "code": null, "e": 25797, "s": 25792, "text": "Java" }, { "code": null, "e": 25895, "s": 25797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25904, "s": 25895, "text": "Comments" }, { "code": null, "e": 25917, "s": 25904, "text": "Old Comments" }, { "code": null, "e": 25963, "s": 25917, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25984, "s": 25963, "text": "Constructors in Java" }, { "code": null, "e": 25999, "s": 25984, "text": "Stream In Java" }, { "code": null, "e": 26018, "s": 25999, "text": "Exceptions in Java" }, { "code": null, "e": 26035, "s": 26018, "text": "Generics in Java" }, { "code": null, "e": 26078, "s": 26035, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26120, "s": 26078, "text": "StringBuilder Class in Java with Examples" }, { "code": null, "e": 26149, "s": 26120, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26179, "s": 26149, "text": "Functional Interfaces in Java" } ]
Sentence Similarity With BERT | Towards Data Science
All we ever seem to talk about nowadays are BERT this, BERT that. I want to write about something else, but BERT is just too good — so this article will be about BERT and sequence similarity! A big part of NLP relies on similarity in highly-dimensional spaces. Typically an NLP solution will take some text, process it to create a big vector/array representing said text — then perform several transformations. It’s highly-dimensional magic. Sentence similarity is one of the clearest examples of how powerful highly-dimensional magic can be. The logic is this: Take a sentence, convert it into a vector. Take many other sentences, and convert them into vectors. Find sentences that have the smallest distance (Euclidean) or smallest angle (cosine similarity) between them — more on that here. We now have a measure of semantic similarity between sentences — easy! At a high level, there’s not much else to it. But of course, we want to understand what is happening in a little more detail and implement this in Python too! So, let’s get started. BERT, as we already mentioned — is the MVP of NLP. And a big part of this is down to BERTs ability to embed the meaning of words into densely packed vectors. We call them dense vectors because every value within the vector has a value and has a reason for being that value — this is in contrast to sparse vectors, such as one-hot encoded vectors where the majority of values are 0. BERT is great at creating these dense vectors, and each encoder layer (there are several) outputs a set of dense vectors. For BERT base, this will be a vector containing 768. Those 768 values contain our numerical representation of a single token — which we can use as contextual word embeddings. Because there is one of these vectors for representing each token (output by each encoder), we are actually looking at a tensor of size 768 by the number of tokens. We can take these tensors — and transform them to create semantic representations of the input sequence. We can then take our similarity metrics and calculate the respective similarity between different sequences. The simplest and most commonly extracted tensor is the last_hidden_state tensor — which is conveniently output by the BERT model. Of course, this is a pretty large tensor — at 512x768 — and we want a vector to apply our similarity measures to it. To do this, we need to convert our last_hidden_states tensor to a vector of 768 dimensions. For us to convert our last_hidden_states tensor into our vector — we use a mean pooling operation. Each of those 512 tokens has a respective 768 values. This pooling operation will take the mean of all token embeddings and compress them into a single 768 vector space — creating a ‘sentence vector’. At the same time, we can’t just take the mean activation as is. We need to consider null padding tokens (which we should not include). That’s great on the theory and logic behind the process — but how do we apply this in reality? We’ll outline two approaches — the easy way and the slightly more complex way. The easiest approach for us to implement everything we just covered is through the sentence-transformers library — which wraps most of this process into a few lines of code. First, we install sentence-transformers using pip install sentence-transformers. This library uses HuggingFace’s transformers behind the scenes — so we can actually find sentence-transformers models here. We’ll be making use of the bert-base-nli-mean-tokens model — which implements the same logic we’ve discussed so far. (It also uses 128 input tokens, rather than 512). Let’s create some sentences, initialize our model, and encode the sentences: Write a few sentences to encode (sentences 0 and 2 are both similar): sentences = [ "Three years later, the coffin was still full of Jello.", "The fish dreamed of escaping the fishbowl and into the toilet where he saw his friend go.", "The person box was packed with jelly many dozens of months later.", "He found a leprechaun in his walnut shell." ] Initialize our model: from sentence_transformers import SentenceTransformer model = SentenceTransformer('bert-base-nli-mean-tokens') HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=405234788.0), HTML(value=''))) Encode the sentences: sentence_embeddings = model.encode(sentences) sentence_embeddings.shape (4, 768) Great, we now have four sentence embeddings — each containing 768 values. Now what we do is take those embeddings and find the cosine similarity between each. So for sentence 0: Three years later, the coffin was still full of Jello. We can find the most similar sentence using: from sklearn.metrics.pairwise import cosine_similarity Let's calculate cosine similarity for sentence 0: cosine_similarity( [sentence_embeddings[0]], sentence_embeddings[1:] ) array([[0.33088642, 0.7218851 , 0.55473834]], dtype=float32) These similarities translate to: Now, this is the easier — more abstract approach. Seven lines of code to compare our sentences. Before getting into the second approach, it is worth noting that it does the same thing as the first — but at one level lower. With this approach, we need to perform our own transformation to the last_hidden_state to create the sentence embedding. For this, we perform the mean pooling operation. Additionally, before the mean pooling operation, we need to create last_hidden_state, which we do like so: After we have produced our dense vectors embeddings, we need to perform a mean pooling operation to create a single vector encoding (the sentence embedding). To do this mean pooling operation, we will need to multiply each value in our embeddings tensor by its respective attention_mask value — so that we ignore non-real tokens. Once we have our dense vectors, we can calculate the cosine similarity between each — which is the same logic we used before: We return almost the same results — the only difference being that the cosine similarity for index three has shifted from 0.5547 to 0.5548 — a minor difference due to rounding. That’s all for this introduction to measuring the semantic similarity of sentences using BERT — using both sentence-transformers and a lower-level implementation with PyTorch and transformers. You can find the full notebooks for both approaches here and here. I hope you’ve enjoyed the article. Let me know if you have any questions or suggestions via Twitter or in the comments below. If you’re interested in more content like this, I post on YouTube too. Thanks for reading! N. Reimers, I. Gurevych, Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (2019), Proceedings of the 2019 Conference on Empirical Methods in NLP 🤖 NLP With Transformers Course If you’re interested in learning more about NLP similarity metrics (including cosine similarity, which we used here) — check out this article I wrote explaining the most popular metrics: towardsdatascience.com *All images are by the author except where stated otherwise
[ { "code": null, "e": 363, "s": 171, "text": "All we ever seem to talk about nowadays are BERT this, BERT that. I want to write about something else, but BERT is just too good — so this article will be about BERT and sequence similarity!" }, { "code": null, "e": 582, "s": 363, "text": "A big part of NLP relies on similarity in highly-dimensional spaces. Typically an NLP solution will take some text, process it to create a big vector/array representing said text — then perform several transformations." }, { "code": null, "e": 613, "s": 582, "text": "It’s highly-dimensional magic." }, { "code": null, "e": 714, "s": 613, "text": "Sentence similarity is one of the clearest examples of how powerful highly-dimensional magic can be." }, { "code": null, "e": 733, "s": 714, "text": "The logic is this:" }, { "code": null, "e": 776, "s": 733, "text": "Take a sentence, convert it into a vector." }, { "code": null, "e": 834, "s": 776, "text": "Take many other sentences, and convert them into vectors." }, { "code": null, "e": 965, "s": 834, "text": "Find sentences that have the smallest distance (Euclidean) or smallest angle (cosine similarity) between them — more on that here." }, { "code": null, "e": 1036, "s": 965, "text": "We now have a measure of semantic similarity between sentences — easy!" }, { "code": null, "e": 1218, "s": 1036, "text": "At a high level, there’s not much else to it. But of course, we want to understand what is happening in a little more detail and implement this in Python too! So, let’s get started." }, { "code": null, "e": 1376, "s": 1218, "text": "BERT, as we already mentioned — is the MVP of NLP. And a big part of this is down to BERTs ability to embed the meaning of words into densely packed vectors." }, { "code": null, "e": 1600, "s": 1376, "text": "We call them dense vectors because every value within the vector has a value and has a reason for being that value — this is in contrast to sparse vectors, such as one-hot encoded vectors where the majority of values are 0." }, { "code": null, "e": 1722, "s": 1600, "text": "BERT is great at creating these dense vectors, and each encoder layer (there are several) outputs a set of dense vectors." }, { "code": null, "e": 1897, "s": 1722, "text": "For BERT base, this will be a vector containing 768. Those 768 values contain our numerical representation of a single token — which we can use as contextual word embeddings." }, { "code": null, "e": 2062, "s": 1897, "text": "Because there is one of these vectors for representing each token (output by each encoder), we are actually looking at a tensor of size 768 by the number of tokens." }, { "code": null, "e": 2276, "s": 2062, "text": "We can take these tensors — and transform them to create semantic representations of the input sequence. We can then take our similarity metrics and calculate the respective similarity between different sequences." }, { "code": null, "e": 2406, "s": 2276, "text": "The simplest and most commonly extracted tensor is the last_hidden_state tensor — which is conveniently output by the BERT model." }, { "code": null, "e": 2523, "s": 2406, "text": "Of course, this is a pretty large tensor — at 512x768 — and we want a vector to apply our similarity measures to it." }, { "code": null, "e": 2615, "s": 2523, "text": "To do this, we need to convert our last_hidden_states tensor to a vector of 768 dimensions." }, { "code": null, "e": 2714, "s": 2615, "text": "For us to convert our last_hidden_states tensor into our vector — we use a mean pooling operation." }, { "code": null, "e": 2915, "s": 2714, "text": "Each of those 512 tokens has a respective 768 values. This pooling operation will take the mean of all token embeddings and compress them into a single 768 vector space — creating a ‘sentence vector’." }, { "code": null, "e": 3050, "s": 2915, "text": "At the same time, we can’t just take the mean activation as is. We need to consider null padding tokens (which we should not include)." }, { "code": null, "e": 3145, "s": 3050, "text": "That’s great on the theory and logic behind the process — but how do we apply this in reality?" }, { "code": null, "e": 3224, "s": 3145, "text": "We’ll outline two approaches — the easy way and the slightly more complex way." }, { "code": null, "e": 3398, "s": 3224, "text": "The easiest approach for us to implement everything we just covered is through the sentence-transformers library — which wraps most of this process into a few lines of code." }, { "code": null, "e": 3603, "s": 3398, "text": "First, we install sentence-transformers using pip install sentence-transformers. This library uses HuggingFace’s transformers behind the scenes — so we can actually find sentence-transformers models here." }, { "code": null, "e": 3720, "s": 3603, "text": "We’ll be making use of the bert-base-nli-mean-tokens model — which implements the same logic we’ve discussed so far." }, { "code": null, "e": 3770, "s": 3720, "text": "(It also uses 128 input tokens, rather than 512)." }, { "code": null, "e": 3847, "s": 3770, "text": "Let’s create some sentences, initialize our model, and encode the sentences:" }, { "code": null, "e": 3917, "s": 3847, "text": "Write a few sentences to encode (sentences 0 and 2 are both similar):" }, { "code": null, "e": 4215, "s": 3917, "text": "sentences = [\n \"Three years later, the coffin was still full of Jello.\",\n \"The fish dreamed of escaping the fishbowl and into the toilet where he saw his friend go.\",\n \"The person box was packed with jelly many dozens of months later.\",\n \"He found a leprechaun in his walnut shell.\"\n]\n" }, { "code": null, "e": 4237, "s": 4215, "text": "Initialize our model:" }, { "code": null, "e": 4350, "s": 4237, "text": "from sentence_transformers import SentenceTransformer\n\nmodel = SentenceTransformer('bert-base-nli-mean-tokens')\n" }, { "code": null, "e": 4441, "s": 4350, "text": "HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=405234788.0), HTML(value='')))" }, { "code": null, "e": 4463, "s": 4441, "text": "Encode the sentences:" }, { "code": null, "e": 4510, "s": 4463, "text": "sentence_embeddings = model.encode(sentences)\n" }, { "code": null, "e": 4537, "s": 4510, "text": "sentence_embeddings.shape\n" }, { "code": null, "e": 4546, "s": 4537, "text": "(4, 768)" }, { "code": null, "e": 4620, "s": 4546, "text": "Great, we now have four sentence embeddings — each containing 768 values." }, { "code": null, "e": 4724, "s": 4620, "text": "Now what we do is take those embeddings and find the cosine similarity between each. So for sentence 0:" }, { "code": null, "e": 4779, "s": 4724, "text": "Three years later, the coffin was still full of Jello." }, { "code": null, "e": 4824, "s": 4779, "text": "We can find the most similar sentence using:" }, { "code": null, "e": 4880, "s": 4824, "text": "from sklearn.metrics.pairwise import cosine_similarity\n" }, { "code": null, "e": 4930, "s": 4880, "text": "Let's calculate cosine similarity for sentence 0:" }, { "code": null, "e": 5010, "s": 4930, "text": "cosine_similarity(\n [sentence_embeddings[0]],\n sentence_embeddings[1:]\n)\n" }, { "code": null, "e": 5071, "s": 5010, "text": "array([[0.33088642, 0.7218851 , 0.55473834]], dtype=float32)" }, { "code": null, "e": 5104, "s": 5071, "text": "These similarities translate to:" }, { "code": null, "e": 5200, "s": 5104, "text": "Now, this is the easier — more abstract approach. Seven lines of code to compare our sentences." }, { "code": null, "e": 5327, "s": 5200, "text": "Before getting into the second approach, it is worth noting that it does the same thing as the first — but at one level lower." }, { "code": null, "e": 5497, "s": 5327, "text": "With this approach, we need to perform our own transformation to the last_hidden_state to create the sentence embedding. For this, we perform the mean pooling operation." }, { "code": null, "e": 5604, "s": 5497, "text": "Additionally, before the mean pooling operation, we need to create last_hidden_state, which we do like so:" }, { "code": null, "e": 5762, "s": 5604, "text": "After we have produced our dense vectors embeddings, we need to perform a mean pooling operation to create a single vector encoding (the sentence embedding)." }, { "code": null, "e": 5934, "s": 5762, "text": "To do this mean pooling operation, we will need to multiply each value in our embeddings tensor by its respective attention_mask value — so that we ignore non-real tokens." }, { "code": null, "e": 6060, "s": 5934, "text": "Once we have our dense vectors, we can calculate the cosine similarity between each — which is the same logic we used before:" }, { "code": null, "e": 6237, "s": 6060, "text": "We return almost the same results — the only difference being that the cosine similarity for index three has shifted from 0.5547 to 0.5548 — a minor difference due to rounding." }, { "code": null, "e": 6430, "s": 6237, "text": "That’s all for this introduction to measuring the semantic similarity of sentences using BERT — using both sentence-transformers and a lower-level implementation with PyTorch and transformers." }, { "code": null, "e": 6497, "s": 6430, "text": "You can find the full notebooks for both approaches here and here." }, { "code": null, "e": 6694, "s": 6497, "text": "I hope you’ve enjoyed the article. Let me know if you have any questions or suggestions via Twitter or in the comments below. If you’re interested in more content like this, I post on YouTube too." }, { "code": null, "e": 6714, "s": 6694, "text": "Thanks for reading!" }, { "code": null, "e": 6873, "s": 6714, "text": "N. Reimers, I. Gurevych, Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks (2019), Proceedings of the 2019 Conference on Empirical Methods in NLP" }, { "code": null, "e": 6904, "s": 6873, "text": "🤖 NLP With Transformers Course" }, { "code": null, "e": 7091, "s": 6904, "text": "If you’re interested in learning more about NLP similarity metrics (including cosine similarity, which we used here) — check out this article I wrote explaining the most popular metrics:" }, { "code": null, "e": 7114, "s": 7091, "text": "towardsdatascience.com" } ]
Find common elements in list of lists in Python
It is possible to have a list whose inner elements are also lists. In such cases we may come across a need when we have to find out the common elements among these inner lists. In this article we will find out the approaches to achieve this. Intersection is a simple mathematical concept of finding the common elements between different sets. Python has the set method which returns a set that contains the similarity between two or more sets. So we first convert the elements of the list into set through a map function and then apply the set method to all this converted lists. Live Demo listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]] # Given list print("Given list of lists : \n",listA) # Applying intersection res = list(set.intersection(*map(set, listA))) # Result print("The common elements among inners lists : ",res) Running the above code gives us the following result − Given list of lists : [['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]] The common elements among inners lists : ['Tue', 7] We can also apply the reduce function in python. This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them . Live Demo from functools import reduce listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]] # Given list print("Given list of lists : \n",listA) # Applying reduce res = list(reduce(lambda i, j: i & j, (set(n) for n in listA))) # Result print("The common elements among inners lists : ",res) Running the above code gives us the following result − Given list of lists : [['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]] The common elements among inners lists : ['Tue', 7]
[ { "code": null, "e": 1304, "s": 1062, "text": "It is possible to have a list whose inner elements are also lists. In such cases we may come across a need when we have to find out the common elements among these inner lists. In this article we will find out the approaches to achieve this." }, { "code": null, "e": 1642, "s": 1304, "text": "Intersection is a simple mathematical concept of finding the common elements between different sets. Python has the set method which returns a set that contains the similarity between two or more sets. So we first convert the elements of the list into set through a map function and then apply the set method to all this converted lists." }, { "code": null, "e": 1653, "s": 1642, "text": " Live Demo" }, { "code": null, "e": 1941, "s": 1653, "text": "listA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]\n\n# Given list\nprint(\"Given list of lists : \\n\",listA)\n\n# Applying intersection\nres = list(set.intersection(*map(set, listA)))\n\n# Result\nprint(\"The common elements among inners lists : \",res)" }, { "code": null, "e": 1996, "s": 1941, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2168, "s": 1996, "text": "Given list of lists :\n[['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]]\nThe common elements among inners lists : ['Tue', 7]" }, { "code": null, "e": 2479, "s": 2168, "text": "We can also apply the reduce function in python. This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them ." }, { "code": null, "e": 2490, "s": 2479, "text": " Live Demo" }, { "code": null, "e": 2818, "s": 2490, "text": "from functools import reduce\nlistA = [['Mon', 3, 'Tue', 7,'Wed',4],['Thu', 5,'Fri',11,'Tue', 7],['Wed', 9, 'Tue', 7,'Wed',6]]\n\n# Given list\nprint(\"Given list of lists : \\n\",listA)\n\n# Applying reduce\nres = list(reduce(lambda i, j: i & j, (set(n) for n in listA)))\n\n# Result\nprint(\"The common elements among inners lists : \",res)" }, { "code": null, "e": 2873, "s": 2818, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3045, "s": 2873, "text": "Given list of lists :\n[['Mon', 3, 'Tue', 7, 'Wed', 4], ['Thu', 5, 'Fri', 11, 'Tue', 7], ['Wed', 9, 'Tue', 7, 'Wed', 6]]\nThe common elements among inners lists : ['Tue', 7]" } ]
Exploratory Data Analysis — MTA Turnstile Traffic Analysis for Street Engagement | by Tan Pengshi Alvin | Towards Data Science
In the Project 1 of Metis Data Science Bootcamp (Singapore Batch 5), we are tasked on exploratory data analysis (EDA) of MTA turnstile data to advise a fictitious non-profit organization, WomenTechWomenYes (WTWY) on the optimal placement of street teams (at entrances to NYC subway stations) for social engagements. WTWY wants to invite interested individuals to its annual gala to raise awareness and increase participation for women in tech, and the street teams’ agenda is to collect as many emails as possible and give out free tickets to the gala. In my analysis, I have made the following assumptions: WTWY is constrained by time and manpower resources, hence insights from my analysis should identify top stations by traffic, as well as the peak periods in those stations. Individuals who are interested in tech have a higher probability to be encountered in city center with a denser cluster of tech corporate offices. The WTWY gala is imminent, and a week of MTA turnstile data is analyzed as an sample for the weeks leading to the gala. The MTA turnstile data is scraped for the week 22 August 2020 to 28 August 2020. Taking the first few rows of the data, we observed the following data frame: The descriptions of the column features are given here. Further exploration reveals that the ‘ENTRIES’ and ‘EXIT’ columns are cumulative serial numbers that increase with time. Also, the rows of the ‘TIME’ column progress at approximately 4 hour blocks and each turnstile has a unique combinations of ‘UNIT’ and ‘SCP’ number as shown. Some rows are also found to be duplicates, and are removed. df.groupby(['UNIT','SCP'])['STATION'].nunique().sort_values() #checking combination of 'UNIT' and 'SCP' is unique to each station,implying each combination refers to a unique turnstile UNIT SCP R001 00-00-00 1 R273 00-00-01 1 00-00-00 1 R272 01-06-02 1 01-06-01 1 .. R112 01-06-01 1 01-06-00 1 01-05-01 1 R113 00-00-04 1 R572 01-03-04 1 Name: STATION, Length: 4945, dtype: int64 In order to find number of people that enter and exit each turnstile, I first sort the columns in the data frame according to the following order: [‘UNIT’, ‘SCP’, ‘DATE’, ‘TIME’], then using the diff() method for Series, I take the difference between consecutive rows for ‘ENTRIES’ and ‘EXITS’ respectively to form new columns. The new columns (named as ‘ENTRY_DELTA’ and ‘EXIT_DELTA’) will then represent the actual number of entries and exits through each turnstile during a particular 4 hour period. Nonetheless, some of the values of entries/exit turn out to be either negative or astronomically high numbers. df['ENTRY_DELTA'][df['ENTRY_DELTA']<0] # Checking reset of entry counter values 252044 -8291685.0 264128 -91.0 264129 -4.0 264130 -34.0 264131 -25.0 ... 341647 -17768.0 339394 -210087.0 342664 -80186.0 337985 -32882.0 337631 -1508.0 Name: ENTRY_DELTA, Length: 1724, dtype: float64 df['ENTRY_DELTA'][df['ENTRY_DELTA']>10000] # Checking reset of entry counter values 271427 1.057536e+09 271465 1.549702e+09 300430 8.368614e+07 297544 1.443527e+06 297546 1.443555e+06 241440 6.512100e+04 241509 3.245470e+05 241515 1.966110e+05 296920 1.405439e+06 Name: ENTRY_DELTA, dtype: float64 df['EXIT_DELTA'][df['EXIT_DELTA']<0] # Checking reset of exit counter values 252044 -5618417.0 372575 -1.0 372585 -2.0 371439 -2794.0 378552 -1.0 ... 341647 -2261.0 339394 -27583.0 342664 -101904.0 337985 -266037.0 337631 -1199.0 Name: EXIT_DELTA, Length: 1345, dtype: float64 df['EXIT_DELTA'][df['EXIT_DELTA']>10000] # Checking reset of exit counter values 300430 82744.0 297544 2955446.0 297546 2955411.0 241509 53279.0 296920 228341.0 Name: EXIT_DELTA, dtype: float64 Further analysis showed that this is due to the transition of rows between 2 different turnstiles in the data frame, or the reset of the serial number counter in particular turnstiles. To make the corrections, these anomalous values are then replaced with the mean of the preceding and succeeding values of entries/exit. This intervention is reasonable because the entries/exit can be approximated as interpolation between consecutive time periods. Thereafter, the total traffic for each turnstile in each time period is calculated by summing entries and exit values. I named this column as ‘ENTRY_EXIT’. Now, we are ready for the data visualization to derive insights for potential placements of street teams for WTWY! Using Panda’s groupby, Matplotlib and Seaborn, I then proceed to plot a histogram, bar chart, and a few heatmaps. Plotting the histogram shows that the distribution of traffic across all MTA stations in New York City is heavily right-skewed, and that the top 10 stations by traffic are outliers in the distribution. Hence, this gives a clearer indication that WTWY could focus their engagement efforts in the top 10 stations. Zooming in, plotting the bar chart of the top 10 stations reveal that 34 St-Penn and 34 St-Herald Square stations have notably more traffic than the rest of the stations, and should be taken as priority. Adding the dimension of day, plotting the heat map of the top 10 stations across the week reveals the trend that people are traveling with the subway more frequently in the weekdays, as compared to the weekends. The trend applies to all the 10 stations. Further breaking the heat map down into day versus time for each station reveals another interesting fact — stations are generally busier in the late afternoon and in the evenings, even during weekdays. This comes as no surprise, as during the Covid pandemic, many companies in NYC have adopted work-from-home arrangements, thus the morning rush hour crowd was avoided. Furthermore, employing street teams on weekday mornings could be counter-productive, as the rest of the essential workers would be busy reporting to work and are less likely to be successfully approached. With another heat map, when we analyze the net entry and exits of commuters in each station (red regions represent net entry, and blue regions represent net exit), we can identify the stations that are located in the denser residential/hotel areas — Flushing-Main and 42 St-Port Auth stations. This is evidenced by their net exits during the evenings, which implies that people are returning back home. As these stations are not close to corporate offices, individuals interested in tech are less likely to be found in these pool of commuters. From our analysis, we can conclude that WTWY should focus their street engagement efforts in the top 10 stations, ideally during weekdays in the late afternoon to evening periods. Moreover, if there are further manpower constraints, Flushing-Main and 42 St-Port Auth stations could be avoided as they are potentially residential and touristy areas where tech corporate offices are not located. Finally, I hope my exploratory data analysis on MTA turnstile data has generated interesting insights, and I look forward to showcasing other upcoming data projects from the Metis Data Science Bootcamp. Stay tuned! Find all my codes and presentation slides for this project here on GitHub! Support me! — If you are not subscribed to Medium, and like my content, do consider supporting me by subscribing via my referral link here.
[ { "code": null, "e": 779, "s": 171, "text": "In the Project 1 of Metis Data Science Bootcamp (Singapore Batch 5), we are tasked on exploratory data analysis (EDA) of MTA turnstile data to advise a fictitious non-profit organization, WomenTechWomenYes (WTWY) on the optimal placement of street teams (at entrances to NYC subway stations) for social engagements. WTWY wants to invite interested individuals to its annual gala to raise awareness and increase participation for women in tech, and the street teams’ agenda is to collect as many emails as possible and give out free tickets to the gala. In my analysis, I have made the following assumptions:" }, { "code": null, "e": 951, "s": 779, "text": "WTWY is constrained by time and manpower resources, hence insights from my analysis should identify top stations by traffic, as well as the peak periods in those stations." }, { "code": null, "e": 1098, "s": 951, "text": "Individuals who are interested in tech have a higher probability to be encountered in city center with a denser cluster of tech corporate offices." }, { "code": null, "e": 1218, "s": 1098, "text": "The WTWY gala is imminent, and a week of MTA turnstile data is analyzed as an sample for the weeks leading to the gala." }, { "code": null, "e": 1376, "s": 1218, "text": "The MTA turnstile data is scraped for the week 22 August 2020 to 28 August 2020. Taking the first few rows of the data, we observed the following data frame:" }, { "code": null, "e": 1771, "s": 1376, "text": "The descriptions of the column features are given here. Further exploration reveals that the ‘ENTRIES’ and ‘EXIT’ columns are cumulative serial numbers that increase with time. Also, the rows of the ‘TIME’ column progress at approximately 4 hour blocks and each turnstile has a unique combinations of ‘UNIT’ and ‘SCP’ number as shown. Some rows are also found to be duplicates, and are removed." }, { "code": null, "e": 1959, "s": 1771, "text": "df.groupby(['UNIT','SCP'])['STATION'].nunique().sort_values() \n#checking combination of 'UNIT' and 'SCP' is unique to each station,implying each combination refers to a unique turnstile\n" }, { "code": null, "e": 2236, "s": 1959, "text": "UNIT SCP \nR001 00-00-00 1\nR273 00-00-01 1\n 00-00-00 1\nR272 01-06-02 1\n 01-06-01 1\n ..\nR112 01-06-01 1\n 01-06-00 1\n 01-05-01 1\nR113 00-00-04 1\nR572 01-03-04 1\nName: STATION, Length: 4945, dtype: int64" }, { "code": null, "e": 2850, "s": 2236, "text": "In order to find number of people that enter and exit each turnstile, I first sort the columns in the data frame according to the following order: [‘UNIT’, ‘SCP’, ‘DATE’, ‘TIME’], then using the diff() method for Series, I take the difference between consecutive rows for ‘ENTRIES’ and ‘EXITS’ respectively to form new columns. The new columns (named as ‘ENTRY_DELTA’ and ‘EXIT_DELTA’) will then represent the actual number of entries and exits through each turnstile during a particular 4 hour period. Nonetheless, some of the values of entries/exit turn out to be either negative or astronomically high numbers." }, { "code": null, "e": 2931, "s": 2850, "text": "df['ENTRY_DELTA'][df['ENTRY_DELTA']<0]\n# Checking reset of entry counter values\n" }, { "code": null, "e": 3199, "s": 2931, "text": "252044 -8291685.0\n264128 -91.0\n264129 -4.0\n264130 -34.0\n264131 -25.0\n ... \n341647 -17768.0\n339394 -210087.0\n342664 -80186.0\n337985 -32882.0\n337631 -1508.0\nName: ENTRY_DELTA, Length: 1724, dtype: float64" }, { "code": null, "e": 3284, "s": 3199, "text": "df['ENTRY_DELTA'][df['ENTRY_DELTA']>10000]\n# Checking reset of entry counter values\n" }, { "code": null, "e": 3525, "s": 3284, "text": "271427 1.057536e+09\n271465 1.549702e+09\n300430 8.368614e+07\n297544 1.443527e+06\n297546 1.443555e+06\n241440 6.512100e+04\n241509 3.245470e+05\n241515 1.966110e+05\n296920 1.405439e+06\nName: ENTRY_DELTA, dtype: float64" }, { "code": null, "e": 3603, "s": 3525, "text": "df['EXIT_DELTA'][df['EXIT_DELTA']<0]\n# Checking reset of exit counter values\n" }, { "code": null, "e": 3870, "s": 3603, "text": "252044 -5618417.0\n372575 -1.0\n372585 -2.0\n371439 -2794.0\n378552 -1.0\n ... \n341647 -2261.0\n339394 -27583.0\n342664 -101904.0\n337985 -266037.0\n337631 -1199.0\nName: EXIT_DELTA, Length: 1345, dtype: float64" }, { "code": null, "e": 3952, "s": 3870, "text": "df['EXIT_DELTA'][df['EXIT_DELTA']>10000]\n# Checking reset of exit counter values\n" }, { "code": null, "e": 4085, "s": 3952, "text": "300430 82744.0\n297544 2955446.0\n297546 2955411.0\n241509 53279.0\n296920 228341.0\nName: EXIT_DELTA, dtype: float64" }, { "code": null, "e": 4537, "s": 4088, "text": "Further analysis showed that this is due to the transition of rows between 2 different turnstiles in the data frame, or the reset of the serial number counter in particular turnstiles. To make the corrections, these anomalous values are then replaced with the mean of the preceding and succeeding values of entries/exit. This intervention is reasonable because the entries/exit can be approximated as interpolation between consecutive time periods." }, { "code": null, "e": 4693, "s": 4537, "text": "Thereafter, the total traffic for each turnstile in each time period is calculated by summing entries and exit values. I named this column as ‘ENTRY_EXIT’." }, { "code": null, "e": 4922, "s": 4693, "text": "Now, we are ready for the data visualization to derive insights for potential placements of street teams for WTWY! Using Panda’s groupby, Matplotlib and Seaborn, I then proceed to plot a histogram, bar chart, and a few heatmaps." }, { "code": null, "e": 5234, "s": 4922, "text": "Plotting the histogram shows that the distribution of traffic across all MTA stations in New York City is heavily right-skewed, and that the top 10 stations by traffic are outliers in the distribution. Hence, this gives a clearer indication that WTWY could focus their engagement efforts in the top 10 stations." }, { "code": null, "e": 5438, "s": 5234, "text": "Zooming in, plotting the bar chart of the top 10 stations reveal that 34 St-Penn and 34 St-Herald Square stations have notably more traffic than the rest of the stations, and should be taken as priority." }, { "code": null, "e": 5692, "s": 5438, "text": "Adding the dimension of day, plotting the heat map of the top 10 stations across the week reveals the trend that people are traveling with the subway more frequently in the weekdays, as compared to the weekends. The trend applies to all the 10 stations." }, { "code": null, "e": 6267, "s": 5692, "text": "Further breaking the heat map down into day versus time for each station reveals another interesting fact — stations are generally busier in the late afternoon and in the evenings, even during weekdays. This comes as no surprise, as during the Covid pandemic, many companies in NYC have adopted work-from-home arrangements, thus the morning rush hour crowd was avoided. Furthermore, employing street teams on weekday mornings could be counter-productive, as the rest of the essential workers would be busy reporting to work and are less likely to be successfully approached." }, { "code": null, "e": 6811, "s": 6267, "text": "With another heat map, when we analyze the net entry and exits of commuters in each station (red regions represent net entry, and blue regions represent net exit), we can identify the stations that are located in the denser residential/hotel areas — Flushing-Main and 42 St-Port Auth stations. This is evidenced by their net exits during the evenings, which implies that people are returning back home. As these stations are not close to corporate offices, individuals interested in tech are less likely to be found in these pool of commuters." }, { "code": null, "e": 7205, "s": 6811, "text": "From our analysis, we can conclude that WTWY should focus their street engagement efforts in the top 10 stations, ideally during weekdays in the late afternoon to evening periods. Moreover, if there are further manpower constraints, Flushing-Main and 42 St-Port Auth stations could be avoided as they are potentially residential and touristy areas where tech corporate offices are not located." }, { "code": null, "e": 7420, "s": 7205, "text": "Finally, I hope my exploratory data analysis on MTA turnstile data has generated interesting insights, and I look forward to showcasing other upcoming data projects from the Metis Data Science Bootcamp. Stay tuned!" }, { "code": null, "e": 7495, "s": 7420, "text": "Find all my codes and presentation slides for this project here on GitHub!" } ]
Minimum splits in a binary string such that every substring is a power of 4 or 6. - GeeksforGeeks
23 Apr, 2021 Given a string S composed of 0 and 1. Find the minimum splits such that the substring is a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such partitioning is possible. Examples: Input: 100110110 Output: 3 The string can be split into a minimum of three substrings 100(power of 4), 110 (power of 6) and 110(power of 6). Input : 00000 Output : -1 0 is not a power of 4 or 6. A simple solution is to split the string recursively at different indices and check if each split is a power of 4 or 6. Start with index 0 and split str[0] from other string. If it is a power of 4 or 6 then call recursively for index 1 and perform the same operation. When an entire string is split check if a total number of partitions are minimum so far or not. Then split str[0..1], check if it is the power of 4 or 6 and then call recursively for rest string. Compare partitions with minimum so far at the end of string traversal. This approach will be exponential in time.An efficient solution is to use Dynamic Programming. A 1-D dp table is created in which dp[i] stores minimum number of partitions required to split string str[i..n-1] into substrings that are power of 4 or 6. Suppose we are at index i and str[i..j] is power of 4 or 6, then minimum number of partitions will be minimum number of partitions to split str[j+1..n-1] plus one partition to split str[i..j] from string, that is dp[j+1] + 1. Hence the recurrence relation for (j!=(n-1)) and (dp[j + 1]!=-1) will be: dp[i] = min(dp[i], dp[j + 1] + 1) Implementation: C++ Java Python 3 C# Javascript // CPP program for Minimum splits in a//string such that substring is a power of 4 or 6. #include <bits/stdc++.h>using namespace std; // Function to find if given number// is power of another number or not.bool isPowerOf(long val, int base){ // Divide given number repeatedly // by base value. while (val > 1) { if (val % base != 0) return false; // not a power val /= base; } return true;} // Function to find minimum number of// partitions of given binary string// so that each partition is power of 4 or 6.int numberOfPartitions(string binaryNo){ int i, j, n = binaryNo.length(); // Variable to store integer value of // given binary string partition. long val; // DP table to store results of // partitioning done at differentindices. int dp[n]; // If the last digit is 1, hence 4^0=1 and 6^0=1 dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1; // Fix starting position for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes is not allowed. if ((binaryNo[i] - '0') == 0) { dp[i] = -1; continue; } dp[i] = INT_MAX; // Iterate for all different partitions starting from i for (j = i; j < n; j++) { // Find integer value of current // binary partition. val = (val * 2) + (long)(binaryNo[j] - '0'); // Check if the value is a power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, then // make dp[i] = -1 to represent this. if (dp[i] == INT_MAX) dp[i] = -1; } return dp[0];} // Driver codeint main(){ string binaryNo = "100110110"; cout << numberOfPartitions(binaryNo); return 0;} // Java program for Minimum splits// in a string such that substring// is a power of 4 or 6.import java.io.*; class GFG{ static boolean isPowerOf(long val, int base){ // Divide given number // repeatedly by base value. while (val > 1) { if (val % base != 0) return false; // not a power val /= base; } return true;} // Function to find minimum// number of partitions of// given binary string so that// each partition is power// of 4 or 6.static int numberOfPartitions(String binaryNo){ int i, j, n = binaryNo.length(); // Variable to store integer // value of given binary // string partition. long val; // DP table to store results // of partitioning done at // differentindices. int dp[] = new int[n]; // If the last digit is 1, // hence 4^0=1 and 6^0=1 dp[n - 1] = (((binaryNo.charAt(n - 1) - '0') == 0) ? -1 : 1); // Fix starting position // for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes // is not allowed. if ((binaryNo.charAt(i) - '0') == 0) { dp[i] = -1; continue; } dp[i] = Integer.MAX_VALUE; // Iterate for all different // partitions starting from i for (j = i; j < n; j++) { // Find integer value of // current binary partition. val = (val * 2) + (long)(binaryNo.charAt(j) - '0'); // Check if the value is a // power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = Math.min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, // then make dp[i] = -1 to // represent this. if (dp[i] == Integer.MAX_VALUE) dp[i] = -1; } return dp[0];} // Driver codepublic static void main (String[] args){ String binaryNo = "100110110"; System.out.println(numberOfPartitions(binaryNo));}} // This code is contributed// by shiv_bhakt. # Python 3 program for Minimum# splits in a string such that# substring is a power of 4 or 6. import sys # Function to find if given number# is power of another number or not.def isPowerOf(val, base): # Divide given number repeatedly # by base value. while (val > 1): if (val % base != 0): return False # not a power val //= base return True # Function to find minimum number of# partitions of given binary string# so that each partition is power of 4 or 6.def numberOfPartitions(binaryNo): n = len(binaryNo) # DP table to store results of # partitioning done at differentindices. dp = [0] * n # If the last digit is 1, hence 4^0=1 and 6^0=1 if ((ord(binaryNo[n - 1]) - ord('0')) == 0) : dp[n - 1] = -1 else: dp[n - 1] = 1 # Fix starting position for partition for i in range( n - 2, -1, -1): val = 0 # Binary representation # with leading zeroes is not allowed. if ((ord(binaryNo[i]) - ord('0')) == 0): dp[i] = -1 continue dp[i] = sys.maxsize # Iterate for all different partitions starting from i for j in range(i, n): # Find integer value of current # binary partition. val = (val * 2) + (ord(binaryNo[j]) - ord('0')) # Check if the value is a power of 4 or 6 or not # apply recurrence relation if (isPowerOf(val, 4) or isPowerOf(val, 6)): if (j == n - 1): dp[i] = 1 else : if (dp[j + 1] != -1): dp[i] = min(dp[i], dp[j + 1] + 1) # If no partitions are possible, then # make dp[i] = -1 to represent this. if (dp[i] == sys.maxsize): dp[i] = -1 return dp[0] # Driver codeif __name__ == "__main__": binaryNo = "100110110" print(numberOfPartitions(binaryNo)) # This code is contributed by Ita_c. // C# program for Minimum splits// in a string such that substring// is a power of 4 or 6. using System; class GFG{ static bool isPowerOf(long val, int b){ // Divide given number // repeatedly by base value. while (val > 1) { if (val % b != 0) return false; // not a power val /= b; } return true;} // Function to find minimum// number of partitions of// given binary string so that// each partition is power// of 4 or 6.static int numberOfPartitions(string binaryNo){ int i, j, n = binaryNo.Length; // Variable to store integer // value of given binary // string partition. long val; // DP table to store results // of partitioning done at // differentindices. int[] dp = new int[n]; // If the last digit is 1, // hence 4^0=1 and 6^0=1 dp[n - 1] = (((binaryNo[n - 1] - '0') == 0) ? -1 : 1); // Fix starting position // for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes // is not allowed. if ((binaryNo[i] - '0') == 0) { dp[i] = -1; continue; } dp[i] = int.MaxValue; // Iterate for all different // partitions starting from i for (j = i; j < n; j++) { // Find integer value of // current binary partition. val = (val * 2) + (long)(binaryNo[j] - '0'); // Check if the value is a // power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = Math.Min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, // then make dp[i] = -1 to // represent this. if (dp[i] == int.MaxValue) dp[i] = -1; } return dp[0];} // Driver codepublic static void Main (){ string binaryNo = "100110110"; Console.Write(numberOfPartitions(binaryNo));}} <script> // Javascript program for Minimum splits in a//string such that substring is a power of 4 or 6. // Function to find if given number// is power of another number or not.function isPowerOf(val, base){ // Divide given number repeatedly // by base value. while (val > 1) { if (val % base != 0) return false; // not a power val /= base; } return true;} // Function to find minimum number of// partitions of given binary string// so that each partition is power of 4 or 6.function numberOfPartitions(binaryNo){ var i, j, n = binaryNo.length; // Variable to store integer value of // given binary string partition. var val; // DP table to store results of // partitioning done at differentindices. var dp = Array(n); // If the last digit is 1, hence 4^0=1 and 6^0=1 dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1; // Fix starting position for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes is not allowed. if ((binaryNo[i] - '0') == 0) { dp[i] = -1; continue; } dp[i] = 1000000000; // Iterate for all different partitions starting from i for (j = i; j < n; j++) { // Find integer value of current // binary partition. val = (val * 2) + (binaryNo[j] - '0'); // Check if the value is a power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = Math.min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, then // make dp[i] = -1 to represent this. if (dp[i] == 1000000000) dp[i] = -1; } return dp[0];} // Driver codevar binaryNo = "100110110";document.write( numberOfPartitions(binaryNo)); // This code is contributed by itsok.</script> Output: 3 Time Complexity: O(n^2*log(x)), x = largest power of 4 or 6 obtainable from input string. Auxiliary Space: O(n) Vishal_Khoda ukasp itsok Algorithms Dynamic Programming Strings Strings Dynamic Programming Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 24299, "s": 24271, "text": "\n23 Apr, 2021" }, { "code": null, "e": 24516, "s": 24299, "text": "Given a string S composed of 0 and 1. Find the minimum splits such that the substring is a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such partitioning is possible. Examples: " }, { "code": null, "e": 24714, "s": 24516, "text": "Input: 100110110\nOutput: 3\nThe string can be split into a minimum of \nthree substrings 100(power of 4), 110\n(power of 6) and 110(power of 6).\n\nInput : 00000\nOutput : -1\n0 is not a power of 4 or 6." }, { "code": null, "e": 25804, "s": 24716, "text": "A simple solution is to split the string recursively at different indices and check if each split is a power of 4 or 6. Start with index 0 and split str[0] from other string. If it is a power of 4 or 6 then call recursively for index 1 and perform the same operation. When an entire string is split check if a total number of partitions are minimum so far or not. Then split str[0..1], check if it is the power of 4 or 6 and then call recursively for rest string. Compare partitions with minimum so far at the end of string traversal. This approach will be exponential in time.An efficient solution is to use Dynamic Programming. A 1-D dp table is created in which dp[i] stores minimum number of partitions required to split string str[i..n-1] into substrings that are power of 4 or 6. Suppose we are at index i and str[i..j] is power of 4 or 6, then minimum number of partitions will be minimum number of partitions to split str[j+1..n-1] plus one partition to split str[i..j] from string, that is dp[j+1] + 1. Hence the recurrence relation for (j!=(n-1)) and (dp[j + 1]!=-1) will be: " }, { "code": null, "e": 25838, "s": 25804, "text": "dp[i] = min(dp[i], dp[j + 1] + 1)" }, { "code": null, "e": 25856, "s": 25838, "text": "Implementation: " }, { "code": null, "e": 25860, "s": 25856, "text": "C++" }, { "code": null, "e": 25865, "s": 25860, "text": "Java" }, { "code": null, "e": 25874, "s": 25865, "text": "Python 3" }, { "code": null, "e": 25877, "s": 25874, "text": "C#" }, { "code": null, "e": 25888, "s": 25877, "text": "Javascript" }, { "code": "// CPP program for Minimum splits in a//string such that substring is a power of 4 or 6. #include <bits/stdc++.h>using namespace std; // Function to find if given number// is power of another number or not.bool isPowerOf(long val, int base){ // Divide given number repeatedly // by base value. while (val > 1) { if (val % base != 0) return false; // not a power val /= base; } return true;} // Function to find minimum number of// partitions of given binary string// so that each partition is power of 4 or 6.int numberOfPartitions(string binaryNo){ int i, j, n = binaryNo.length(); // Variable to store integer value of // given binary string partition. long val; // DP table to store results of // partitioning done at differentindices. int dp[n]; // If the last digit is 1, hence 4^0=1 and 6^0=1 dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1; // Fix starting position for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes is not allowed. if ((binaryNo[i] - '0') == 0) { dp[i] = -1; continue; } dp[i] = INT_MAX; // Iterate for all different partitions starting from i for (j = i; j < n; j++) { // Find integer value of current // binary partition. val = (val * 2) + (long)(binaryNo[j] - '0'); // Check if the value is a power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, then // make dp[i] = -1 to represent this. if (dp[i] == INT_MAX) dp[i] = -1; } return dp[0];} // Driver codeint main(){ string binaryNo = \"100110110\"; cout << numberOfPartitions(binaryNo); return 0;}", "e": 28012, "s": 25888, "text": null }, { "code": "// Java program for Minimum splits// in a string such that substring// is a power of 4 or 6.import java.io.*; class GFG{ static boolean isPowerOf(long val, int base){ // Divide given number // repeatedly by base value. while (val > 1) { if (val % base != 0) return false; // not a power val /= base; } return true;} // Function to find minimum// number of partitions of// given binary string so that// each partition is power// of 4 or 6.static int numberOfPartitions(String binaryNo){ int i, j, n = binaryNo.length(); // Variable to store integer // value of given binary // string partition. long val; // DP table to store results // of partitioning done at // differentindices. int dp[] = new int[n]; // If the last digit is 1, // hence 4^0=1 and 6^0=1 dp[n - 1] = (((binaryNo.charAt(n - 1) - '0') == 0) ? -1 : 1); // Fix starting position // for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes // is not allowed. if ((binaryNo.charAt(i) - '0') == 0) { dp[i] = -1; continue; } dp[i] = Integer.MAX_VALUE; // Iterate for all different // partitions starting from i for (j = i; j < n; j++) { // Find integer value of // current binary partition. val = (val * 2) + (long)(binaryNo.charAt(j) - '0'); // Check if the value is a // power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = Math.min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, // then make dp[i] = -1 to // represent this. if (dp[i] == Integer.MAX_VALUE) dp[i] = -1; } return dp[0];} // Driver codepublic static void main (String[] args){ String binaryNo = \"100110110\"; System.out.println(numberOfPartitions(binaryNo));}} // This code is contributed// by shiv_bhakt.", "e": 30502, "s": 28012, "text": null }, { "code": "# Python 3 program for Minimum# splits in a string such that# substring is a power of 4 or 6. import sys # Function to find if given number# is power of another number or not.def isPowerOf(val, base): # Divide given number repeatedly # by base value. while (val > 1): if (val % base != 0): return False # not a power val //= base return True # Function to find minimum number of# partitions of given binary string# so that each partition is power of 4 or 6.def numberOfPartitions(binaryNo): n = len(binaryNo) # DP table to store results of # partitioning done at differentindices. dp = [0] * n # If the last digit is 1, hence 4^0=1 and 6^0=1 if ((ord(binaryNo[n - 1]) - ord('0')) == 0) : dp[n - 1] = -1 else: dp[n - 1] = 1 # Fix starting position for partition for i in range( n - 2, -1, -1): val = 0 # Binary representation # with leading zeroes is not allowed. if ((ord(binaryNo[i]) - ord('0')) == 0): dp[i] = -1 continue dp[i] = sys.maxsize # Iterate for all different partitions starting from i for j in range(i, n): # Find integer value of current # binary partition. val = (val * 2) + (ord(binaryNo[j]) - ord('0')) # Check if the value is a power of 4 or 6 or not # apply recurrence relation if (isPowerOf(val, 4) or isPowerOf(val, 6)): if (j == n - 1): dp[i] = 1 else : if (dp[j + 1] != -1): dp[i] = min(dp[i], dp[j + 1] + 1) # If no partitions are possible, then # make dp[i] = -1 to represent this. if (dp[i] == sys.maxsize): dp[i] = -1 return dp[0] # Driver codeif __name__ == \"__main__\": binaryNo = \"100110110\" print(numberOfPartitions(binaryNo)) # This code is contributed by Ita_c. ", "e": 32486, "s": 30502, "text": null }, { "code": "// C# program for Minimum splits// in a string such that substring// is a power of 4 or 6. using System; class GFG{ static bool isPowerOf(long val, int b){ // Divide given number // repeatedly by base value. while (val > 1) { if (val % b != 0) return false; // not a power val /= b; } return true;} // Function to find minimum// number of partitions of// given binary string so that// each partition is power// of 4 or 6.static int numberOfPartitions(string binaryNo){ int i, j, n = binaryNo.Length; // Variable to store integer // value of given binary // string partition. long val; // DP table to store results // of partitioning done at // differentindices. int[] dp = new int[n]; // If the last digit is 1, // hence 4^0=1 and 6^0=1 dp[n - 1] = (((binaryNo[n - 1] - '0') == 0) ? -1 : 1); // Fix starting position // for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes // is not allowed. if ((binaryNo[i] - '0') == 0) { dp[i] = -1; continue; } dp[i] = int.MaxValue; // Iterate for all different // partitions starting from i for (j = i; j < n; j++) { // Find integer value of // current binary partition. val = (val * 2) + (long)(binaryNo[j] - '0'); // Check if the value is a // power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = Math.Min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, // then make dp[i] = -1 to // represent this. if (dp[i] == int.MaxValue) dp[i] = -1; } return dp[0];} // Driver codepublic static void Main (){ string binaryNo = \"100110110\"; Console.Write(numberOfPartitions(binaryNo));}}", "e": 34851, "s": 32486, "text": null }, { "code": "<script> // Javascript program for Minimum splits in a//string such that substring is a power of 4 or 6. // Function to find if given number// is power of another number or not.function isPowerOf(val, base){ // Divide given number repeatedly // by base value. while (val > 1) { if (val % base != 0) return false; // not a power val /= base; } return true;} // Function to find minimum number of// partitions of given binary string// so that each partition is power of 4 or 6.function numberOfPartitions(binaryNo){ var i, j, n = binaryNo.length; // Variable to store integer value of // given binary string partition. var val; // DP table to store results of // partitioning done at differentindices. var dp = Array(n); // If the last digit is 1, hence 4^0=1 and 6^0=1 dp[n - 1] = ((binaryNo[n - 1] - '0') == 0) ? -1 : 1; // Fix starting position for partition for (i = n - 2; i >= 0; i--) { val = 0; // Binary representation // with leading zeroes is not allowed. if ((binaryNo[i] - '0') == 0) { dp[i] = -1; continue; } dp[i] = 1000000000; // Iterate for all different partitions starting from i for (j = i; j < n; j++) { // Find integer value of current // binary partition. val = (val * 2) + (binaryNo[j] - '0'); // Check if the value is a power of 4 or 6 or not // apply recurrence relation if (isPowerOf(val, 4) || isPowerOf(val, 6)) { if (j == n - 1) { dp[i] = 1; } else { if (dp[j + 1] != -1) dp[i] = Math.min(dp[i], dp[j + 1] + 1); } } } // If no partitions are possible, then // make dp[i] = -1 to represent this. if (dp[i] == 1000000000) dp[i] = -1; } return dp[0];} // Driver codevar binaryNo = \"100110110\";document.write( numberOfPartitions(binaryNo)); // This code is contributed by itsok.</script>", "e": 36969, "s": 34851, "text": null }, { "code": null, "e": 36977, "s": 36969, "text": "Output:" }, { "code": null, "e": 36980, "s": 36977, "text": " 3" }, { "code": null, "e": 37093, "s": 36980, "text": "Time Complexity: O(n^2*log(x)), x = largest power of 4 or 6 obtainable from input string. Auxiliary Space: O(n) " }, { "code": null, "e": 37106, "s": 37093, "text": "Vishal_Khoda" }, { "code": null, "e": 37112, "s": 37106, "text": "ukasp" }, { "code": null, "e": 37118, "s": 37112, "text": "itsok" }, { "code": null, "e": 37129, "s": 37118, "text": "Algorithms" }, { "code": null, "e": 37149, "s": 37129, "text": "Dynamic Programming" }, { "code": null, "e": 37157, "s": 37149, "text": "Strings" }, { "code": null, "e": 37165, "s": 37157, "text": "Strings" }, { "code": null, "e": 37185, "s": 37165, "text": "Dynamic Programming" }, { "code": null, "e": 37196, "s": 37185, "text": "Algorithms" }, { "code": null, "e": 37294, "s": 37196, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37303, "s": 37294, "text": "Comments" }, { "code": null, "e": 37316, "s": 37303, "text": "Old Comments" }, { "code": null, "e": 37341, "s": 37316, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37397, "s": 37341, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 37440, "s": 37397, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 37469, "s": 37440, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 37503, "s": 37469, "text": "K means Clustering - Introduction" }, { "code": null, "e": 37532, "s": 37503, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 37562, "s": 37532, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 37594, "s": 37562, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 37628, "s": 37594, "text": "Longest Common Subsequence | DP-4" } ]
Mastering Query Plans in Spark 3.0 | by David Vrba | Towards Data Science
In Spark SQL the query plan is the entry point for understanding the details about the query execution. It carries lots of useful information and provides insights about how the query will be executed. This is very important especially in heavy workloads or whenever the execution takes to long and becomes costly. Based on the information from the query plan we may find out what is not efficient and decide to rewrite part of the query to achieve better performance. For someone not familiar with query plans, at first sight, the information may look a bit cryptic. It has a structure of a tree and each node represents an operator that provides some basic details about the execution. The official Spark documentation which is otherwise nicely written and very informative becomes insufficient when it comes to execution plans. The motivation for this article is to provide some familiarity with the physical plans, we will take a tour of some of the most frequently used operators and explain what information they provide and how it can be interpreted. The theory presented here is based mostly on the study of the Spark source code and on the practical experience with running and optimizing Spark queries on daily basis. For the sake of simplicity let’s consider a query in which we apply a filter, carry out an aggregation, and join with another DataFrame: # in PySpark API:query = ( questionsDF .filter(col('year') == 2019) .groupBy('user_id') .agg( count('*').alias('cnt') ) .join(usersDF, 'user_id')) You can think about the data in this example in such a way that usersDF is a set of users that are asking questions that are represented by questionsDF. The questions are partitioned by the year column which is a year when the question was asked. In the query, we are interested in questions asked in 2019 and for each user, we want to know how many questions he/she asked. Also for each user, we want to have some additional information in the output, that is why we join with the usersDF after the aggregation. There are two basic ways how to see the physical plan. The first one is by calling explain function on a DataFrame which shows a textual representation of the plan: There have been some improvements in Spark 3.0 in this regard and the explain function now takes a new argument mode. The value of this argument can be one of the following: formatted, cost, codegen. Using the formatted mode converts the query plan to a better organized output (here only part of the plan is displayed): So in the formatted plan, you can see the “naked” tree which has only the names of the operators with a number in parenthesis. Below the tree, there is then a detailed description of each operator referenced by the number. The cost mode will show besides the physical plan also the optimized logical plan with the statistics for each operator so you can see what are the estimates for the data size at different steps of execution. Finally, the codegen mode shows the generated java code that will be executed. The second option to see the plan is going to the SQL tab in Spark UI where are lists of all running and finished queries. By clicking on your query you will see the graphical representation of the physical plan. In the picture below I combined the graphical representation with the formatted textual tree to see how they correspond to each other: The difference here is that the graphical representation has the leaf nodes on the top and the root is at the bottom, while the textual tree is upside down. In the graphical representation of the physical plan, you can see that the operators are grouped into big blue rectangles. These big rectangles correspond to codegen stages. It is an optimization feature, which takes place in the phase of physical planning. There is a rule called CollapseCodegenStages which is responsible for that and the idea is to take operators that support code generation and collapse it together to speed-up the execution by eliminating virtual function calls. Not all operators support code generation, so some operators (for instance Exchange) are not part of the big rectangles. In our example, there are three codegen stages that correspond to three big rectangles and in the formatted plan output, you can see the id of the codegen stage in the brackets at the operator. Also from the tree, you can tell if an operator supports the codegen or not because there is an asterisk with corresponding stage codegen id in the parenthesis if the codegen is supported. Let’s now briefly describe how to interpret each of the operators in our query plan. The Scan parquet operator represents reading the data from a parquet file format. From the detailed information, you can directly see what columns will be selected from the source. Even though we do not select specific fields in our query, there is a ColumnPruning rule in the optimizer that will be applied and it makes sure that only those columns that are actually needed will be selected from the source. We can also see here two types of filters: PartitionFilters and PushedFilters. The PartitionFilters are filters that are applied on columns by which the datasource is partitioned in the file system. These are very important because they allow for skipping the data that we don’t need. It is always good to check whether the filters are propagated here correctly. The idea behind this is to read as little data as possible since the I/O is expensive. In Spark 2.4 there was also a field partitionCount which was the number of partitions that are actually scanned, but this field is no longer present in Spark 3.0. The PushedFilters are on the other hand filters on fields that can be pushed directly to parquet files and they can be useful if the parquet file is sorted by these filtered columns because in that case, we can leverage the internal parquet structure for data skipping as well. The parquet file is composed of row groups and the footer of the file contains metadata about each of these row groups. This metadata contains also statistical information such as min and max value for each row group and based on this information Spark can decide whether it will read the row group or not. The Filter operator is quite intuitive to understand, it simply represents the filtering condition. What may not be so obvious is how the operator was created because very often it doesn’t directly correspond to the filtering condition used in the query. The reason for that is that all the filters are first processed by the Catalyst optimizer which may modify and relocate them. There are several rules applied to the logical filters before they are converted to a physical operator. Let’s list a couple of the rules here: PushDownPredicates — this rule will push filters closer to the source through several other operators, but not all of them. For example, it will not push them through expressions that are not deterministic. If we use functions such as first, last, collect_set, collect_list, rand (and some other) the Filter will not be pushed through them because these functions are not deterministic in Spark. CombineFilters — combines two neighboring operators into one (it collects the conditions from two following filters into one complex condition). InferFiltersFromConstraints — this rule actually creates a new Filter operator for example from a join condition (from a simple inner join it will create a filter condition joining key is not null). PruneFilters — removes redundant filters (for example if a filter always evaluates to True). This operator simply represents what columns will be projected (selected). Each time we call select, withColumn, or drop transformations on a DataFrame, Spark will add the Project operator to the logical plan which is then converted to its counterpart in the physical plan. Again there are some optimization rules applied to it before it is converted: ColumnPruning — this is a rule we already mentioned above, it prunes the columns that are not needed to reduce the data volume that will be scanned. CollapseProject — it combines neighboring Project operators into one. PushProjectionThroughUnion — this rule will push the Project through both sides of the Union operator. The Exchange operator represents shuffle, which is a physical data movement on the cluster. This operation is considered to be quite expensive because it moves the data over the network. The information in the query plan contains also details about how the data will be repartitioned. In our example, it is hashpartitioning(user_id, 200) as you can see below: This means that the data will be repartitioned according to the user_id column into 200 partitions and all rows with the same value of user_id will belong to the same partition and will be located on the same executor. To make sure that exactly 200 partitions are created, Spark will always compute the hash of the user_id and then will compute positive modulo 200. The consequence of this is that more different user_ids will be located in the same partition. And what can also happen is that some partitions can become empty. There are other types of partitioning worth to mention: RoundRobinPartitioning — with this partitioning the data will be distributed randomly into n approximately equally sized partitions, where n is specified by the user in the repartition(n) function SinglePartition — with this partitioning all the data are moved to a single partition to a single executor. This happens for example when calling a window function where the window becomes the whole DataFrame (when you don’t provide an argument to the partitionBy() function in the Window definition). RangePartitioning — this partitioning is used when sorting the data, after calling orderBy or sort transformations. This operator represents data aggregation. It usually comes in pair of two operators which may or may not be divided by an Exchange as you can see here: To understand better the logic behind the Exchange in these situations you can check my previous article about data distribution in Spark SQL where I describe it in detail. The reason for having two HashAggregate operators is that the first one does a partial aggregation, which aggregates separately each partition on each executor. In our example, you can see in the Functions field that it says partial_count(1). The final merge of the partial results follows in the second HashAggregate. The operator also has the Keys field which shows the columns by which the data is grouped. The Results field shows the columns that are available after the aggregation. The BroadcastHashJoin (BHJ) is an operator that represents a specific joining algorithm. Apart from this one, there are also other joining algorithms available in Spark such as SortMergeJoin or ShuffleHashJoin and to read more about them you can check my other article about joins in Spark 3.0. The BHJ always comes in a pair with BroadcastExchange which is an operator that represents the broadcasted shuffle — the data will be collected to the driver and then send over to each executor where it will be available for the join. This is a new operator introduced in Spark 3.0 and it is used as a transition between columnar and row execution. The physical plans in Spark SQL are composed of operators that carry useful information about the execution. Having a proper understanding of each operator may help to get insights about the execution and by analyzing the plan we may discover what is not optimal and possibly try to fix it. In this article, we described a set of operators that are frequently used in Spark physical plans. The set is by no means complete but we tried to focus on operators that are commonly used and very likely to be present in plans of basic analytical queries.
[ { "code": null, "e": 640, "s": 171, "text": "In Spark SQL the query plan is the entry point for understanding the details about the query execution. It carries lots of useful information and provides insights about how the query will be executed. This is very important especially in heavy workloads or whenever the execution takes to long and becomes costly. Based on the information from the query plan we may find out what is not efficient and decide to rewrite part of the query to achieve better performance." }, { "code": null, "e": 1229, "s": 640, "text": "For someone not familiar with query plans, at first sight, the information may look a bit cryptic. It has a structure of a tree and each node represents an operator that provides some basic details about the execution. The official Spark documentation which is otherwise nicely written and very informative becomes insufficient when it comes to execution plans. The motivation for this article is to provide some familiarity with the physical plans, we will take a tour of some of the most frequently used operators and explain what information they provide and how it can be interpreted." }, { "code": null, "e": 1399, "s": 1229, "text": "The theory presented here is based mostly on the study of the Spark source code and on the practical experience with running and optimizing Spark queries on daily basis." }, { "code": null, "e": 1536, "s": 1399, "text": "For the sake of simplicity let’s consider a query in which we apply a filter, carry out an aggregation, and join with another DataFrame:" }, { "code": null, "e": 1693, "s": 1536, "text": "# in PySpark API:query = ( questionsDF .filter(col('year') == 2019) .groupBy('user_id') .agg( count('*').alias('cnt') ) .join(usersDF, 'user_id'))" }, { "code": null, "e": 2206, "s": 1693, "text": "You can think about the data in this example in such a way that usersDF is a set of users that are asking questions that are represented by questionsDF. The questions are partitioned by the year column which is a year when the question was asked. In the query, we are interested in questions asked in 2019 and for each user, we want to know how many questions he/she asked. Also for each user, we want to have some additional information in the output, that is why we join with the usersDF after the aggregation." }, { "code": null, "e": 2371, "s": 2206, "text": "There are two basic ways how to see the physical plan. The first one is by calling explain function on a DataFrame which shows a textual representation of the plan:" }, { "code": null, "e": 2692, "s": 2371, "text": "There have been some improvements in Spark 3.0 in this regard and the explain function now takes a new argument mode. The value of this argument can be one of the following: formatted, cost, codegen. Using the formatted mode converts the query plan to a better organized output (here only part of the plan is displayed):" }, { "code": null, "e": 3203, "s": 2692, "text": "So in the formatted plan, you can see the “naked” tree which has only the names of the operators with a number in parenthesis. Below the tree, there is then a detailed description of each operator referenced by the number. The cost mode will show besides the physical plan also the optimized logical plan with the statistics for each operator so you can see what are the estimates for the data size at different steps of execution. Finally, the codegen mode shows the generated java code that will be executed." }, { "code": null, "e": 3551, "s": 3203, "text": "The second option to see the plan is going to the SQL tab in Spark UI where are lists of all running and finished queries. By clicking on your query you will see the graphical representation of the physical plan. In the picture below I combined the graphical representation with the formatted textual tree to see how they correspond to each other:" }, { "code": null, "e": 3708, "s": 3551, "text": "The difference here is that the graphical representation has the leaf nodes on the top and the root is at the bottom, while the textual tree is upside down." }, { "code": null, "e": 4698, "s": 3708, "text": "In the graphical representation of the physical plan, you can see that the operators are grouped into big blue rectangles. These big rectangles correspond to codegen stages. It is an optimization feature, which takes place in the phase of physical planning. There is a rule called CollapseCodegenStages which is responsible for that and the idea is to take operators that support code generation and collapse it together to speed-up the execution by eliminating virtual function calls. Not all operators support code generation, so some operators (for instance Exchange) are not part of the big rectangles. In our example, there are three codegen stages that correspond to three big rectangles and in the formatted plan output, you can see the id of the codegen stage in the brackets at the operator. Also from the tree, you can tell if an operator supports the codegen or not because there is an asterisk with corresponding stage codegen id in the parenthesis if the codegen is supported." }, { "code": null, "e": 4783, "s": 4698, "text": "Let’s now briefly describe how to interpret each of the operators in our query plan." }, { "code": null, "e": 5805, "s": 4783, "text": "The Scan parquet operator represents reading the data from a parquet file format. From the detailed information, you can directly see what columns will be selected from the source. Even though we do not select specific fields in our query, there is a ColumnPruning rule in the optimizer that will be applied and it makes sure that only those columns that are actually needed will be selected from the source. We can also see here two types of filters: PartitionFilters and PushedFilters. The PartitionFilters are filters that are applied on columns by which the datasource is partitioned in the file system. These are very important because they allow for skipping the data that we don’t need. It is always good to check whether the filters are propagated here correctly. The idea behind this is to read as little data as possible since the I/O is expensive. In Spark 2.4 there was also a field partitionCount which was the number of partitions that are actually scanned, but this field is no longer present in Spark 3.0." }, { "code": null, "e": 6390, "s": 5805, "text": "The PushedFilters are on the other hand filters on fields that can be pushed directly to parquet files and they can be useful if the parquet file is sorted by these filtered columns because in that case, we can leverage the internal parquet structure for data skipping as well. The parquet file is composed of row groups and the footer of the file contains metadata about each of these row groups. This metadata contains also statistical information such as min and max value for each row group and based on this information Spark can decide whether it will read the row group or not." }, { "code": null, "e": 6915, "s": 6390, "text": "The Filter operator is quite intuitive to understand, it simply represents the filtering condition. What may not be so obvious is how the operator was created because very often it doesn’t directly correspond to the filtering condition used in the query. The reason for that is that all the filters are first processed by the Catalyst optimizer which may modify and relocate them. There are several rules applied to the logical filters before they are converted to a physical operator. Let’s list a couple of the rules here:" }, { "code": null, "e": 7311, "s": 6915, "text": "PushDownPredicates — this rule will push filters closer to the source through several other operators, but not all of them. For example, it will not push them through expressions that are not deterministic. If we use functions such as first, last, collect_set, collect_list, rand (and some other) the Filter will not be pushed through them because these functions are not deterministic in Spark." }, { "code": null, "e": 7456, "s": 7311, "text": "CombineFilters — combines two neighboring operators into one (it collects the conditions from two following filters into one complex condition)." }, { "code": null, "e": 7655, "s": 7456, "text": "InferFiltersFromConstraints — this rule actually creates a new Filter operator for example from a join condition (from a simple inner join it will create a filter condition joining key is not null)." }, { "code": null, "e": 7748, "s": 7655, "text": "PruneFilters — removes redundant filters (for example if a filter always evaluates to True)." }, { "code": null, "e": 8100, "s": 7748, "text": "This operator simply represents what columns will be projected (selected). Each time we call select, withColumn, or drop transformations on a DataFrame, Spark will add the Project operator to the logical plan which is then converted to its counterpart in the physical plan. Again there are some optimization rules applied to it before it is converted:" }, { "code": null, "e": 8249, "s": 8100, "text": "ColumnPruning — this is a rule we already mentioned above, it prunes the columns that are not needed to reduce the data volume that will be scanned." }, { "code": null, "e": 8319, "s": 8249, "text": "CollapseProject — it combines neighboring Project operators into one." }, { "code": null, "e": 8422, "s": 8319, "text": "PushProjectionThroughUnion — this rule will push the Project through both sides of the Union operator." }, { "code": null, "e": 8782, "s": 8422, "text": "The Exchange operator represents shuffle, which is a physical data movement on the cluster. This operation is considered to be quite expensive because it moves the data over the network. The information in the query plan contains also details about how the data will be repartitioned. In our example, it is hashpartitioning(user_id, 200) as you can see below:" }, { "code": null, "e": 9366, "s": 8782, "text": "This means that the data will be repartitioned according to the user_id column into 200 partitions and all rows with the same value of user_id will belong to the same partition and will be located on the same executor. To make sure that exactly 200 partitions are created, Spark will always compute the hash of the user_id and then will compute positive modulo 200. The consequence of this is that more different user_ids will be located in the same partition. And what can also happen is that some partitions can become empty. There are other types of partitioning worth to mention:" }, { "code": null, "e": 9563, "s": 9366, "text": "RoundRobinPartitioning — with this partitioning the data will be distributed randomly into n approximately equally sized partitions, where n is specified by the user in the repartition(n) function" }, { "code": null, "e": 9865, "s": 9563, "text": "SinglePartition — with this partitioning all the data are moved to a single partition to a single executor. This happens for example when calling a window function where the window becomes the whole DataFrame (when you don’t provide an argument to the partitionBy() function in the Window definition)." }, { "code": null, "e": 9981, "s": 9865, "text": "RangePartitioning — this partitioning is used when sorting the data, after calling orderBy or sort transformations." }, { "code": null, "e": 10134, "s": 9981, "text": "This operator represents data aggregation. It usually comes in pair of two operators which may or may not be divided by an Exchange as you can see here:" }, { "code": null, "e": 10795, "s": 10134, "text": "To understand better the logic behind the Exchange in these situations you can check my previous article about data distribution in Spark SQL where I describe it in detail. The reason for having two HashAggregate operators is that the first one does a partial aggregation, which aggregates separately each partition on each executor. In our example, you can see in the Functions field that it says partial_count(1). The final merge of the partial results follows in the second HashAggregate. The operator also has the Keys field which shows the columns by which the data is grouped. The Results field shows the columns that are available after the aggregation." }, { "code": null, "e": 11325, "s": 10795, "text": "The BroadcastHashJoin (BHJ) is an operator that represents a specific joining algorithm. Apart from this one, there are also other joining algorithms available in Spark such as SortMergeJoin or ShuffleHashJoin and to read more about them you can check my other article about joins in Spark 3.0. The BHJ always comes in a pair with BroadcastExchange which is an operator that represents the broadcasted shuffle — the data will be collected to the driver and then send over to each executor where it will be available for the join." }, { "code": null, "e": 11439, "s": 11325, "text": "This is a new operator introduced in Spark 3.0 and it is used as a transition between columnar and row execution." }, { "code": null, "e": 11730, "s": 11439, "text": "The physical plans in Spark SQL are composed of operators that carry useful information about the execution. Having a proper understanding of each operator may help to get insights about the execution and by analyzing the plan we may discover what is not optimal and possibly try to fix it." } ]
SORT command in Linux/Unix with examples - GeeksforGeeks
11 Feb, 2022 SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming the contents are ASCII. Using options in the sort command can also be used to sort numerically. SORT command sorts the contents of a text file, line by line. sort is a standard command-line program that prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The sort command is a command-line utility for sorting lines of text files. It supports sorting alphabetically, in reverse order, by number, by month, and can also remove duplicates. The sort command can also sort by items not at the beginning of the line, ignore case sensitivity, and return whether a file is sorted or not. Sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as the sort key. Blank space is the default field separator. The sort command follows these features as stated below: Lines starting with a number will appear before lines starting with a letter. Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet. Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase. Lines starting with a number will appear before lines starting with a letter. Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet. Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase. Examples Suppose you create a data file with name file.txt: Command : $ cat > file.txt abhishek chitransh satish rajan naveen divyam harsh Sorting a file: Now use the sort command Syntax : $ sort filename.txt Command: $ sort file.txt Output : abhishek chitransh divyam harsh naveen rajan satish Note: This command does not actually change the input file, i.e. file.txt. Sort function with mix file i.e. uppercase and lower case: When we have a mix file with both uppercase and lowercase letters then first the upper case letters would be sorted following with the lower case letters. Example: Create a file mix.txt Command : $ cat > mix.txt abc apple BALL Abc bat Now use the sort command Command : $ sort mix.txt Output : Abc BALL abc apple bat Options with sort function: 1. -o Option: Unix also provides us with special facilities like if you want to write the output to a new file, output.txt, redirects the output like this or you can also use the built-in sort option -o, which allows you to specify an output file. Using the -o option is functionally the same as redirecting the output to a file. Note: Neither one has an advantage over the other. Example: The input file is the same as mentioned above. Syntax: $ sort inputfile.txt > filename.txt $ sort -o filename.txt inputfile.txt Command: $ sort file.txt > output.txt $ sort -o output.txt file.txt $ cat output.txt Output : abhishek chitransh divyam harsh naveen rajan satish 2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. Example: The input file is the same as mentioned above. Syntax : $ sort -r inputfile.txt Command : $ sort -r file.txt Output : satish rajan naveen harsh divyam chitransh abhishek 3. -n Option: To sort a file numerically used –n option. -n option is also predefined in Unix as the above options are. This option is used to sort the file with numeric data present inside. Example : Let us consider a file with numbers: Command : $ cat > file1.txt 50 39 15 89 200 Syntax: $ sort -n filename.txt Command : $ sort -n file1.txt Output : 15 39 50 89 200 4. -nr option: To sort a file with numeric data in reverse order we can use the combination of two options as stated below. Example: The numeric file is the same as above. Syntax : $ sort -nr filename.txt Command : $ sort -nr file1.txt Output : 200 89 50 39 15 5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column. Example : Let us create a table with 2 columns $ cat > employee.txt manager 5000 clerk 4000 employee 6000 peon 4500 director 9000 guard 3000 Syntax : $ sort -k filename.txt Command : $ sort -k 2n employee.txt guard 3000 clerk 4000 peon 4500 manager 5000 employee 6000 director 9000 6. -c option: This option is used to check if the file given is already sorted or not & checks if a file is already sorted pass the -c option to sort. This will write to standard output if there are lines that are out of order. The sort tool can be used to understand if this file is sorted and which lines are out of order Example : Suppose a file exists with a list of cars called cars.txt. Audi Cadillac BMW Dodge Syntax : $ sort -c filename.txt Command : $ sort -c cars.txt Output : sort: cars.txt:3: disorder: BMW Note : If there is no output then the file is considered to be already sorted 7. -u option: To sort and remove duplicates pass the -u option to sort. This will write a sorted list to standard output and remove duplicates. This option is helpful as the duplicates being removed give us a redundant file. Example: Suppose a file exists with a list of cars called cars.txt. Audi BMW Cadillac BMW Dodge Syntax : $ sort -u filename.txt Command : $ sort -u cars.txt $ cat cars.txt Output : Audi BMW Cadillac Dodge 8. -M Option: To sort by month pass the -M option to sort. This will write a sorted list to standard output ordered by month name. Example: Suppose the following file exists and is saved as months.txt $ cat > months.txt February January March August September Syntax : $ sort -M filename.txt Using The -M option with sort allows us to order this file. Command : $ sort -M months.txt $ cat months.txt Output : January February March August September Application and uses of sort command: It can sort any type of file be it table file text file numeric file and so on. Sorting can be directly implemented from one file to another without the present work being hampered. Sorting of table files on the basis of columns has been made way simpler and easier. So many options are available for sorting in all possible ways. The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided. Original data is always safe and not hampered. It can sort any type of file be it table file text file numeric file and so on. Sorting can be directly implemented from one file to another without the present work being hampered. Sorting of table files on the basis of columns has been made way simpler and easier. So many options are available for sorting in all possible ways. The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided. Original data is always safe and not hampered. TechFukrey roopal jangid mahajanrohanraj9 linux-command Linux-text-processing-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples echo command in Linux with Examples touch command in Linux with Examples Tail command in Linux with examples Compiling with g++ Mutex lock for Linux Thread Synchronization ps command in Linux with Examples
[ { "code": null, "e": 23641, "s": 23610, "text": " \n11 Feb, 2022\n" }, { "code": null, "e": 23869, "s": 23641, "text": "SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming the contents are ASCII. Using options in the sort command can also be used to sort numerically. " }, { "code": null, "e": 23931, "s": 23869, "text": "SORT command sorts the contents of a text file, line by line." }, { "code": null, "e": 24081, "s": 23931, "text": "sort is a standard command-line program that prints the lines of its input or concatenation of all files listed in its argument list in sorted order." }, { "code": null, "e": 24264, "s": 24081, "text": "The sort command is a command-line utility for sorting lines of text files. It supports sorting alphabetically, in reverse order, by number, by month, and can also remove duplicates." }, { "code": null, "e": 24489, "s": 24264, "text": "The sort command can also sort by items not at the beginning of the line, ignore case sensitivity, and return whether a file is sorted or not. Sorting is done based on one or more sort keys extracted from each line of input." }, { "code": null, "e": 24588, "s": 24489, "text": "By default, the entire input is taken as the sort key. Blank space is the default field separator." }, { "code": null, "e": 24647, "s": 24588, "text": "The sort command follows these features as stated below: " }, { "code": null, "e": 24985, "s": 24647, "text": "\nLines starting with a number will appear before lines starting with a letter.\nLines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet.\nLines starting with a uppercase letter will appear before lines starting with the same letter in lowercase.\n" }, { "code": null, "e": 25063, "s": 24985, "text": "Lines starting with a number will appear before lines starting with a letter." }, { "code": null, "e": 25213, "s": 25063, "text": "Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet." }, { "code": null, "e": 25321, "s": 25213, "text": "Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase." }, { "code": null, "e": 25330, "s": 25321, "text": "Examples" }, { "code": null, "e": 25382, "s": 25330, "text": "Suppose you create a data file with name file.txt: " }, { "code": null, "e": 25462, "s": 25382, "text": "Command : \n$ cat > file.txt\nabhishek\nchitransh\nsatish\nrajan\nnaveen\ndivyam\nharsh" }, { "code": null, "e": 25504, "s": 25462, "text": "Sorting a file: Now use the sort command " }, { "code": null, "e": 25514, "s": 25504, "text": "Syntax : " }, { "code": null, "e": 25534, "s": 25514, "text": "$ sort filename.txt" }, { "code": null, "e": 25622, "s": 25534, "text": "Command:\n$ sort file.txt\n\nOutput :\nabhishek\nchitransh\ndivyam\nharsh\nnaveen \nrajan\nsatish" }, { "code": null, "e": 25698, "s": 25622, "text": "Note: This command does not actually change the input file, i.e. file.txt. " }, { "code": null, "e": 25912, "s": 25698, "text": "Sort function with mix file i.e. uppercase and lower case: When we have a mix file with both uppercase and lowercase letters then first the upper case letters would be sorted following with the lower case letters." }, { "code": null, "e": 25922, "s": 25912, "text": "Example: " }, { "code": null, "e": 25945, "s": 25922, "text": "Create a file mix.txt " }, { "code": null, "e": 25994, "s": 25945, "text": "Command :\n$ cat > mix.txt\nabc\napple\nBALL\nAbc\nbat" }, { "code": null, "e": 26020, "s": 25994, "text": "Now use the sort command " }, { "code": null, "e": 26666, "s": 26020, "text": "Command :\n$ sort mix.txt\nOutput :\nAbc \nBALL \nabc \napple \nbat" }, { "code": null, "e": 26694, "s": 26666, "text": "Options with sort function:" }, { "code": null, "e": 26943, "s": 26694, "text": "1. -o Option: Unix also provides us with special facilities like if you want to write the output to a new file, output.txt, redirects the output like this or you can also use the built-in sort option -o, which allows you to specify an output file. " }, { "code": null, "e": 27026, "s": 26943, "text": "Using the -o option is functionally the same as redirecting the output to a file. " }, { "code": null, "e": 27078, "s": 27026, "text": "Note: Neither one has an advantage over the other. " }, { "code": null, "e": 27135, "s": 27078, "text": "Example: The input file is the same as mentioned above. " }, { "code": null, "e": 27143, "s": 27135, "text": "Syntax:" }, { "code": null, "e": 27216, "s": 27143, "text": "$ sort inputfile.txt > filename.txt\n$ sort -o filename.txt inputfile.txt" }, { "code": null, "e": 27365, "s": 27216, "text": "Command:\n$ sort file.txt > output.txt \n$ sort -o output.txt file.txt\n$ cat output.txt\n\nOutput :\nabhishek\nchitransh\ndivyam\nharsh\nnaveen \nrajan\nsatish" }, { "code": null, "e": 27585, "s": 27365, "text": "2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. " }, { "code": null, "e": 27642, "s": 27585, "text": "Example: The input file is the same as mentioned above. " }, { "code": null, "e": 27652, "s": 27642, "text": "Syntax : " }, { "code": null, "e": 27676, "s": 27652, "text": "$ sort -r inputfile.txt" }, { "code": null, "e": 27767, "s": 27676, "text": "Command :\n$ sort -r file.txt\nOutput :\nsatish\nrajan\nnaveen \nharsh\ndivyam\nchitransh\nabhishek" }, { "code": null, "e": 27959, "s": 27767, "text": "3. -n Option: To sort a file numerically used –n option. -n option is also predefined in Unix as the above options are. This option is used to sort the file with numeric data present inside. " }, { "code": null, "e": 27970, "s": 27959, "text": "Example : " }, { "code": null, "e": 28008, "s": 27970, "text": "Let us consider a file with numbers: " }, { "code": null, "e": 28052, "s": 28008, "text": "Command :\n$ cat > file1.txt\n50\n39\n15\n89\n200" }, { "code": null, "e": 28060, "s": 28052, "text": "Syntax:" }, { "code": null, "e": 28083, "s": 28060, "text": "$ sort -n filename.txt" }, { "code": null, "e": 28138, "s": 28083, "text": "Command :\n$ sort -n file1.txt\nOutput :\n15\n39\n50\n89\n200" }, { "code": null, "e": 28263, "s": 28138, "text": "4. -nr option: To sort a file with numeric data in reverse order we can use the combination of two options as stated below. " }, { "code": null, "e": 28312, "s": 28263, "text": "Example: The numeric file is the same as above. " }, { "code": null, "e": 28322, "s": 28312, "text": "Syntax : " }, { "code": null, "e": 28346, "s": 28322, "text": "$ sort -nr filename.txt" }, { "code": null, "e": 28402, "s": 28346, "text": "Command :\n$ sort -nr file1.txt\nOutput :\n200\n89\n50\n39\n15" }, { "code": null, "e": 28516, "s": 28402, "text": "5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. " }, { "code": null, "e": 28618, "s": 28516, "text": "Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column. " }, { "code": null, "e": 28629, "s": 28618, "text": "Example : " }, { "code": null, "e": 28667, "s": 28629, "text": "Let us create a table with 2 columns " }, { "code": null, "e": 28774, "s": 28667, "text": "$ cat > employee.txt\nmanager 5000\nclerk 4000\nemployee 6000\npeon 4500\ndirector 9000\nguard 3000" }, { "code": null, "e": 28783, "s": 28774, "text": "Syntax :" }, { "code": null, "e": 28806, "s": 28783, "text": "$ sort -k filename.txt" }, { "code": null, "e": 28926, "s": 28806, "text": "Command :\n$ sort -k 2n employee.txt\nguard 3000\nclerk 4000\npeon 4500\nmanager 5000\nemployee 6000\ndirector 9000" }, { "code": null, "e": 29251, "s": 28926, "text": "6. -c option: This option is used to check if the file given is already sorted or not & checks if a file is already sorted pass the -c option to sort. This will write to standard output if there are lines that are out of order. The sort tool can be used to understand if this file is sorted and which lines are out of order " }, { "code": null, "e": 29262, "s": 29251, "text": "Example : " }, { "code": null, "e": 29322, "s": 29262, "text": "Suppose a file exists with a list of cars called cars.txt. " }, { "code": null, "e": 29346, "s": 29322, "text": "Audi\nCadillac\nBMW\nDodge" }, { "code": null, "e": 29355, "s": 29346, "text": "Syntax :" }, { "code": null, "e": 29378, "s": 29355, "text": "$ sort -c filename.txt" }, { "code": null, "e": 29528, "s": 29378, "text": "Command :\n$ sort -c cars.txt\nOutput :\nsort: cars.txt:3: disorder: BMW\n Note : If there is no output then the file is considered to be already sorted " }, { "code": null, "e": 29754, "s": 29528, "text": "7. -u option: To sort and remove duplicates pass the -u option to sort. This will write a sorted list to standard output and remove duplicates. This option is helpful as the duplicates being removed give us a redundant file. " }, { "code": null, "e": 29823, "s": 29754, "text": "Example: Suppose a file exists with a list of cars called cars.txt. " }, { "code": null, "e": 29851, "s": 29823, "text": "Audi\nBMW\nCadillac\nBMW\nDodge" }, { "code": null, "e": 29860, "s": 29851, "text": "Syntax :" }, { "code": null, "e": 29883, "s": 29860, "text": "$ sort -u filename.txt" }, { "code": null, "e": 29960, "s": 29883, "text": "Command :\n$ sort -u cars.txt\n$ cat cars.txt\nOutput :\nAudi\nBMW\nCadillac\nDodge" }, { "code": null, "e": 30092, "s": 29960, "text": "8. -M Option: To sort by month pass the -M option to sort. This will write a sorted list to standard output ordered by month name. " }, { "code": null, "e": 30102, "s": 30092, "text": "Example: " }, { "code": null, "e": 30164, "s": 30102, "text": "Suppose the following file exists and is saved as months.txt " }, { "code": null, "e": 30183, "s": 30164, "text": "$ cat > months.txt" }, { "code": null, "e": 30238, "s": 30183, "text": "February \nJanuary \nMarch \nAugust \nSeptember \n\nSyntax :" }, { "code": null, "e": 30261, "s": 30238, "text": "$ sort -M filename.txt" }, { "code": null, "e": 30321, "s": 30261, "text": "Using The -M option with sort allows us to order this file." }, { "code": null, "e": 30418, "s": 30321, "text": "Command :\n$ sort -M months.txt\n$ cat months.txt\nOutput :\nJanuary\nFebruary\nMarch\nAugust\nSeptember" }, { "code": null, "e": 30456, "s": 30418, "text": "Application and uses of sort command:" }, { "code": null, "e": 30963, "s": 30456, "text": "\nIt can sort any type of file be it table file text file numeric file and so on.\nSorting can be directly implemented from one file to another without the present work being hampered.\nSorting of table files on the basis of columns has been made way simpler and easier.\nSo many options are available for sorting in all possible ways.\nThe most beneficial use is that a particular data file can be used many times as no change is made in the input file provided.\nOriginal data is always safe and not hampered.\n" }, { "code": null, "e": 31043, "s": 30963, "text": "It can sort any type of file be it table file text file numeric file and so on." }, { "code": null, "e": 31145, "s": 31043, "text": "Sorting can be directly implemented from one file to another without the present work being hampered." }, { "code": null, "e": 31230, "s": 31145, "text": "Sorting of table files on the basis of columns has been made way simpler and easier." }, { "code": null, "e": 31294, "s": 31230, "text": "So many options are available for sorting in all possible ways." }, { "code": null, "e": 31421, "s": 31294, "text": "The most beneficial use is that a particular data file can be used many times as no change is made in the input file provided." }, { "code": null, "e": 31468, "s": 31421, "text": "Original data is always safe and not hampered." }, { "code": null, "e": 31479, "s": 31468, "text": "TechFukrey" }, { "code": null, "e": 31493, "s": 31479, "text": "roopal jangid" }, { "code": null, "e": 31510, "s": 31493, "text": "mahajanrohanraj9" }, { "code": null, "e": 31526, "s": 31510, "text": "\nlinux-command\n" }, { "code": null, "e": 31559, "s": 31526, "text": "\nLinux-text-processing-commands\n" }, { "code": null, "e": 31572, "s": 31559, "text": "\nLinux-Unix\n" }, { "code": null, "e": 31777, "s": 31572, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 31812, "s": 31777, "text": "tar command in Linux with examples" }, { "code": null, "e": 31850, "s": 31812, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 31888, "s": 31850, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 31923, "s": 31888, "text": "Cat command in Linux with examples" }, { "code": null, "e": 31959, "s": 31923, "text": "echo command in Linux with Examples" }, { "code": null, "e": 31996, "s": 31959, "text": "touch command in Linux with Examples" }, { "code": null, "e": 32032, "s": 31996, "text": "Tail command in Linux with examples" }, { "code": null, "e": 32051, "s": 32032, "text": "Compiling with g++" }, { "code": null, "e": 32095, "s": 32051, "text": "Mutex lock for Linux Thread Synchronization" } ]
LinkedList in Java - GeeksforGeeks
08 Apr, 2022 Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. It also has a few disadvantages like the nodes cannot be accessed directly instead we need to start from the head and follow through the link to reach a node we wish to access. How Does LinkedList work Internally? Since a LinkedList acts as a dynamic array and we do not have to specify the size while creating it, the size of the list automatically increases when we dynamically add and remove items. And also, the elements are not stored in a continuous fashion. Therefore, there is no need to increase the size. Internally, the LinkedList is implemented using the doubly linked list data structure. The main difference between a normal linked list and a doubly LinkedList is that a doubly linked list contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in the singly linked list. In order to create a LinkedList, we need to create an object of the LinkedList class. The LinkedList class consists of various constructors that allow the possible creation of the list. The following are the constructors available in this class: 1. LinkedList(): This constructor is used to create an empty linked list. If we wish to create an empty LinkedList with the name ll, then, it can be created as: LinkedList ll = new LinkedList(); 2. LinkedList(Collection C): This constructor is used to create an ordered list that contains all the elements of a specified collection, as returned by the collection’s iterator. If we wish to create a LinkedList with the name ll, then, it can be created as: LinkedList ll = new LinkedList(C); Example: Java // Java Program to Demonstrate// Implementation of LinkedList// class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating object of the // class linked list LinkedList<String> ll = new LinkedList<String>(); // Adding elements to the linked list ll.add("A"); ll.add("B"); ll.addLast("C"); ll.addFirst("D"); ll.add(2, "E"); System.out.println(ll); ll.remove("B"); ll.remove(3); ll.removeFirst(); ll.removeLast(); System.out.println(ll); }} [D, A, E, B, C] [A] In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are: AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list. Adding elementsUpdating elementsRemoving elementsIterating over elements Adding elements Updating elements Removing elements Iterating over elements Let us see how to perform some basic operations on LinkedList to understand it better as follows: Operation 1: Adding Elements In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are: add(Object): This method is used to add an element at the end of the LinkedList. add(int index, Object): This method is used to add an element at a specific index in the LinkedList. Example: Java // Java program to add elements// to a LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add("Geeks"); ll.add("Geeks"); ll.add(1, "For"); System.out.println(ll); }} [Geeks, For, Geeks] Operation 2: Changing Elements After adding the elements, if we wish to change the element, it can be done using the set() method. Since a LinkedList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index. Example: Java // Java program to change elements// in a LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add("Geeks"); ll.add("Geeks"); ll.add(1, "Geeks"); System.out.println("Initial LinkedList " + ll); ll.set(1, "For"); System.out.println("Updated LinkedList " + ll); }} Initial LinkedList [Geeks, Geeks, Geeks] Updated LinkedList [Geeks, For, Geeks] Operation 3: Removing Elements In order to remove an element from a LinkedList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are: remove(Object): This method is used to simply remove an object from the LinkedList. If there are multiple such objects, then the first occurrence of the object is removed. remove(int index): Since a LinkedList is indexed, this method takes an integer value which simply removes the element present at that specific index in the LinkedList. After removing the element and the indices of elements are updated so do the object of LinkedList is updated giving a new List after the deletion of element/s. Example: Java // Java program to remove elements// in a LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add("Geeks"); ll.add("Geeks"); ll.add(1, "For"); System.out.println( "Initial LinkedList " + ll); ll.remove(1); System.out.println( "After the Index Removal " + ll); ll.remove("Geeks"); System.out.println( "After the Object Removal " + ll); }} Initial LinkedList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks] Operation 4: Iterating the LinkedList There are multiple ways to iterate through LinkedList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for-loop. Example: Java // Java program to iterate the elements// in an LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add("Geeks"); ll.add("Geeks"); ll.add(1, "For"); // Using the Get method and the // for loop for (int i = 0; i < ll.size(); i++) { System.out.print(ll.get(i) + " "); } System.out.println(); // Using the for each loop for (String str : ll) System.out.print(str + " "); }} Geeks For Geeks Geeks For Geeks Chinmoy Lenka Amrutesh99 KaashyapMSK 19ucs197 solankimayank surinderdawra388 Java - util package Java-Collections java-LinkedList java-list Java Linked List Linked List Java Java-Collections 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 Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 28637, "s": 28609, "text": "\n08 Apr, 2022" }, { "code": null, "e": 29307, "s": 28637, "text": "Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. Due to the dynamicity and ease of insertions and deletions, they are preferred over the arrays. It also has a few disadvantages like the nodes cannot be accessed directly instead we need to start from the head and follow through the link to reach a node we wish to access." }, { "code": null, "e": 29344, "s": 29307, "text": "How Does LinkedList work Internally?" }, { "code": null, "e": 29985, "s": 29344, "text": "Since a LinkedList acts as a dynamic array and we do not have to specify the size while creating it, the size of the list automatically increases when we dynamically add and remove items. And also, the elements are not stored in a continuous fashion. Therefore, there is no need to increase the size. Internally, the LinkedList is implemented using the doubly linked list data structure. The main difference between a normal linked list and a doubly LinkedList is that a doubly linked list contains an extra pointer, typically called the previous pointer, together with the next pointer and data which are there in the singly linked list. " }, { "code": null, "e": 30232, "s": 29985, "text": "In order to create a LinkedList, we need to create an object of the LinkedList class. The LinkedList class consists of various constructors that allow the possible creation of the list. The following are the constructors available in this class: " }, { "code": null, "e": 30394, "s": 30232, "text": "1. LinkedList(): This constructor is used to create an empty linked list. If we wish to create an empty LinkedList with the name ll, then, it can be created as: " }, { "code": null, "e": 30430, "s": 30394, "text": "LinkedList ll = new LinkedList(); " }, { "code": null, "e": 30691, "s": 30430, "text": "2. LinkedList(Collection C): This constructor is used to create an ordered list that contains all the elements of a specified collection, as returned by the collection’s iterator. If we wish to create a LinkedList with the name ll, then, it can be created as: " }, { "code": null, "e": 30726, "s": 30691, "text": "LinkedList ll = new LinkedList(C);" }, { "code": null, "e": 30735, "s": 30726, "text": "Example:" }, { "code": null, "e": 30740, "s": 30735, "text": "Java" }, { "code": "// Java Program to Demonstrate// Implementation of LinkedList// class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating object of the // class linked list LinkedList<String> ll = new LinkedList<String>(); // Adding elements to the linked list ll.add(\"A\"); ll.add(\"B\"); ll.addLast(\"C\"); ll.addFirst(\"D\"); ll.add(2, \"E\"); System.out.println(ll); ll.remove(\"B\"); ll.remove(3); ll.removeFirst(); ll.removeLast(); System.out.println(ll); }}", "e": 31404, "s": 30740, "text": null }, { "code": null, "e": 31424, "s": 31404, "text": "[D, A, E, B, C]\n[A]" }, { "code": null, "e": 31655, "s": 31426, "text": "In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:" }, { "code": null, "e": 32044, "s": 31655, "text": "AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list." }, { "code": null, "e": 32224, "s": 32044, "text": "AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods." }, { "code": null, "e": 32434, "s": 32224, "text": "CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list." }, { "code": null, "e": 32507, "s": 32434, "text": "Adding elementsUpdating elementsRemoving elementsIterating over elements" }, { "code": null, "e": 32523, "s": 32507, "text": "Adding elements" }, { "code": null, "e": 32541, "s": 32523, "text": "Updating elements" }, { "code": null, "e": 32559, "s": 32541, "text": "Removing elements" }, { "code": null, "e": 32583, "s": 32559, "text": "Iterating over elements" }, { "code": null, "e": 32681, "s": 32583, "text": "Let us see how to perform some basic operations on LinkedList to understand it better as follows:" }, { "code": null, "e": 32710, "s": 32681, "text": "Operation 1: Adding Elements" }, { "code": null, "e": 32883, "s": 32710, "text": "In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are: " }, { "code": null, "e": 32964, "s": 32883, "text": "add(Object): This method is used to add an element at the end of the LinkedList." }, { "code": null, "e": 33065, "s": 32964, "text": "add(int index, Object): This method is used to add an element at a specific index in the LinkedList." }, { "code": null, "e": 33074, "s": 33065, "text": "Example:" }, { "code": null, "e": 33079, "s": 33074, "text": "Java" }, { "code": "// Java program to add elements// to a LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add(\"Geeks\"); ll.add(\"Geeks\"); ll.add(1, \"For\"); System.out.println(ll); }}", "e": 33389, "s": 33079, "text": null }, { "code": null, "e": 33409, "s": 33389, "text": "[Geeks, For, Geeks]" }, { "code": null, "e": 33442, "s": 33411, "text": "Operation 2: Changing Elements" }, { "code": null, "e": 33756, "s": 33442, "text": "After adding the elements, if we wish to change the element, it can be done using the set() method. Since a LinkedList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index." }, { "code": null, "e": 33765, "s": 33756, "text": "Example:" }, { "code": null, "e": 33770, "s": 33765, "text": "Java" }, { "code": "// Java program to change elements// in a LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add(\"Geeks\"); ll.add(\"Geeks\"); ll.add(1, \"Geeks\"); System.out.println(\"Initial LinkedList \" + ll); ll.set(1, \"For\"); System.out.println(\"Updated LinkedList \" + ll); }}", "e": 34195, "s": 33770, "text": null }, { "code": null, "e": 34275, "s": 34195, "text": "Initial LinkedList [Geeks, Geeks, Geeks]\nUpdated LinkedList [Geeks, For, Geeks]" }, { "code": null, "e": 34308, "s": 34277, "text": "Operation 3: Removing Elements" }, { "code": null, "e": 34488, "s": 34308, "text": "In order to remove an element from a LinkedList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are: " }, { "code": null, "e": 34660, "s": 34488, "text": "remove(Object): This method is used to simply remove an object from the LinkedList. If there are multiple such objects, then the first occurrence of the object is removed." }, { "code": null, "e": 34988, "s": 34660, "text": "remove(int index): Since a LinkedList is indexed, this method takes an integer value which simply removes the element present at that specific index in the LinkedList. After removing the element and the indices of elements are updated so do the object of LinkedList is updated giving a new List after the deletion of element/s." }, { "code": null, "e": 34997, "s": 34988, "text": "Example:" }, { "code": null, "e": 35002, "s": 34997, "text": "Java" }, { "code": "// Java program to remove elements// in a LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add(\"Geeks\"); ll.add(\"Geeks\"); ll.add(1, \"For\"); System.out.println( \"Initial LinkedList \" + ll); ll.remove(1); System.out.println( \"After the Index Removal \" + ll); ll.remove(\"Geeks\"); System.out.println( \"After the Object Removal \" + ll); }}", "e": 35556, "s": 35002, "text": null }, { "code": null, "e": 35667, "s": 35556, "text": "Initial LinkedList [Geeks, For, Geeks]\nAfter the Index Removal [Geeks, Geeks]\nAfter the Object Removal [Geeks]" }, { "code": null, "e": 35707, "s": 35669, "text": "Operation 4: Iterating the LinkedList" }, { "code": null, "e": 35916, "s": 35707, "text": "There are multiple ways to iterate through LinkedList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for-loop." }, { "code": null, "e": 35925, "s": 35916, "text": "Example:" }, { "code": null, "e": 35930, "s": 35925, "text": "Java" }, { "code": "// Java program to iterate the elements// in an LinkedList import java.util.*; public class GFG { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<>(); ll.add(\"Geeks\"); ll.add(\"Geeks\"); ll.add(1, \"For\"); // Using the Get method and the // for loop for (int i = 0; i < ll.size(); i++) { System.out.print(ll.get(i) + \" \"); } System.out.println(); // Using the for each loop for (String str : ll) System.out.print(str + \" \"); }}", "e": 36528, "s": 35930, "text": null }, { "code": null, "e": 36561, "s": 36528, "text": "Geeks For Geeks \nGeeks For Geeks" }, { "code": null, "e": 36577, "s": 36563, "text": "Chinmoy Lenka" }, { "code": null, "e": 36588, "s": 36577, "text": "Amrutesh99" }, { "code": null, "e": 36600, "s": 36588, "text": "KaashyapMSK" }, { "code": null, "e": 36609, "s": 36600, "text": "19ucs197" }, { "code": null, "e": 36623, "s": 36609, "text": "solankimayank" }, { "code": null, "e": 36640, "s": 36623, "text": "surinderdawra388" }, { "code": null, "e": 36660, "s": 36640, "text": "Java - util package" }, { "code": null, "e": 36677, "s": 36660, "text": "Java-Collections" }, { "code": null, "e": 36693, "s": 36677, "text": "java-LinkedList" }, { "code": null, "e": 36703, "s": 36693, "text": "java-list" }, { "code": null, "e": 36708, "s": 36703, "text": "Java" }, { "code": null, "e": 36720, "s": 36708, "text": "Linked List" }, { "code": null, "e": 36732, "s": 36720, "text": "Linked List" }, { "code": null, "e": 36737, "s": 36732, "text": "Java" }, { "code": null, "e": 36754, "s": 36737, "text": "Java-Collections" }, { "code": null, "e": 36852, "s": 36754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36861, "s": 36852, "text": "Comments" }, { "code": null, "e": 36874, "s": 36861, "text": "Old Comments" }, { "code": null, "e": 36918, "s": 36874, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36943, "s": 36918, "text": "Reverse a string in Java" }, { "code": null, "e": 36979, "s": 36943, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 37010, "s": 36979, "text": "How to iterate any Map in Java" }, { "code": null, "e": 37042, "s": 37010, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 37077, "s": 37042, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 37116, "s": 37077, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 37138, "s": 37116, "text": "Reverse a linked list" }, { "code": null, "e": 37186, "s": 37138, "text": "Stack Data Structure (Introduction and Program)" } ]
C++ List Library - list() Function
The C++ fill constructor std::list::list() constructs a new list with n elements and assign zero value to each element of list. Following is the declaration for std::list::list() constructor form std::list header. explicit list (size_type n); n − Number of elements to be inserted into container. This member function never throws exception. Linear i.e. O(n) The following example shows the usage of std::list::list() constructor. #include <iostream> #include <list> using namespace std; int main(void) { list<int> l(5); cout << "List contains following element" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − List contains following element 0 0 0 0 0 Print Add Notes Bookmark this page
[ { "code": null, "e": 2731, "s": 2603, "text": "The C++ fill constructor std::list::list() constructs a new list with n elements and assign zero value to each element of list." }, { "code": null, "e": 2817, "s": 2731, "text": "Following is the declaration for std::list::list() constructor form std::list header." }, { "code": null, "e": 2847, "s": 2817, "text": "explicit list (size_type n);\n" }, { "code": null, "e": 2901, "s": 2847, "text": "n − Number of elements to be inserted into container." }, { "code": null, "e": 2946, "s": 2901, "text": "This member function never throws exception." }, { "code": null, "e": 2963, "s": 2946, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3035, "s": 2963, "text": "The following example shows the usage of std::list::list() constructor." }, { "code": null, "e": 3279, "s": 3035, "text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nint main(void) {\n list<int> l(5);\n\n cout << \"List contains following element\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3362, "s": 3279, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3405, "s": 3362, "text": "List contains following element\n0\n0\n0\n0\n0\n" }, { "code": null, "e": 3412, "s": 3405, "text": " Print" }, { "code": null, "e": 3423, "s": 3412, "text": " Add Notes" } ]
How to change the DPI of a Pandas Dataframe Plot in Matplotlib?
To change the DPI of a Pandas DataFrame plot, we can use rcParams to set the dot per inch. Set the figure size and adjust the padding between and around the subplots. Set the DPI values in .rcParams["figure.dpi"] = 120 Create a Pandas dataframe to make a plot. Plot the dataframe. To display the figure, use show() method. import pandas as pd from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True plt.rcParams["figure.dpi"] = 120 data = pd.DataFrame({"column1": [4, 6, 7, 1, 8]}) data.plot() plt.show()
[ { "code": null, "e": 1153, "s": 1062, "text": "To change the DPI of a Pandas DataFrame plot, we can use rcParams to set the dot per inch." }, { "code": null, "e": 1229, "s": 1153, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1281, "s": 1229, "text": "Set the DPI values in .rcParams[\"figure.dpi\"] = 120" }, { "code": null, "e": 1323, "s": 1281, "text": "Create a Pandas dataframe to make a plot." }, { "code": null, "e": 1343, "s": 1323, "text": "Plot the dataframe." }, { "code": null, "e": 1385, "s": 1343, "text": "To display the figure, use show() method." }, { "code": null, "e": 1639, "s": 1385, "text": "import pandas as pd\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nplt.rcParams[\"figure.dpi\"] = 120\n\ndata = pd.DataFrame({\"column1\": [4, 6, 7, 1, 8]})\ndata.plot()\n\nplt.show()" } ]
Logstash - Internal Architecture
In this chapter, we will discuss regarding the internal architecture and the different components of Logstash. Logstash processes logs from different servers and data sources and it behaves as the shipper. The shippers are used to collect the logs and these are installed in every input source. Brokers like Redis, Kafka or RabbitMQ are buffers to hold the data for indexers, there may be more than one brokers as failed over instances. Indexers like Lucene are used to index the logs for better search performance and then the output is stored in Elasticsearch or other output destination. The data in output storage is available for Kibana and other visualization software. The Logstash pipeline consists of three components Input, Filters and Output. The input part is responsible to specify and access the input data source such as the log folder of the Apache Tomcat Server. The Logstash configuration file contains the details about the three components of Logstash. In this case, we are creating a file name called Logstash.conf. The following configuration captures data from an input log “inlog.log” and writes it to an output log “outlog.log” without any filters. The Logstash configuration file just copies the data from the inlog.log file using the input plugin and flushes the log data to outlog.log file using the output plugin. input { file { path => "C:/tpwork/logstash/bin/log/inlog.log" } } output { file { path => "C:/tpwork/logstash/bin/log/outlog.log" } } Logstash uses –f option to specify the config file. C:\logstash\bin> logstash –f logstash.conf The following code block shows the input log data. Hello tutorialspoint.com The Logstash output contains the input data in message field. Logstash also adds other fields to the output like Timestamp, Path of the Input Source, Version, Host and Tags. { "path":"C:/tpwork/logstash/bin/log/inlog1.log", "@timestamp":"2016-12-13T02:28:38.763Z", "@version":"1", "host":"Dell-PC", "message":" Hello tutorialspoint.com", "tags":[] } As you can, the output of Logstash contains more than the data supplied through the input log. The output contains the Source Path, Timestamp, Version, Hostname and Tag, which are used to represent the extra messages like errors. We can use filters to process the data and make its useful for our needs. In the next example, we are using filter to get the data, which restricts the output to only data with a verb like GET or POST followed by a Unique Resource Identifier. In this Logstash configuration, we add a filter named grok to filter out the input data. The input log event, which matches the pattern sequence input log, only get to the output destination with error. Logstash adds a tag named "_grokparsefailure" in the output events, which does not match the grok filter pattern sequence. Logstash offers many inbuilt regex patterns for parsing popular server logs like Apache. The pattern used here expects a verb like get, post, etc., followed by a uniform resource identifier. input { file { path => "C:/tpwork/logstash/bin/log/inlog2.log" } } filter { grok { match => {"message" => "%{WORD:verb} %{URIPATHPARAM:uri}"} } } output { file { path => "C:/tpwork/logstash/bin/log/outlog2.log" } } We can run Logstash by using the following command. C:\logstash\bin> logstash –f Logstash.conf Our input file contains two events separated by default delimiter, i.e., new line delimiter. The first event matches the pattern specified in GROk and the second one does not. GET /tutorialspoint/Logstash Input 1234 We can see that the second output event contains "_grokparsefailure" tag, because it does not match the grok filter pattern. The user can also remove these unmatched events in output by using the ‘if’ condition in the output plugin. { "path":"C:/tpwork/logstash/bin/log/inlog2.log", "@timestamp":"2016-12-13T02:47:10.352Z","@version":"1","host":"Dell-PC","verb":"GET", "message":"GET /tutorialspoint/logstash", "uri":"/tutorialspoint/logstash", "tags":[] } { "path":"C:/tpwork/logstash/bin/log/inlog2.log", "@timestamp":"2016-12-13T02:48:12.418Z", "@version":"1", "host":"Dell-PC", "message":"t 1234\r", "tags":["_grokparsefailure"] } Print Add Notes Bookmark this page
[ { "code": null, "e": 2166, "s": 2055, "text": "In this chapter, we will discuss regarding the internal architecture and the different components of Logstash." }, { "code": null, "e": 2492, "s": 2166, "text": "Logstash processes logs from different servers and data sources and it behaves as the shipper. The shippers are used to collect the logs and these are installed in every input source. Brokers like Redis, Kafka or RabbitMQ are buffers to hold the data for indexers, there may be more than one brokers as failed over instances." }, { "code": null, "e": 2731, "s": 2492, "text": "Indexers like Lucene are used to index the logs for better search performance and then the output is stored in Elasticsearch or other output destination. The data in output storage is available for Kibana and other visualization software." }, { "code": null, "e": 2935, "s": 2731, "text": "The Logstash pipeline consists of three components Input, Filters and Output. The input part is responsible to specify and access the input data source such as the log folder of the Apache Tomcat Server." }, { "code": null, "e": 3092, "s": 2935, "text": "The Logstash configuration file contains the details about the three components of Logstash. In this case, we are creating a file name called Logstash.conf." }, { "code": null, "e": 3229, "s": 3092, "text": "The following configuration captures data from an input log “inlog.log” and writes it to an output log “outlog.log” without any filters." }, { "code": null, "e": 3398, "s": 3229, "text": "The Logstash configuration file just copies the data from the inlog.log file using the input plugin and flushes the log data to outlog.log file using the output plugin." }, { "code": null, "e": 3556, "s": 3398, "text": "input {\n file {\n path => \"C:/tpwork/logstash/bin/log/inlog.log\"\n }\n}\noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/outlog.log\"\n }\n}" }, { "code": null, "e": 3608, "s": 3556, "text": "Logstash uses –f option to specify the config file." }, { "code": null, "e": 3652, "s": 3608, "text": "C:\\logstash\\bin> logstash –f logstash.conf\n" }, { "code": null, "e": 3703, "s": 3652, "text": "The following code block shows the input log data." }, { "code": null, "e": 3729, "s": 3703, "text": "Hello tutorialspoint.com\n" }, { "code": null, "e": 3903, "s": 3729, "text": "The Logstash output contains the input data in message field. Logstash also adds other fields to the output like Timestamp, Path of the Input Source, Version, Host and Tags." }, { "code": null, "e": 4091, "s": 3903, "text": "{\n \"path\":\"C:/tpwork/logstash/bin/log/inlog1.log\",\n \"@timestamp\":\"2016-12-13T02:28:38.763Z\",\n \"@version\":\"1\", \"host\":\"Dell-PC\",\n \"message\":\" Hello tutorialspoint.com\", \"tags\":[]\n}" }, { "code": null, "e": 4321, "s": 4091, "text": "As you can, the output of Logstash contains more than the data supplied through the input log. The output contains the Source Path, Timestamp, Version, Hostname and Tag, which are used to represent the extra messages like errors." }, { "code": null, "e": 4564, "s": 4321, "text": "We can use filters to process the data and make its useful for our needs. In the next example, we are using filter to get the data, which restricts the output to only data with a verb like GET or POST followed by a Unique Resource Identifier." }, { "code": null, "e": 4890, "s": 4564, "text": "In this Logstash configuration, we add a filter named grok to filter out the input data. The input log event, which matches the pattern sequence input log, only get to the output destination with error. Logstash adds a tag named \"_grokparsefailure\" in the output events, which does not match the grok filter pattern sequence." }, { "code": null, "e": 5081, "s": 4890, "text": "Logstash offers many inbuilt regex patterns for parsing popular server logs like Apache. The pattern used here expects a verb like get, post, etc., followed by a uniform resource identifier." }, { "code": null, "e": 5332, "s": 5081, "text": "input {\n file {\n path => \"C:/tpwork/logstash/bin/log/inlog2.log\"\n }\n}\nfilter {\n grok {\n match => {\"message\" => \"%{WORD:verb} %{URIPATHPARAM:uri}\"}\n }\n}\noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/outlog2.log\"\n }\n}" }, { "code": null, "e": 5384, "s": 5332, "text": "We can run Logstash by using the following command." }, { "code": null, "e": 5429, "s": 5384, "text": "C:\\logstash\\bin> logstash –f Logstash.conf\n" }, { "code": null, "e": 5605, "s": 5429, "text": "Our input file contains two events separated by default delimiter, i.e., new line delimiter. The first event matches the pattern specified in GROk and the second one does not." }, { "code": null, "e": 5646, "s": 5605, "text": "GET /tutorialspoint/Logstash\nInput 1234\n" }, { "code": null, "e": 5879, "s": 5646, "text": "We can see that the second output event contains \"_grokparsefailure\" tag, because it does not match the grok filter pattern. The user can also remove these unmatched events in output by using the ‘if’ condition in the output plugin." }, { "code": null, "e": 6299, "s": 5879, "text": "{\n \"path\":\"C:/tpwork/logstash/bin/log/inlog2.log\",\n \"@timestamp\":\"2016-12-13T02:47:10.352Z\",\"@version\":\"1\",\"host\":\"Dell-PC\",\"verb\":\"GET\",\n \"message\":\"GET /tutorialspoint/logstash\", \"uri\":\"/tutorialspoint/logstash\", \"tags\":[]\n}\n{\n \"path\":\"C:/tpwork/logstash/bin/log/inlog2.log\",\n \"@timestamp\":\"2016-12-13T02:48:12.418Z\", \"@version\":\"1\", \"host\":\"Dell-PC\",\n \"message\":\"t 1234\\r\", \"tags\":[\"_grokparsefailure\"]\n}" }, { "code": null, "e": 6306, "s": 6299, "text": " Print" }, { "code": null, "e": 6317, "s": 6306, "text": " Add Notes" } ]
How to convert time seconds to h:m:s format in Python?
If you have a function that returns information in seconds, but you need that information in hours:minutes:seconds format, you can use the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations: seconds = 56741 m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) This will give the output − 15:45:41 You can also use the timedelta function to get the same functionality but at a cost to performance. import datetime timedelta_obj = datetime.timedelta(seconds=56741) print(timedelta_obj) This will give the output − 15:45:41
[ { "code": null, "e": 1378, "s": 1062, "text": "If you have a function that returns information in seconds, but you need that information in hours:minutes:seconds format, you can use the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:" }, { "code": null, "e": 1475, "s": 1378, "text": "seconds = 56741\nm, s = divmod(seconds, 60)\nh, m = divmod(m, 60)\nprint \"%d:%02d:%02d\" % (h, m, s)" }, { "code": null, "e": 1503, "s": 1475, "text": "This will give the output −" }, { "code": null, "e": 1512, "s": 1503, "text": "15:45:41" }, { "code": null, "e": 1613, "s": 1512, "text": "You can also use the timedelta function to get the same functionality but at a cost to performance. " }, { "code": null, "e": 1700, "s": 1613, "text": "import datetime\ntimedelta_obj = datetime.timedelta(seconds=56741)\nprint(timedelta_obj)" }, { "code": null, "e": 1728, "s": 1700, "text": "This will give the output −" }, { "code": null, "e": 1737, "s": 1728, "text": "15:45:41" } ]