title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Finding the path from one vertex to rest using BFS - GeeksforGeeks
|
06 Aug, 2021
Given an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS.Examples:
Input:
Output:
0 <- 2
1 <- 0 <- 2
2
3 <- 1 <- 0 <- 2
4 <- 5 <- 2
5 <- 2
6 <- 2
Approach: In the images shown below:
que[] array stores the vertices reached and we will enqueue a vertex only if it has not been visited and dequeue it once all its child node have been considered.
In order to distinguish whether the node has been visited or not we will put 1 in visited[] array at the respective index to signify it has been visited and if at given index 0 is present it will signify that it has not been visited.
Parent array is to store the parent node of each vertex. For ex. In case of 0 connected to 2, 2 will be the parent node of 0 and we will put 2 at the index 0 in the parent array.
Below is the implementation of the above approach:
C++14
Java
Python3
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the path from// source (s) to destination (d)void print(vector<int> parent, int s, int d){ // The while loop will stop only when the // destination and the source node become equal while (s != d) { // Print the destination and store the parent // of the node in the destination since parent // stores the node through which // the current node has been reached cout << d << " <- "; d = parent[d]; } cout << d << endl;} // Finding Path using BFS ALgorithmvoid bfs(vector<vector<int> > adjList, int source, int n){ vector<int> parent(n, 0); vector<int> que(n, 0); int front = -1, rear = -1; vector<int> visited(n, 0); //Arrays.fill(visited, 0); visited = 1; parent = source; // To add any non visited node we will increment the rear // and add that vertex to the end of the array (enqueuing) que[++rear] = source; int k; // The loop will continue till the rear and front are equal while (front != rear) { // Here Dequeuing is nothing but to increment the front int k = que[++front]; //L<Integer> list = adjList.get(k); for (int j:adjList[k]) { if (visited[j] == 0) { que[++rear] = j; visited[j] = 1; parent[j] = k; } } } // Print the path from source to every other node for (k = 0; k < n; k++) print(parent, source, k);} // Driver codeint main(){ // Adjacency list representation of the graph vector<vector<int> > adjList; // Vertices 1 and 2 have an incoming edge // from vertex 0 adjList.push_back({1, 2}); // Vertex 3 has an incoming edge // from vertex 1 adjList.push_back({3}); // Vertices 0, 5 and 6 have an incoming // edge from vertex 2 adjList.push_back({0, 5, 6}); // Vertices 1 and 4 have an incoming edge // from vertex 3 adjList.push_back({1, 4}); // Vertices 2 and 3 have an incoming edge // from vertex 4 adjList.push_back({2, 3}); // Vertices 4 and 6 have an incoming edge // from vertex 5 adjList.push_back({4, 6}); // Vertex 5 has an incoming edge // from vertex 6 adjList.push_back({5}); int n = adjList.size(); int source = 2; bfs(adjList, source, n);} // This code is contributed by mohit kumar 29.
// Java implementation of the approachimport java.util.ArrayList;import java.util.Arrays;import java.util.List; class GFG{ // Function to print the path from // source (s) to destination (d) static void print(int parent[], int s, int d) { // The while loop will stop only when the // destination and the source node become equal while (s != d) { // Print the destination and store the parent // of the node in the destination since parent // stores the node through which // the current node has been reached System.out.print(d + " <- "); d = parent[d]; } System.out.println(d); } // Finding Path using BFS ALgorithm static void bfs(List<List<Integer> > adjList, int source, int n) { int parent[] = new int[n]; int que[] = new int[n]; Arrays.fill(parent, 0); Arrays.fill(que, 0); int front = -1, rear = -1; int visited[] = new int[n]; Arrays.fill(visited, 0); visited = 1; parent = source; // To add any non visited node we will increment the rear // and add that vertex to the end of the array (enqueuing) que[++rear] = source; int k; // The loop will continue till the rear and front are equal while (front != rear) { // Here Dequeuing is nothing but to increment the front int k = que[++front]; List<Integer> list = adjList.get(k); for (int i = 0; i < list.size(); i++) { int j = list.get(i); if (visited[j] == 0) { que[++rear] = j; visited[j] = 1; parent[j] = k; } } } // Print the path from source to every other node for (k = 0; k < n; k++) print(parent, source, k); } // Driver code public static void main(String args[]) { // Adjacency list representation of the graph List<List<Integer> > adjList = new ArrayList<>(); // Vertices 1 and 2 have an incoming edge // from vertex 0 List<Integer> tmp = new ArrayList<Integer>(Arrays.asList(1, 2)); adjList.add(tmp); // Vertex 3 has an incoming edge from vertex 1 tmp = new ArrayList<Integer>(Arrays.asList(3)); adjList.add(tmp); // Vertices 0, 5 and 6 have an incoming // edge from vertex 2 tmp = new ArrayList<Integer>(Arrays.asList(0, 5, 6)); adjList.add(tmp); // Vertices 1 and 4 have an incoming edge // from vertex 3 tmp = new ArrayList<Integer>(Arrays.asList(1, 4)); adjList.add(tmp); // Vertices 2 and 3 have an incoming edge // from vertex 4 tmp = new ArrayList<Integer>(Arrays.asList(2, 3)); adjList.add(tmp); // Vertices 4 and 6 have an incoming edge // from vertex 5 tmp = new ArrayList<Integer>(Arrays.asList(4, 6)); adjList.add(tmp); // Vertex 5 has an incoming edge from vertex 6 tmp = new ArrayList<Integer>(Arrays.asList(5)); adjList.add(tmp); int n = adjList.size(); int source = 2; bfs(adjList, source, n); }}
# Python3 implementation of the approach # Function to print the path from# src (s) to destination (d)def printfunc(parent, s, d): # The while loop will stop only when # the destination and the src node # become equal while s != d: # Print the destination and store # the parent of the node in the # destination since parent stores # the node through which the current # node has been reached print(str(d) + " <-", end = " ") d = parent[d] print(d) # Finding Path using BFS ALgorithmdef bfs(adjList, src, n): parent = [0] * (n) que = [0] * (n) front, rear = -1, -1 visited = [0] * (n) visited[src] = 1 parent[src] = src # To add any non visited node we will # increment the rear and add that vertex # to the end of the array (enqueuing) rear += 1 que[rear] = src # The loop will continue till the rear # and front are equal while front != rear: # Here Dequeuing is nothing but to # increment the front int front += 1 k = que[front] List = adjList[k] for i in range(0, len(List)): j = List[i] if visited[j] == 0: rear += 1 que[rear] = j visited[j] = 1 parent[j] = k # Print the path from src to every # other node for k in range(0, n): printfunc(parent, src, k) # Driver codeif __name__ == "__main__": # Adjacency list representation # of the graph adjList = [] # Vertices 1 and 2 have an incoming edge # from vertex 0 adjList.append([1, 2]) # Vertex 3 has an incoming edge # from vertex 1 adjList.append([3]) # Vertices 0, 5 and 6 have an incoming # edge from vertex 2 adjList.append([0, 5, 6]) # Vertices 1 and 4 have an incoming edge # from vertex 3 adjList.append([1, 4]) # Vertices 2 and 3 have an incoming edge # from vertex 4 adjList.append([2, 3]) # Vertices 4 and 6 have an incoming edge # from vertex 5 adjList.append([4, 6]) # Vertex 5 has an incoming edge # from vertex 6 adjList.append([5]) n = len(adjList) src = 2 bfs(adjList, src, n) # This code is contributed by Rituraj Jain
<script> // JavaScript implementation of the approach // Function to print the path from // source (s) to destination (d) function print(parent,s,d) { // The while loop will stop only when the // destination and the source node become equal while (s != d) { // Print the destination and store the parent // of the node in the destination since parent // stores the node through which // the current node has been reached document.write(d + " <- "); d = parent[d]; } document.write(d+"<br>"); } // Finding Path using BFS ALgorithm function bfs( adjList,source,n) { let parent = new Array(n); let que = new Array(n); for(let i=0;i<n;i++) { parent[i]=0; que[i]=0; } let front = -1, rear = -1; let visited = new Array(n); for(let i=0;i<n;i++) { visited[i]=0; } visited = 1; parent = source; // To add any non visited node we will increment the rear // and add that vertex to the end of the array (enqueuing) que[++rear] = source; let k; // The loop will continue till the rear // and front are equal while (front != rear) { // Here Dequeuing is nothing but // to increment the front int k = que[++front]; let list = adjList[k]; for (let i = 0; i < list.length; i++) { let j = list[i]; if (visited[j] == 0) { que[++rear] = j; visited[j] = 1; parent[j] = k; } } } // Print the path from source to every other node for (k = 0; k < n; k++) print(parent, source, k); } // Driver code // Adjacency list representation of the graph let adjList = []; // Vertices 1 and 2 have an incoming edge // from vertex 0 adjList.push([1, 2]) // Vertex 3 has an incoming edge from vertex 1 adjList.push([3]) // Vertices 0, 5 and 6 have an incoming // edge from vertex 2 adjList.push([0, 5, 6]) // Vertices 1 and 4 have an incoming edge // from vertex 3 adjList.push([1, 4]) // Vertices 2 and 3 have an incoming edge // from vertex 4 adjList.push([2, 3]) // Vertices 4 and 6 have an incoming edge // from vertex 5 adjList.push([4, 6]) // Vertex 5 has an incoming edge from vertex 6 adjList.push([5]) let n = adjList.length; let source = 2; bfs(adjList, source, n); // This code is contributed by unknown2108 </script>
0 <- 2
1 <- 0 <- 2
2
3 <- 1 <- 0 <- 2
4 <- 5 <- 2
5 <- 2
6 <- 2
Time Complexity: O(V + E) where V and E are the numbers of vertices and edges in the graph respectively.Auxiliary Space: O(V + E).
rituraj_jain
mohit kumar 29
unknown2108
pankajsharmagfg
BFS
Shortest Path
Data Structures
Graph
Java Programs
Data Structures
Graph
Shortest Path
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Insertion in a B+ tree
Hash Functions and list/types of Hash functions
Shortest path in a directed graph by Dijkstra’s algorithm
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
|
[
{
"code": null,
"e": 25052,
"s": 25024,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 25208,
"s": 25052,
"text": "Given an adjacency list representation of a directed graph, the task is to find the path from source to every other node in the graph using BFS.Examples: "
},
{
"code": null,
"e": 25215,
"s": 25208,
"text": "Input:"
},
{
"code": null,
"e": 25287,
"s": 25215,
"text": "Output:\n0 <- 2\n1 <- 0 <- 2\n2\n3 <- 1 <- 0 <- 2\n4 <- 5 <- 2\n5 <- 2\n6 <- 2"
},
{
"code": null,
"e": 25326,
"s": 25287,
"text": "Approach: In the images shown below: "
},
{
"code": null,
"e": 25488,
"s": 25326,
"text": "que[] array stores the vertices reached and we will enqueue a vertex only if it has not been visited and dequeue it once all its child node have been considered."
},
{
"code": null,
"e": 25722,
"s": 25488,
"text": "In order to distinguish whether the node has been visited or not we will put 1 in visited[] array at the respective index to signify it has been visited and if at given index 0 is present it will signify that it has not been visited."
},
{
"code": null,
"e": 25901,
"s": 25722,
"text": "Parent array is to store the parent node of each vertex. For ex. In case of 0 connected to 2, 2 will be the parent node of 0 and we will put 2 at the index 0 in the parent array."
},
{
"code": null,
"e": 25969,
"s": 25917,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25975,
"s": 25969,
"text": "C++14"
},
{
"code": null,
"e": 25980,
"s": 25975,
"text": "Java"
},
{
"code": null,
"e": 25988,
"s": 25980,
"text": "Python3"
},
{
"code": null,
"e": 25999,
"s": 25988,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the path from// source (s) to destination (d)void print(vector<int> parent, int s, int d){ // The while loop will stop only when the // destination and the source node become equal while (s != d) { // Print the destination and store the parent // of the node in the destination since parent // stores the node through which // the current node has been reached cout << d << \" <- \"; d = parent[d]; } cout << d << endl;} // Finding Path using BFS ALgorithmvoid bfs(vector<vector<int> > adjList, int source, int n){ vector<int> parent(n, 0); vector<int> que(n, 0); int front = -1, rear = -1; vector<int> visited(n, 0); //Arrays.fill(visited, 0); visited = 1; parent = source; // To add any non visited node we will increment the rear // and add that vertex to the end of the array (enqueuing) que[++rear] = source; int k; // The loop will continue till the rear and front are equal while (front != rear) { // Here Dequeuing is nothing but to increment the front int k = que[++front]; //L<Integer> list = adjList.get(k); for (int j:adjList[k]) { if (visited[j] == 0) { que[++rear] = j; visited[j] = 1; parent[j] = k; } } } // Print the path from source to every other node for (k = 0; k < n; k++) print(parent, source, k);} // Driver codeint main(){ // Adjacency list representation of the graph vector<vector<int> > adjList; // Vertices 1 and 2 have an incoming edge // from vertex 0 adjList.push_back({1, 2}); // Vertex 3 has an incoming edge // from vertex 1 adjList.push_back({3}); // Vertices 0, 5 and 6 have an incoming // edge from vertex 2 adjList.push_back({0, 5, 6}); // Vertices 1 and 4 have an incoming edge // from vertex 3 adjList.push_back({1, 4}); // Vertices 2 and 3 have an incoming edge // from vertex 4 adjList.push_back({2, 3}); // Vertices 4 and 6 have an incoming edge // from vertex 5 adjList.push_back({4, 6}); // Vertex 5 has an incoming edge // from vertex 6 adjList.push_back({5}); int n = adjList.size(); int source = 2; bfs(adjList, source, n);} // This code is contributed by mohit kumar 29.",
"e": 28440,
"s": 25999,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.ArrayList;import java.util.Arrays;import java.util.List; class GFG{ // Function to print the path from // source (s) to destination (d) static void print(int parent[], int s, int d) { // The while loop will stop only when the // destination and the source node become equal while (s != d) { // Print the destination and store the parent // of the node in the destination since parent // stores the node through which // the current node has been reached System.out.print(d + \" <- \"); d = parent[d]; } System.out.println(d); } // Finding Path using BFS ALgorithm static void bfs(List<List<Integer> > adjList, int source, int n) { int parent[] = new int[n]; int que[] = new int[n]; Arrays.fill(parent, 0); Arrays.fill(que, 0); int front = -1, rear = -1; int visited[] = new int[n]; Arrays.fill(visited, 0); visited = 1; parent = source; // To add any non visited node we will increment the rear // and add that vertex to the end of the array (enqueuing) que[++rear] = source; int k; // The loop will continue till the rear and front are equal while (front != rear) { // Here Dequeuing is nothing but to increment the front int k = que[++front]; List<Integer> list = adjList.get(k); for (int i = 0; i < list.size(); i++) { int j = list.get(i); if (visited[j] == 0) { que[++rear] = j; visited[j] = 1; parent[j] = k; } } } // Print the path from source to every other node for (k = 0; k < n; k++) print(parent, source, k); } // Driver code public static void main(String args[]) { // Adjacency list representation of the graph List<List<Integer> > adjList = new ArrayList<>(); // Vertices 1 and 2 have an incoming edge // from vertex 0 List<Integer> tmp = new ArrayList<Integer>(Arrays.asList(1, 2)); adjList.add(tmp); // Vertex 3 has an incoming edge from vertex 1 tmp = new ArrayList<Integer>(Arrays.asList(3)); adjList.add(tmp); // Vertices 0, 5 and 6 have an incoming // edge from vertex 2 tmp = new ArrayList<Integer>(Arrays.asList(0, 5, 6)); adjList.add(tmp); // Vertices 1 and 4 have an incoming edge // from vertex 3 tmp = new ArrayList<Integer>(Arrays.asList(1, 4)); adjList.add(tmp); // Vertices 2 and 3 have an incoming edge // from vertex 4 tmp = new ArrayList<Integer>(Arrays.asList(2, 3)); adjList.add(tmp); // Vertices 4 and 6 have an incoming edge // from vertex 5 tmp = new ArrayList<Integer>(Arrays.asList(4, 6)); adjList.add(tmp); // Vertex 5 has an incoming edge from vertex 6 tmp = new ArrayList<Integer>(Arrays.asList(5)); adjList.add(tmp); int n = adjList.size(); int source = 2; bfs(adjList, source, n); }}",
"e": 31693,
"s": 28440,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to print the path from# src (s) to destination (d)def printfunc(parent, s, d): # The while loop will stop only when # the destination and the src node # become equal while s != d: # Print the destination and store # the parent of the node in the # destination since parent stores # the node through which the current # node has been reached print(str(d) + \" <-\", end = \" \") d = parent[d] print(d) # Finding Path using BFS ALgorithmdef bfs(adjList, src, n): parent = [0] * (n) que = [0] * (n) front, rear = -1, -1 visited = [0] * (n) visited[src] = 1 parent[src] = src # To add any non visited node we will # increment the rear and add that vertex # to the end of the array (enqueuing) rear += 1 que[rear] = src # The loop will continue till the rear # and front are equal while front != rear: # Here Dequeuing is nothing but to # increment the front int front += 1 k = que[front] List = adjList[k] for i in range(0, len(List)): j = List[i] if visited[j] == 0: rear += 1 que[rear] = j visited[j] = 1 parent[j] = k # Print the path from src to every # other node for k in range(0, n): printfunc(parent, src, k) # Driver codeif __name__ == \"__main__\": # Adjacency list representation # of the graph adjList = [] # Vertices 1 and 2 have an incoming edge # from vertex 0 adjList.append([1, 2]) # Vertex 3 has an incoming edge # from vertex 1 adjList.append([3]) # Vertices 0, 5 and 6 have an incoming # edge from vertex 2 adjList.append([0, 5, 6]) # Vertices 1 and 4 have an incoming edge # from vertex 3 adjList.append([1, 4]) # Vertices 2 and 3 have an incoming edge # from vertex 4 adjList.append([2, 3]) # Vertices 4 and 6 have an incoming edge # from vertex 5 adjList.append([4, 6]) # Vertex 5 has an incoming edge # from vertex 6 adjList.append([5]) n = len(adjList) src = 2 bfs(adjList, src, n) # This code is contributed by Rituraj Jain",
"e": 33988,
"s": 31693,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to print the path from // source (s) to destination (d) function print(parent,s,d) { // The while loop will stop only when the // destination and the source node become equal while (s != d) { // Print the destination and store the parent // of the node in the destination since parent // stores the node through which // the current node has been reached document.write(d + \" <- \"); d = parent[d]; } document.write(d+\"<br>\"); } // Finding Path using BFS ALgorithm function bfs( adjList,source,n) { let parent = new Array(n); let que = new Array(n); for(let i=0;i<n;i++) { parent[i]=0; que[i]=0; } let front = -1, rear = -1; let visited = new Array(n); for(let i=0;i<n;i++) { visited[i]=0; } visited = 1; parent = source; // To add any non visited node we will increment the rear // and add that vertex to the end of the array (enqueuing) que[++rear] = source; let k; // The loop will continue till the rear // and front are equal while (front != rear) { // Here Dequeuing is nothing but // to increment the front int k = que[++front]; let list = adjList[k]; for (let i = 0; i < list.length; i++) { let j = list[i]; if (visited[j] == 0) { que[++rear] = j; visited[j] = 1; parent[j] = k; } } } // Print the path from source to every other node for (k = 0; k < n; k++) print(parent, source, k); } // Driver code // Adjacency list representation of the graph let adjList = []; // Vertices 1 and 2 have an incoming edge // from vertex 0 adjList.push([1, 2]) // Vertex 3 has an incoming edge from vertex 1 adjList.push([3]) // Vertices 0, 5 and 6 have an incoming // edge from vertex 2 adjList.push([0, 5, 6]) // Vertices 1 and 4 have an incoming edge // from vertex 3 adjList.push([1, 4]) // Vertices 2 and 3 have an incoming edge // from vertex 4 adjList.push([2, 3]) // Vertices 4 and 6 have an incoming edge // from vertex 5 adjList.push([4, 6]) // Vertex 5 has an incoming edge from vertex 6 adjList.push([5]) let n = adjList.length; let source = 2; bfs(adjList, source, n); // This code is contributed by unknown2108 </script>",
"e": 36807,
"s": 33988,
"text": null
},
{
"code": null,
"e": 36871,
"s": 36807,
"text": "0 <- 2\n1 <- 0 <- 2\n2\n3 <- 1 <- 0 <- 2\n4 <- 5 <- 2\n5 <- 2\n6 <- 2"
},
{
"code": null,
"e": 37006,
"s": 36873,
"text": "Time Complexity: O(V + E) where V and E are the numbers of vertices and edges in the graph respectively.Auxiliary Space: O(V + E). "
},
{
"code": null,
"e": 37019,
"s": 37006,
"text": "rituraj_jain"
},
{
"code": null,
"e": 37034,
"s": 37019,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37046,
"s": 37034,
"text": "unknown2108"
},
{
"code": null,
"e": 37062,
"s": 37046,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 37066,
"s": 37062,
"text": "BFS"
},
{
"code": null,
"e": 37080,
"s": 37066,
"text": "Shortest Path"
},
{
"code": null,
"e": 37096,
"s": 37080,
"text": "Data Structures"
},
{
"code": null,
"e": 37102,
"s": 37096,
"text": "Graph"
},
{
"code": null,
"e": 37116,
"s": 37102,
"text": "Java Programs"
},
{
"code": null,
"e": 37132,
"s": 37116,
"text": "Data Structures"
},
{
"code": null,
"e": 37138,
"s": 37132,
"text": "Graph"
},
{
"code": null,
"e": 37152,
"s": 37138,
"text": "Shortest Path"
},
{
"code": null,
"e": 37156,
"s": 37152,
"text": "BFS"
},
{
"code": null,
"e": 37254,
"s": 37156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37290,
"s": 37254,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 37349,
"s": 37290,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 37372,
"s": 37349,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 37420,
"s": 37372,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 37478,
"s": 37420,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 37518,
"s": 37478,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 37569,
"s": 37518,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 37607,
"s": 37569,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 37665,
"s": 37607,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Tryit Editor v3.7
|
CSS Grid Intro
Tryit: Grid elements
|
[
{
"code": null,
"e": 24,
"s": 9,
"text": "CSS Grid Intro"
}
] |
How to create dynamic values and objects in JavaScript ?
|
23 Feb, 2021
In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array.
To do, so you can create a variable and assign it a particular value. Then while in the array, when you are declaring the variable use square brackets with the variable name in it, and with this when in the future you decide to change the variable name you need not access the whole array, instead you can just update the value of the variable and the variable in the array automatically changes.
Syntax:
const var_name = 'Name';
const = { [var_name] = 'GeeksForGeeks'};
Example 1:
Javascript
<script> const dynamic1 = "Age"; const dynamic2 = "Marks"; const user = { Name : "GeeksForGeeks", [dynamic1] : "57", [dynamic2] : "42" }; console.log(user);</script>
Output: In this output dynamic1 is assigned the value ‘Age’, hence in the output it is shown by the name of ‘Age’, on the other hand, dynamic2 is assigned with ‘Marks’ and it is shown by the name of ‘Marks’ in the output also.
{
Age: "57",
Marks: "42",
Name: "GeeksForGeeks"
}
Example 2: Let us look at what if we change the two assigned values of dynamic1 and dynamic2 respectively.
Javascript
<script> const dynamic1 = "Marks"; const dynamic2 = "Age"; const user = { Name : "GeeksForGeeks", [dynamic1] : "57", [dynamic2] : "42" }; console.log(user);</script>
Output: Hence from the above code, it is clear that changing the names of the variables above the change is visible in the array attributes as well. Hence using this method we can make sure that we need not go through the array every time we wish to update any variable name or its value.
{
Age: "42",
Marks: "57",
Name: "GeeksForGeeks"
}
javascript-object
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 188,
"s": 28,
"text": "In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array."
},
{
"code": null,
"e": 585,
"s": 188,
"text": "To do, so you can create a variable and assign it a particular value. Then while in the array, when you are declaring the variable use square brackets with the variable name in it, and with this when in the future you decide to change the variable name you need not access the whole array, instead you can just update the value of the variable and the variable in the array automatically changes."
},
{
"code": null,
"e": 593,
"s": 585,
"text": "Syntax:"
},
{
"code": null,
"e": 659,
"s": 593,
"text": "const var_name = 'Name';\nconst = { [var_name] = 'GeeksForGeeks'};"
},
{
"code": null,
"e": 670,
"s": 659,
"text": "Example 1:"
},
{
"code": null,
"e": 681,
"s": 670,
"text": "Javascript"
},
{
"code": "<script> const dynamic1 = \"Age\"; const dynamic2 = \"Marks\"; const user = { Name : \"GeeksForGeeks\", [dynamic1] : \"57\", [dynamic2] : \"42\" }; console.log(user);</script>",
"e": 919,
"s": 681,
"text": null
},
{
"code": null,
"e": 1146,
"s": 919,
"text": "Output: In this output dynamic1 is assigned the value ‘Age’, hence in the output it is shown by the name of ‘Age’, on the other hand, dynamic2 is assigned with ‘Marks’ and it is shown by the name of ‘Marks’ in the output also."
},
{
"code": null,
"e": 1202,
"s": 1146,
"text": "{\n Age: \"57\",\n Marks: \"42\",\n Name: \"GeeksForGeeks\"\n}"
},
{
"code": null,
"e": 1309,
"s": 1202,
"text": "Example 2: Let us look at what if we change the two assigned values of dynamic1 and dynamic2 respectively."
},
{
"code": null,
"e": 1320,
"s": 1309,
"text": "Javascript"
},
{
"code": "<script> const dynamic1 = \"Marks\"; const dynamic2 = \"Age\"; const user = { Name : \"GeeksForGeeks\", [dynamic1] : \"57\", [dynamic2] : \"42\" }; console.log(user);</script>",
"e": 1558,
"s": 1320,
"text": null
},
{
"code": null,
"e": 1847,
"s": 1558,
"text": "Output: Hence from the above code, it is clear that changing the names of the variables above the change is visible in the array attributes as well. Hence using this method we can make sure that we need not go through the array every time we wish to update any variable name or its value."
},
{
"code": null,
"e": 1903,
"s": 1847,
"text": "{\n Age: \"42\",\n Marks: \"57\",\n Name: \"GeeksForGeeks\"\n}"
},
{
"code": null,
"e": 1921,
"s": 1903,
"text": "javascript-object"
},
{
"code": null,
"e": 1932,
"s": 1921,
"text": "JavaScript"
}
] |
Part of Speech Tagging with Stop words using NLTK in python
|
11 Apr, 2022
The Natural Language Toolkit (NLTK) is a platform used for building programs for text analysis. One of the more powerful aspects of the NLTK module is the Part of Speech tagging.In order to run the below python program you must have to install NLTK. Please follow the installation steps.
Open your terminal, run pip install nltk.
Write python in the command prompt so python Interactive Shell is ready to execute your code/Script.
Type import nltk
nltk.download()
A GUI will pop up then choose to download “all” for all packages, and then click ‘download’. This will give you all of the tokenizers, chunkers, other algorithms, and all of the corpora, so that’s why installation will take quite time. Examples:
import nltk
nltk.download()
let’s knock out some quick vocabulary: Corpus : Body of text, singular. Corpora is the plural of this. Lexicon : Words and their meanings. Token : Each “entity” that is a part of whatever was split up based on rules.In corpus linguistics, part-of-speech tagging (POS tagging or PoS tagging or POST), also called grammatical tagging or word-category disambiguation.
Input: Everything is all about money.
Output: [('Everything', 'NN'), ('is', 'VBZ'),
('all', 'DT'),('about', 'IN'),
('money', 'NN'), ('.', '.')]
Here’s a list of the tags, what they mean, and some examples:
CC coordinating conjunction CD cardinal digit DT determiner EX existential there (like: “there is” ... think of it like “there exists”) FW foreign word IN preposition/subordinating conjunction JJ adjective – ‘big’ JJR adjective, comparative – ‘bigger’ JJS adjective, superlative – ‘biggest’ LS list marker 1) MD modal – could, will NN noun, singular ‘- desk’ NNS noun plural – ‘desks’ NNP proper noun, singular – ‘Harrison’ NNPS proper noun, plural – ‘Americans’ PDT predeterminer – ‘all the kids’ POS possessive ending parent’s PRP personal pronoun – I, he, she PRP$ possessive pronoun – my, his, hers RB adverb – very, silently, RBR adverb, comparative – better RBS adverb, superlative – best RP particle – give up TO – to go ‘to’ the store. UH interjection – errrrrrrrm VB verb, base form – take VBD verb, past tense – took VBG verb, gerund/present participle – taking VBN verb, past participle – taken VBP verb, sing. present, non-3d – take VBZ verb, 3rd person sing. present – takes WDT wh-determiner – which WP wh-pronoun – who, what WP$ possessive wh-pronoun, eg- whose WRB wh-adverb, eg- where, when
Text may contain stop words like ‘the’, ‘is’, ‘are’. Stop words can be filtered from the text to be processed. There is no universal list of stop words in nlp research, however the nltk module contains a list of stop words. You can add your own Stop word. Go to your NLTK download directory path -> corpora -> stopwords -> update the stop word file depends on your language which one you are using. Here we are using english (stopwords.words(‘english’)).
Python
import nltkfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize, sent_tokenizestop_words = set(stopwords.words('english')) // Dummy texttxt = "Sukanya, Rajib and Naba are my good friends. " \ "Sukanya is getting married next year. " \ "Marriage is a big step in one’s life." \ "It is both exciting and frightening. " \ "But friendship is a sacred bond between people." \ "It is a special kind of love between us. " \ "Many of you must have tried searching for a friend "\ "but never found the right one." # sent_tokenize is one of instances of# PunktSentenceTokenizer from the nltk.tokenize.punkt module tokenized = sent_tokenize(txt)for i in tokenized: # Word tokenizers is used to find the words # and punctuation in a string wordsList = nltk.word_tokenize(i) # removing stop words from wordList wordsList = [w for w in wordsList if not w in stop_words] # Using a Tagger. Which is part-of-speech # tagger or POS-tagger. tagged = nltk.pos_tag(wordsList) print(tagged)
Output:
[('Sukanya', 'NNP'), ('Rajib', 'NNP'), ('Naba', 'NNP'), ('good', 'JJ'), ('friends', 'NNS')]
[('Sukanya', 'NNP'), ('getting', 'VBG'), ('married', 'VBN'), ('next', 'JJ'), ('year', 'NN')]
[('Marriage', 'NN'), ('big', 'JJ'), ('step', 'NN'), ('one', 'CD'), ('’', 'NN'), ('life', 'NN')]
[('It', 'PRP'), ('exciting', 'VBG'), ('frightening', 'VBG')]
[('But', 'CC'), ('friendship', 'NN'), ('sacred', 'VBD'), ('bond', 'NN'), ('people', 'NNS')]
[('It', 'PRP'), ('special', 'JJ'), ('kind', 'NN'), ('love', 'VB'), ('us', 'PRP')]
[('Many', 'JJ'), ('must', 'MD'), ('tried', 'VB'), ('searching', 'VBG'), ('friend', 'NN'),
('never', 'RB'), ('found', 'VBD'), ('right', 'RB'), ('one', 'CD')]
Basically, the goal of a POS tagger is to assign linguistic (mostly grammatical) information to sub-sentential units. Such units are called tokens and, most of the time, correspond to words and symbols (e.g. punctuation).
jaikrishna1
rkbhola5
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": "\n11 Apr, 2022"
},
{
"code": null,
"e": 342,
"s": 52,
"text": "The Natural Language Toolkit (NLTK) is a platform used for building programs for text analysis. One of the more powerful aspects of the NLTK module is the Part of Speech tagging.In order to run the below python program you must have to install NLTK. Please follow the installation steps. "
},
{
"code": null,
"e": 384,
"s": 342,
"text": "Open your terminal, run pip install nltk."
},
{
"code": null,
"e": 485,
"s": 384,
"text": "Write python in the command prompt so python Interactive Shell is ready to execute your code/Script."
},
{
"code": null,
"e": 502,
"s": 485,
"text": "Type import nltk"
},
{
"code": null,
"e": 518,
"s": 502,
"text": "nltk.download()"
},
{
"code": null,
"e": 766,
"s": 518,
"text": "A GUI will pop up then choose to download “all” for all packages, and then click ‘download’. This will give you all of the tokenizers, chunkers, other algorithms, and all of the corpora, so that’s why installation will take quite time. Examples: "
},
{
"code": null,
"e": 794,
"s": 766,
"text": "import nltk\nnltk.download()"
},
{
"code": null,
"e": 1160,
"s": 794,
"text": "let’s knock out some quick vocabulary: Corpus : Body of text, singular. Corpora is the plural of this. Lexicon : Words and their meanings. Token : Each “entity” that is a part of whatever was split up based on rules.In corpus linguistics, part-of-speech tagging (POS tagging or PoS tagging or POST), also called grammatical tagging or word-category disambiguation. "
},
{
"code": null,
"e": 1327,
"s": 1160,
"text": "Input: Everything is all about money.\nOutput: [('Everything', 'NN'), ('is', 'VBZ'), \n ('all', 'DT'),('about', 'IN'), \n ('money', 'NN'), ('.', '.')] "
},
{
"code": null,
"e": 1390,
"s": 1327,
"text": "Here’s a list of the tags, what they mean, and some examples: "
},
{
"code": null,
"e": 2499,
"s": 1390,
"text": "CC coordinating conjunction CD cardinal digit DT determiner EX existential there (like: “there is” ... think of it like “there exists”) FW foreign word IN preposition/subordinating conjunction JJ adjective – ‘big’ JJR adjective, comparative – ‘bigger’ JJS adjective, superlative – ‘biggest’ LS list marker 1) MD modal – could, will NN noun, singular ‘- desk’ NNS noun plural – ‘desks’ NNP proper noun, singular – ‘Harrison’ NNPS proper noun, plural – ‘Americans’ PDT predeterminer – ‘all the kids’ POS possessive ending parent’s PRP personal pronoun – I, he, she PRP$ possessive pronoun – my, his, hers RB adverb – very, silently, RBR adverb, comparative – better RBS adverb, superlative – best RP particle – give up TO – to go ‘to’ the store. UH interjection – errrrrrrrm VB verb, base form – take VBD verb, past tense – took VBG verb, gerund/present participle – taking VBN verb, past participle – taken VBP verb, sing. present, non-3d – take VBZ verb, 3rd person sing. present – takes WDT wh-determiner – which WP wh-pronoun – who, what WP$ possessive wh-pronoun, eg- whose WRB wh-adverb, eg- where, when"
},
{
"code": null,
"e": 2955,
"s": 2499,
"text": "Text may contain stop words like ‘the’, ‘is’, ‘are’. Stop words can be filtered from the text to be processed. There is no universal list of stop words in nlp research, however the nltk module contains a list of stop words. You can add your own Stop word. Go to your NLTK download directory path -> corpora -> stopwords -> update the stop word file depends on your language which one you are using. Here we are using english (stopwords.words(‘english’)). "
},
{
"code": null,
"e": 2962,
"s": 2955,
"text": "Python"
},
{
"code": "import nltkfrom nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize, sent_tokenizestop_words = set(stopwords.words('english')) // Dummy texttxt = \"Sukanya, Rajib and Naba are my good friends. \" \\ \"Sukanya is getting married next year. \" \\ \"Marriage is a big step in one’s life.\" \\ \"It is both exciting and frightening. \" \\ \"But friendship is a sacred bond between people.\" \\ \"It is a special kind of love between us. \" \\ \"Many of you must have tried searching for a friend \"\\ \"but never found the right one.\" # sent_tokenize is one of instances of# PunktSentenceTokenizer from the nltk.tokenize.punkt module tokenized = sent_tokenize(txt)for i in tokenized: # Word tokenizers is used to find the words # and punctuation in a string wordsList = nltk.word_tokenize(i) # removing stop words from wordList wordsList = [w for w in wordsList if not w in stop_words] # Using a Tagger. Which is part-of-speech # tagger or POS-tagger. tagged = nltk.pos_tag(wordsList) print(tagged)",
"e": 4008,
"s": 2962,
"text": null
},
{
"code": null,
"e": 4018,
"s": 4008,
"text": "Output: "
},
{
"code": null,
"e": 4692,
"s": 4018,
"text": "[('Sukanya', 'NNP'), ('Rajib', 'NNP'), ('Naba', 'NNP'), ('good', 'JJ'), ('friends', 'NNS')]\n[('Sukanya', 'NNP'), ('getting', 'VBG'), ('married', 'VBN'), ('next', 'JJ'), ('year', 'NN')]\n[('Marriage', 'NN'), ('big', 'JJ'), ('step', 'NN'), ('one', 'CD'), ('’', 'NN'), ('life', 'NN')]\n[('It', 'PRP'), ('exciting', 'VBG'), ('frightening', 'VBG')]\n[('But', 'CC'), ('friendship', 'NN'), ('sacred', 'VBD'), ('bond', 'NN'), ('people', 'NNS')]\n[('It', 'PRP'), ('special', 'JJ'), ('kind', 'NN'), ('love', 'VB'), ('us', 'PRP')]\n[('Many', 'JJ'), ('must', 'MD'), ('tried', 'VB'), ('searching', 'VBG'), ('friend', 'NN'), \n('never', 'RB'), ('found', 'VBD'), ('right', 'RB'), ('one', 'CD')]"
},
{
"code": null,
"e": 4915,
"s": 4692,
"text": "Basically, the goal of a POS tagger is to assign linguistic (mostly grammatical) information to sub-sentential units. Such units are called tokens and, most of the time, correspond to words and symbols (e.g. punctuation). "
},
{
"code": null,
"e": 4927,
"s": 4915,
"text": "jaikrishna1"
},
{
"code": null,
"e": 4936,
"s": 4927,
"text": "rkbhola5"
},
{
"code": null,
"e": 4951,
"s": 4936,
"text": "python-modules"
},
{
"code": null,
"e": 4958,
"s": 4951,
"text": "Python"
}
] |
How to compare values in two Pandas Dataframes?
|
12 Jan, 2022
Let’s discuss how to compare values in the Pandas dataframe. Here are the steps for comparing values in two pandas Dataframes:
Step 1 Dataframe Creation: The dataframes for the two datasets can be created using the following code:
Python3
import pandas as pd # elements of first datasetfirst_Set = {'Prod_1': ['Laptop', 'Mobile Phone', 'Desktop', 'LED'], 'Price_1': [25000, 8000, 20000, 35000] } # creation of Dataframe 1df1 = pd.DataFrame(first_Set, columns=['Prod_1', 'Price_1'])print(df1) # elements of second datasetsecond_Set = {'Prod_2': ['Laptop', 'Mobile Phone', 'Desktop', 'LED'], 'Price_2': [25000, 10000, 15000, 30000] } # creation of Dataframe 2df2 = pd.DataFrame(second_Set, columns=['Prod_2', 'Price_2'])print(df2)
Output:
Step 2 Comparison of values: You need to import numpy for the successful execution of this step. Here is the general template to perform the comparison:
df1[‘new column for the comparison results’] = np.where(condition, ‘value if true’, ‘value if false’)
Example: After execution of this code, the new column with the name Price_Matching will be formed under df1. Columns result will be displayed according to the following conditions:
If Price_1 is equal to Price_2, then assign the value of True
Otherwise, assign the value of False.
Python3
import numpy as np # add the Price2 column from# df2 to df1df1['Price_2'] = df2['Price_2'] # create new column in df1 to# check if prices matchdf1['Price_Matching'] = np.where(df1['Price_1'] == df2['Price_2'], 'True', 'False') df1
Output:
kumar_satyam
Python pandas-dataFrame
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 Jan, 2022"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Let’s discuss how to compare values in the Pandas dataframe. Here are the steps for comparing values in two pandas Dataframes:"
},
{
"code": null,
"e": 260,
"s": 155,
"text": "Step 1 Dataframe Creation: The dataframes for the two datasets can be created using the following code: "
},
{
"code": null,
"e": 268,
"s": 260,
"text": "Python3"
},
{
"code": "import pandas as pd # elements of first datasetfirst_Set = {'Prod_1': ['Laptop', 'Mobile Phone', 'Desktop', 'LED'], 'Price_1': [25000, 8000, 20000, 35000] } # creation of Dataframe 1df1 = pd.DataFrame(first_Set, columns=['Prod_1', 'Price_1'])print(df1) # elements of second datasetsecond_Set = {'Prod_2': ['Laptop', 'Mobile Phone', 'Desktop', 'LED'], 'Price_2': [25000, 10000, 15000, 30000] } # creation of Dataframe 2df2 = pd.DataFrame(second_Set, columns=['Prod_2', 'Price_2'])print(df2)",
"e": 855,
"s": 268,
"text": null
},
{
"code": null,
"e": 863,
"s": 855,
"text": "Output:"
},
{
"code": null,
"e": 1016,
"s": 863,
"text": "Step 2 Comparison of values: You need to import numpy for the successful execution of this step. Here is the general template to perform the comparison:"
},
{
"code": null,
"e": 1118,
"s": 1016,
"text": "df1[‘new column for the comparison results’] = np.where(condition, ‘value if true’, ‘value if false’)"
},
{
"code": null,
"e": 1300,
"s": 1118,
"text": "Example: After execution of this code, the new column with the name Price_Matching will be formed under df1. Columns result will be displayed according to the following conditions: "
},
{
"code": null,
"e": 1362,
"s": 1300,
"text": "If Price_1 is equal to Price_2, then assign the value of True"
},
{
"code": null,
"e": 1400,
"s": 1362,
"text": "Otherwise, assign the value of False."
},
{
"code": null,
"e": 1408,
"s": 1400,
"text": "Python3"
},
{
"code": "import numpy as np # add the Price2 column from# df2 to df1df1['Price_2'] = df2['Price_2'] # create new column in df1 to# check if prices matchdf1['Price_Matching'] = np.where(df1['Price_1'] == df2['Price_2'], 'True', 'False') df1",
"e": 1671,
"s": 1408,
"text": null
},
{
"code": null,
"e": 1679,
"s": 1671,
"text": "Output:"
},
{
"code": null,
"e": 1692,
"s": 1679,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1716,
"s": 1692,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1730,
"s": 1716,
"text": "Python-pandas"
},
{
"code": null,
"e": 1737,
"s": 1730,
"text": "Python"
}
] |
Cristian's Algorithm - GeeksforGeeks
|
10 Nov, 2021
Cristian’s Algorithm is a clock synchronization algorithm is used to synchronize time with a time server by client processes. This algorithm works well with low-latency networks where Round Trip Time is short as compared to accuracy while redundancy-prone distributed systems/applications do not go hand in hand with this algorithm. Here Round Trip Time refers to the time duration between the start of a Request and the end of the corresponding Response.Below is an illustration imitating the working of Cristian’s algorithm:
Algorithm:1) The process on the client machine sends the request for fetching clock time(time at the server) to the Clock Server at time .2) The Clock Server listens to the request made by the client process and returns the response in form of clock server time.3) The client process fetches the response from the Clock Server at time and calculates the synchronized client clock time using the formula given below.
where refers to the synchronized clock time, refers to the clock time returned by the server, refers to the time at which request was sent by the client process, refers to the time at which response was received by the client processWorking/Reliability of the above formula:refers to the combined time taken by the network and the server to transfer the request to the server, process the request, and return the response back to the client process, assuming that the network latency and are approximately equal.The time at the client-side differs from actual time by at most seconds. Using the above statement we can draw a conclusion that the error in synchronization can be at most seconds. Hence,
Python Codes below illustrate the working of Cristian’s algorithm: Code below is used to initiate a prototype of a clock server on local machine:
Python3
# Python3 program imitating a clock server import socketimport datetime # function used to initiate the Clock Serverdef initiateClockServer(): s = socket.socket() print("Socket successfully created") # Server port port = 8000 s.bind(('', port)) # Start listening to requests s.listen(5) print("Socket is listening...") # Clock Server Running forever while True: # Establish connection with client connection, address = s.accept() print('Server connected to', address) # Respond the client with server clock time connection.send(str( datetime.datetime.now()).encode()) # Close the connection with the client process connection.close() # Driver functionif __name__ == '__main__': # Trigger the Clock Server initiateClockServer()
Output:
Socket successfully created
Socket is listening...
Code below is used to initiate a prototype of a client process on the local machine:
Python3
# Python3 program imitating a client process import socketimport datetimefrom dateutil import parserfrom timeit import default_timer as timer # function used to Synchronize client process timedef synchronizeTime(): s = socket.socket() # Server port port = 8000 # connect to the clock server on local computer s.connect(('127.0.0.1', port)) request_time = timer() # receive data from the server server_time = parser.parse(s.recv(1024).decode()) response_time = timer() actual_time = datetime.datetime.now() print("Time returned by server: " + str(server_time)) process_delay_latency = response_time - request_time print("Process Delay latency: " \ + str(process_delay_latency) \ + " seconds") print("Actual clock time at client side: " \ + str(actual_time)) # synchronize process client clock time client_time = server_time \ + datetime.timedelta(seconds = \ (process_delay_latency) / 2) print("Synchronized process client time: " \ + str(client_time)) # calculate synchronization error error = actual_time - client_time print("Synchronization error : " + str(error.total_seconds()) + " seconds") s.close() # Driver functionif __name__ == '__main__': # synchronize time using clock server synchronizeTime()
Output:
Time returned by server: 2018-11-07 17:56:43.302379
Process Delay latency: 0.0005150819997652434 seconds
Actual clock time at client side: 2018-11-07 17:56:43.302756
Synchronized process client time: 2018-11-07 17:56:43.302637
Synchronization error : 0.000119 seconds
Improvision in Clock Synchronization:Using iterative testing over the network, we can define a minimum transfer time using which we can formulate an improved synchronization clock time(less synchronization error). Here, by defining a minimum transfer time, with a high confidence, we can say that the server time will always be generated after and the will always be generated before , where is the minimum transfer time which is the minimum value of and during several iterative tests. Here synchronization error can be formulated as follows:
Similarly, if and differ by a considerable amount of time, we may substitute by and , where is the minimum observed request time and refers to the minimum observed response time over the network. The synchronized clock time in this case can be calculated as:
So, by just introducing response and request time as separate time latencies, we can improve the synchronization of clock time and hence decrease the overall synchronization error. A number of iterative tests to be run depends on the overall clock drift observed.References: 1) https://en.wikipedia.org/wiki/Cristian%27s_algorithm 2) https://en.wikipedia.org/wiki/Round-trip_delay_time 3) https://www.geeksforgeeks.org/socket-programming-python 4) https://en.wikipedia.org/wiki/Clock_drift
varshagumber28
abhishek0719kadiyan
as5853535
tanwarsinghvaibhav
Clock Synchronization Algorithm
Technical Scripter 2018
Algorithms
Computer Networks
Python
Technical Scripter
Algorithms
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Difference between Informed and Uninformed Search in AI
Recursive Practice Problems with Solutions
Layers of OSI Model
TCP/IP Model
TCP Server-Client implementation in C
RSA Algorithm in Cryptography
Differences between TCP and UDP
|
[
{
"code": null,
"e": 24057,
"s": 24029,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 24586,
"s": 24057,
"text": "Cristian’s Algorithm is a clock synchronization algorithm is used to synchronize time with a time server by client processes. This algorithm works well with low-latency networks where Round Trip Time is short as compared to accuracy while redundancy-prone distributed systems/applications do not go hand in hand with this algorithm. Here Round Trip Time refers to the time duration between the start of a Request and the end of the corresponding Response.Below is an illustration imitating the working of Cristian’s algorithm: "
},
{
"code": null,
"e": 25002,
"s": 24586,
"text": "Algorithm:1) The process on the client machine sends the request for fetching clock time(time at the server) to the Clock Server at time .2) The Clock Server listens to the request made by the client process and returns the response in form of clock server time.3) The client process fetches the response from the Clock Server at time and calculates the synchronized client clock time using the formula given below."
},
{
"code": null,
"e": 25709,
"s": 25007,
"text": "where refers to the synchronized clock time, refers to the clock time returned by the server, refers to the time at which request was sent by the client process, refers to the time at which response was received by the client processWorking/Reliability of the above formula:refers to the combined time taken by the network and the server to transfer the request to the server, process the request, and return the response back to the client process, assuming that the network latency and are approximately equal.The time at the client-side differs from actual time by at most seconds. Using the above statement we can draw a conclusion that the error in synchronization can be at most seconds. Hence, "
},
{
"code": null,
"e": 25862,
"s": 25714,
"text": "Python Codes below illustrate the working of Cristian’s algorithm: Code below is used to initiate a prototype of a clock server on local machine: "
},
{
"code": null,
"e": 25870,
"s": 25862,
"text": "Python3"
},
{
"code": "# Python3 program imitating a clock server import socketimport datetime # function used to initiate the Clock Serverdef initiateClockServer(): s = socket.socket() print(\"Socket successfully created\") # Server port port = 8000 s.bind(('', port)) # Start listening to requests s.listen(5) print(\"Socket is listening...\") # Clock Server Running forever while True: # Establish connection with client connection, address = s.accept() print('Server connected to', address) # Respond the client with server clock time connection.send(str( datetime.datetime.now()).encode()) # Close the connection with the client process connection.close() # Driver functionif __name__ == '__main__': # Trigger the Clock Server initiateClockServer()",
"e": 26754,
"s": 25870,
"text": null
},
{
"code": null,
"e": 26764,
"s": 26754,
"text": "Output: "
},
{
"code": null,
"e": 26815,
"s": 26764,
"text": "Socket successfully created\nSocket is listening..."
},
{
"code": null,
"e": 26901,
"s": 26815,
"text": "Code below is used to initiate a prototype of a client process on the local machine: "
},
{
"code": null,
"e": 26909,
"s": 26901,
"text": "Python3"
},
{
"code": "# Python3 program imitating a client process import socketimport datetimefrom dateutil import parserfrom timeit import default_timer as timer # function used to Synchronize client process timedef synchronizeTime(): s = socket.socket() # Server port port = 8000 # connect to the clock server on local computer s.connect(('127.0.0.1', port)) request_time = timer() # receive data from the server server_time = parser.parse(s.recv(1024).decode()) response_time = timer() actual_time = datetime.datetime.now() print(\"Time returned by server: \" + str(server_time)) process_delay_latency = response_time - request_time print(\"Process Delay latency: \" \\ + str(process_delay_latency) \\ + \" seconds\") print(\"Actual clock time at client side: \" \\ + str(actual_time)) # synchronize process client clock time client_time = server_time \\ + datetime.timedelta(seconds = \\ (process_delay_latency) / 2) print(\"Synchronized process client time: \" \\ + str(client_time)) # calculate synchronization error error = actual_time - client_time print(\"Synchronization error : \" + str(error.total_seconds()) + \" seconds\") s.close() # Driver functionif __name__ == '__main__': # synchronize time using clock server synchronizeTime()",
"e": 28364,
"s": 26909,
"text": null
},
{
"code": null,
"e": 28374,
"s": 28364,
"text": "Output: "
},
{
"code": null,
"e": 28642,
"s": 28374,
"text": "Time returned by server: 2018-11-07 17:56:43.302379\nProcess Delay latency: 0.0005150819997652434 seconds\nActual clock time at client side: 2018-11-07 17:56:43.302756\nSynchronized process client time: 2018-11-07 17:56:43.302637\nSynchronization error : 0.000119 seconds"
},
{
"code": null,
"e": 29187,
"s": 28642,
"text": "Improvision in Clock Synchronization:Using iterative testing over the network, we can define a minimum transfer time using which we can formulate an improved synchronization clock time(less synchronization error). Here, by defining a minimum transfer time, with a high confidence, we can say that the server time will always be generated after and the will always be generated before , where is the minimum transfer time which is the minimum value of and during several iterative tests. Here synchronization error can be formulated as follows: "
},
{
"code": null,
"e": 29452,
"s": 29192,
"text": "Similarly, if and differ by a considerable amount of time, we may substitute by and , where is the minimum observed request time and refers to the minimum observed response time over the network. The synchronized clock time in this case can be calculated as: "
},
{
"code": null,
"e": 29948,
"s": 29457,
"text": "So, by just introducing response and request time as separate time latencies, we can improve the synchronization of clock time and hence decrease the overall synchronization error. A number of iterative tests to be run depends on the overall clock drift observed.References: 1) https://en.wikipedia.org/wiki/Cristian%27s_algorithm 2) https://en.wikipedia.org/wiki/Round-trip_delay_time 3) https://www.geeksforgeeks.org/socket-programming-python 4) https://en.wikipedia.org/wiki/Clock_drift "
},
{
"code": null,
"e": 29963,
"s": 29948,
"text": "varshagumber28"
},
{
"code": null,
"e": 29983,
"s": 29963,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 29993,
"s": 29983,
"text": "as5853535"
},
{
"code": null,
"e": 30012,
"s": 29993,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 30044,
"s": 30012,
"text": "Clock Synchronization Algorithm"
},
{
"code": null,
"e": 30068,
"s": 30044,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30079,
"s": 30068,
"text": "Algorithms"
},
{
"code": null,
"e": 30097,
"s": 30079,
"text": "Computer Networks"
},
{
"code": null,
"e": 30104,
"s": 30097,
"text": "Python"
},
{
"code": null,
"e": 30123,
"s": 30104,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30134,
"s": 30123,
"text": "Algorithms"
},
{
"code": null,
"e": 30152,
"s": 30134,
"text": "Computer Networks"
},
{
"code": null,
"e": 30250,
"s": 30152,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30259,
"s": 30250,
"text": "Comments"
},
{
"code": null,
"e": 30272,
"s": 30259,
"text": "Old Comments"
},
{
"code": null,
"e": 30321,
"s": 30272,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30346,
"s": 30321,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30373,
"s": 30346,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 30429,
"s": 30373,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 30472,
"s": 30429,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 30492,
"s": 30472,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 30505,
"s": 30492,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 30543,
"s": 30505,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 30573,
"s": 30543,
"text": "RSA Algorithm in Cryptography"
}
] |
How to step up your Folium Choropleth Map skills | by Navid Mashinchi | Towards Data Science
|
The purpose of this tutorial is to take your Foilium skills to the next level. In this article, we will create a more advanced Choroplet map than usual. We will add customized functionalities to add a draggable legend, hover functionalities, and cross-hatching (crossing lines). If you would like to learn those skills, I highly recommend going over each step on your own with a sample dataset. You will learn tools that you can implement in your own projects and impress your boss or client. Some of the functionalities took me hours of research, and I thought it would be a good idea to share these skills for people to step up their folium skills. Sharing is caring, and I always like to share knowledge and pass it on to people that look to improve. So I hope you will enjoy this tutorial.
The first step is to clean the data to plot our Choropleth map.
# We first import the libraries. import pandas as pdimport folium from folium.plugins import StripePatternimport geopandas as gpdimport numpy as np# Next we import the data. df = pd.read_csv("sample_data")# We grab the state and wills columndf = df[["state","wills"]]df.head()
# We check how many rows we have and the types of our data.df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 48 entries, 0 to 47Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 state 48 non-null object 1 wills 32 non-null float64dtypes: float64(1), object(1)memory usage: 896.0+ bytes
As we can see above, we have 48 entries and 16 missing values in the wills column. The next step is to import the geoJson file. To create a choropleth, we need two things:
First, we need a geoJSON file that gives us the geographical coordinates for the layers. We can then use geopandas to read the coordinates into a data frame.
Second, we need the values to be displayed on the maps in different colors. In our example, we will use the “wills” column from our sample data.
For our example, we need the coordinates of the US states.
# We import the geoJSON file. url = ("https://raw.githubusercontent.com/python-visualization/folium/master/examples/data")state_geo = f"{url}/us-states.json"# We read the file and print it.geoJSON_df = gpd.read_file(state_geo)geoJSON_df.head()
In the data frame above, you see the geometry column, which gives us the Choropleth map layers’ coordinates.
# Next we grab the states and put them in a list and check the length.geoJSON_states = list(geoJSON_df.id.values)len(geoJSON_states)48
Our actual data has 48 states. Hence we are missing two states. Let’s figure out which states are missing because we need to merge the two datasets in the next steps to plot our Choropleth map. To find the missing states, we will use the NumPy setdiff1d function. The function finds the set difference of two arrays.
# Let's check which states are missing.missing_states = np.setdiff1d(geoJSON_states,df_states_list)missing_statesarray(['AK', 'HI'], dtype='<U2')
The missing states are Alaska and Hawaii. The next step is to remove those two states from the geoJSON data frame, so we have the same amount of states in both data frames to merge both data frames. To merge the two data frames, we need to make sure the column names of both data frames with the state values have the same column name. When we merge the data frames, we need to merge them based on a specific key, as you will see below.
# we rename the column from id to state in the geoJSON_df so we can merge the two data frames.geoJSON_df = geoJSON_df.rename(columns = {"id":"state"})# Next we merge our sample data (df) and the geoJSON data frame on the key id.final_df = geoJSON_df.merge(df, on = "state")final_df.head()
Voila, as you can see above, we have the merged data frame. Up to this point, we cleaned the data and are ready to work on the folium map and get to the fun part.
To create a Folium map, we need to set the initial coordinates so we tell at which coordinates the map is centered at the beginning.
# Initialize folium map.sample_map = folium.Map(location=[48, -102], zoom_start=4)sample_map
You should see a map of the United States above. The next step is to create the Choropleth and add the layers to display the different colors based on the wills column from our sample data.
To set up the Choropleth map, we will use the foliumChoropleth() function. The most critical parameters that we need to set up correctly are the geo_data, data, columns, key_on, and fill_color. To get a better understanding of the parameters, we take a look at the documentation. According to the documentation, we learn the following:
geo_data (string/object) — URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON geometries
data (Pandas DataFrame or Series, default None) — Data to bind to the GeoJSON.
columns (dict or tuple, default None) — If the data is a Pandas DataFrame, the columns of data to be bound. Must pass column 1 as the key, and column 2 the values.
key_on (string, default None) — Variable in the geo_data GeoJSON file to bind the data to. Must start with ‘feature’ and be in JavaScript objection notation. Ex: ‘feature.id’ or ‘feature.properties.statename’.
To learn more about the other parameters that you see above, please refer to the following link:
python-visualization.github.io
The next step is to set up the Choropleth map.
# Set up Choropleth mapfolium.Choropleth(geo_data=final_df,data=final_df,columns=['state',"wills"],key_on="feature.properties.state",fill_color='YlGnBu',fill_opacity=1,line_opacity=0.2,legend_name="wills",smooth_factor=0,Highlight= True,line_color = "#0000",name = "Wills",show=False,overlay=True,nan_fill_color = "White").add_to(sample_map)sample_map
As you can see above, the white states represent null values in the data. In the code above, I set the nan_fill_color parameter to white.
Up to this point, this is pretty much how you create a basic Choropleth using folium. This might be satisfying, but we should probably inform the user what the white states really mean. The legend above doesn’t tell us the information since it’s just giving us the information about the wills column. To spice things up and take this plot to another level, we should probably add another legend to this plot so that the user can tell by just looking at the map that the white states represent null values. To add a secondary legend, I came across a good example online, which I highly recommend going over. See link below:
nbviewer.jupyter.org
We are just not going to add a regular legend, but a draggable legend that makes your plot even more interactive. To add the draggable legend, you probably need to understand some basic HTML and JavaScript. Please see the code below for illustration.
# We import the required library:from branca.element import Template, MacroElementtemplate = """{% macro html(this, kwargs) %}<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Draggable - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#maplegend" ).draggable({ start: function (event, ui) { $(this).css({ right: "auto", top: "auto", bottom: "auto" }); } });}); </script></head><body> <div id='maplegend' class='maplegend' style='position: absolute; z-index:9999; border:2px solid grey; background-color:rgba(255, 255, 255, 0.8); border-radius:6px; padding: 10px; font-size:14px; right: 20px; bottom: 20px;'> <div class='legend-title'>Legend (draggable!)</div><div class='legend-scale'> <ul class='legend-labels'> <li><span style='background:white;opacity:0.7;'></span>States that have Null values.</li> </ul></div></div> </body></html><style type='text/css'> .maplegend .legend-title { text-align: left; margin-bottom: 5px; font-weight: bold; font-size: 90%; } .maplegend .legend-scale ul { margin: 0; margin-bottom: 5px; padding: 0; float: left; list-style: none; } .maplegend .legend-scale ul li { font-size: 80%; list-style: none; margin-left: 0; line-height: 18px; margin-bottom: 2px; } .maplegend ul.legend-labels li span { display: block; float: left; height: 16px; width: 30px; margin-right: 5px; margin-left: 0; border: 1px solid #999; } .maplegend .legend-source { font-size: 80%; color: #777; clear: both; } .maplegend a { color: #777; }</style>{% endmacro %}"""macro = MacroElement()macro._template = Template(template)sample_map.get_root().add_child(macro)sample_map
As you can see above, we have added the draggable legend. You can click on it and drag it to the position you wish. If you aren’t familiar with HTML, I suggest you copy and paste the code to your project and pay attention to the following line:
<li><span style=’background:white;opacity:0.7;’></span>States that have Null values.</li>
If you want to add multiple values in the legend, just copy-paste the line above and change the background color and the name.
Suppose your boss doesn’t like you to have two legends, and he asks you to come up with another solution. Another option would be to add cross-hatching (crossing lines) that represents the missing values. To add patterns to the layer, we need to use the folium plugin called StripePattern. Please see below the code:
# We create another map called sample_map2.sample_map2 = folium.Map(location=[48, -102], zoom_start=4)# Set up Choropleth mapfolium.Choropleth(geo_data=final_df,data=final_df,columns=['state',"wills"],key_on="feature.properties.state",fill_color='YlGnBu',fill_opacity=1,line_opacity=0.2,legend_name="wills",smooth_factor=0,Highlight= True,line_color = "#0000",name = "Wills",show=True,overlay=True,nan_fill_color = "White").add_to(sample_map2)# Here we add cross-hatching (crossing lines) to display the Null values.nans = final_df[final_df["wills"].isnull()]['state'].valuesgdf_nans = final_df[final_df['state'].isin(nans)]sp = StripePattern(angle=45, color='grey', space_color='white')sp.add_to(sample_map2)folium.features.GeoJson(name="Click for Wills NaN values",data=gdf_nans, style_function=lambda x :{'fillPattern': sp},show=True).add_to(sample_map2)# We add a layer controller. folium.LayerControl(collapsed=False).add_to(sample_map2)sample_map2
To add the cross-hatching above, we look at the following lines in the code above:
nans = final_df[final_df[“wills”].isnull()][‘state’].valuesgdf_nans = final_df[final_df[‘state’].isin(nans)]sp = StripePattern(angle=45, color=’grey’, space_color=’white’)sp.add_to(sample_map2)folium.features.GeoJson(name=”Click for earnings NaN values”,data=gdf_nans, style_function=lambda x :{‘fillPattern’: sp},show=True).add_to(sample_map2)
nans = final_df[final_df[“wills”].isnull()][‘state’].values
gdf_nans = final_df[final_df[‘state’].isin(nans)]
sp = StripePattern(angle=45, color=’grey’, space_color=’white’)
sp.add_to(sample_map2)
folium.features.GeoJson(name=”Click for earnings NaN values”,data=gdf_nans, style_function=lambda x :{‘fillPattern’: sp},show=True).add_to(sample_map2)
In number 1, we grab the states inside the wills column that have null values. In number 2, I am extracting the rows where the state is equal to the states that are inside the nans variable from number 1. In numbers 3 and 4, I set up the pattern that I would like to show for the NaN values. Lastly, in number 5, I add the NaN layer with the sp variable as the fillPattern. Note I am also adding the layer controller in the second last row.
The last topic that I will go over is the hover functionality. Suppose you want to hover over the states and display some data. In order to add this functionality, we will again use the folium. features.GeoJson() function as we did in the code above.
# Add hover functionality.style_function = lambda x: {'fillColor': '#ffffff', 'color':'#000000', 'fillOpacity': 0.1, 'weight': 0.1}highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.50, 'weight': 0.1}NIL = folium.features.GeoJson( data = final_df, style_function=style_function, control=False, highlight_function=highlight_function, tooltip=folium.features.GeoJsonTooltip( fields=['state','wills'], aliases=['state','wills'], style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;") ))sample_map2.add_child(NIL)sample_map2.keep_in_front(NIL)sample_map2
First, we create a style_function and a highlight_function to finalize how we want our hover function to appear. Next, at the NIL variable, we need to pay attention to the right parameter values.
We set the data to the final_df data frame.
We set the style function to the style_function we created on the second line.
We set the highlight function to the highlight_function from line 6.
We use the GeoJsonTooltip function and set the fields and aliases parameters to the column names in our final_df data frame to display the desired data points when we hover over the states.
See the final code all together below. I have also added the light and dark mode option, to the layer controller at the bottom of the code. I am using the cartodbdark_matter layer for the light mode, and for the dark mode, I use the cartodbpositron layer.
# We create another map called sample_map2.sample_map2 = folium.Map(location=[48, -102], zoom_start=4)# Set up Choropleth mapfolium.Choropleth(geo_data=final_df,data=final_df,columns=['state',"wills"],key_on="feature.properties.state",fill_color='YlGnBu',fill_opacity=1,line_opacity=0.2,legend_name="wills",smooth_factor=0,Highlight= True,line_color = "#0000",name = "Wills",show=True,overlay=True,nan_fill_color = "White").add_to(sample_map2)# Add hover functionality.style_function = lambda x: {'fillColor': '#ffffff', 'color':'#000000', 'fillOpacity': 0.1, 'weight': 0.1}highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.50, 'weight': 0.1}NIL = folium.features.GeoJson( data = final_df, style_function=style_function, control=False, highlight_function=highlight_function, tooltip=folium.features.GeoJsonTooltip( fields=['state','wills'], aliases=['state','wills'], style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;") ))sample_map2.add_child(NIL)sample_map2.keep_in_front(NIL)# Here we add cross-hatching (crossing lines) to display the Null values.nans = final_df[final_df["wills"].isnull()]['state'].valuesgdf_nans = final_df[final_df['state'].isin(nans)]sp = StripePattern(angle=45, color='grey', space_color='white')sp.add_to(sample_map2)folium.features.GeoJson(name="Click for Wills NaN values",data=gdf_nans, style_function=lambda x :{'fillPattern': sp},show=True).add_to(sample_map2)# Add dark and light mode. folium.TileLayer('cartodbdark_matter',name="dark mode",control=True).add_to(sample_map2)folium.TileLayer('cartodbpositron',name="light mode",control=True).add_to(sample_map2)# We add a layer controller. folium.LayerControl(collapsed=False).add_to(sample_map2)sample_map2
Finally, let us go over the steps that we went over in this tutorial and summarize what we learned:
We used NumPy, Pandas, and GeoPandas to clean the data and created a final data frame by merging the geoJSON data and our sample data to create a Choropleth map using folium.
We learned how to add a draggable legend.
We also learned how to add cross-hatching (crossing lines) to display the null values.
Last but not least, we went over the hover functionality.
I hope you enjoyed this tutorial, and you will be able to implement these skills in your future projects to introduce your boss or client. If you have any questions on this topic or have some feedback, feel free to contact me. I’d be very grateful if you would share it on any social media platforms. Thank you and until next time️! ✌️
|
[
{
"code": null,
"e": 966,
"s": 172,
"text": "The purpose of this tutorial is to take your Foilium skills to the next level. In this article, we will create a more advanced Choroplet map than usual. We will add customized functionalities to add a draggable legend, hover functionalities, and cross-hatching (crossing lines). If you would like to learn those skills, I highly recommend going over each step on your own with a sample dataset. You will learn tools that you can implement in your own projects and impress your boss or client. Some of the functionalities took me hours of research, and I thought it would be a good idea to share these skills for people to step up their folium skills. Sharing is caring, and I always like to share knowledge and pass it on to people that look to improve. So I hope you will enjoy this tutorial."
},
{
"code": null,
"e": 1030,
"s": 966,
"text": "The first step is to clean the data to plot our Choropleth map."
},
{
"code": null,
"e": 1307,
"s": 1030,
"text": "# We first import the libraries. import pandas as pdimport folium from folium.plugins import StripePatternimport geopandas as gpdimport numpy as np# Next we import the data. df = pd.read_csv(\"sample_data\")# We grab the state and wills columndf = df[[\"state\",\"wills\"]]df.head()"
},
{
"code": null,
"e": 1674,
"s": 1307,
"text": "# We check how many rows we have and the types of our data.df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 48 entries, 0 to 47Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 state 48 non-null object 1 wills 32 non-null float64dtypes: float64(1), object(1)memory usage: 896.0+ bytes"
},
{
"code": null,
"e": 1846,
"s": 1674,
"text": "As we can see above, we have 48 entries and 16 missing values in the wills column. The next step is to import the geoJson file. To create a choropleth, we need two things:"
},
{
"code": null,
"e": 2004,
"s": 1846,
"text": "First, we need a geoJSON file that gives us the geographical coordinates for the layers. We can then use geopandas to read the coordinates into a data frame."
},
{
"code": null,
"e": 2149,
"s": 2004,
"text": "Second, we need the values to be displayed on the maps in different colors. In our example, we will use the “wills” column from our sample data."
},
{
"code": null,
"e": 2208,
"s": 2149,
"text": "For our example, we need the coordinates of the US states."
},
{
"code": null,
"e": 2452,
"s": 2208,
"text": "# We import the geoJSON file. url = (\"https://raw.githubusercontent.com/python-visualization/folium/master/examples/data\")state_geo = f\"{url}/us-states.json\"# We read the file and print it.geoJSON_df = gpd.read_file(state_geo)geoJSON_df.head()"
},
{
"code": null,
"e": 2561,
"s": 2452,
"text": "In the data frame above, you see the geometry column, which gives us the Choropleth map layers’ coordinates."
},
{
"code": null,
"e": 2696,
"s": 2561,
"text": "# Next we grab the states and put them in a list and check the length.geoJSON_states = list(geoJSON_df.id.values)len(geoJSON_states)48"
},
{
"code": null,
"e": 3013,
"s": 2696,
"text": "Our actual data has 48 states. Hence we are missing two states. Let’s figure out which states are missing because we need to merge the two datasets in the next steps to plot our Choropleth map. To find the missing states, we will use the NumPy setdiff1d function. The function finds the set difference of two arrays."
},
{
"code": null,
"e": 3159,
"s": 3013,
"text": "# Let's check which states are missing.missing_states = np.setdiff1d(geoJSON_states,df_states_list)missing_statesarray(['AK', 'HI'], dtype='<U2')"
},
{
"code": null,
"e": 3596,
"s": 3159,
"text": "The missing states are Alaska and Hawaii. The next step is to remove those two states from the geoJSON data frame, so we have the same amount of states in both data frames to merge both data frames. To merge the two data frames, we need to make sure the column names of both data frames with the state values have the same column name. When we merge the data frames, we need to merge them based on a specific key, as you will see below."
},
{
"code": null,
"e": 3885,
"s": 3596,
"text": "# we rename the column from id to state in the geoJSON_df so we can merge the two data frames.geoJSON_df = geoJSON_df.rename(columns = {\"id\":\"state\"})# Next we merge our sample data (df) and the geoJSON data frame on the key id.final_df = geoJSON_df.merge(df, on = \"state\")final_df.head()"
},
{
"code": null,
"e": 4048,
"s": 3885,
"text": "Voila, as you can see above, we have the merged data frame. Up to this point, we cleaned the data and are ready to work on the folium map and get to the fun part."
},
{
"code": null,
"e": 4181,
"s": 4048,
"text": "To create a Folium map, we need to set the initial coordinates so we tell at which coordinates the map is centered at the beginning."
},
{
"code": null,
"e": 4274,
"s": 4181,
"text": "# Initialize folium map.sample_map = folium.Map(location=[48, -102], zoom_start=4)sample_map"
},
{
"code": null,
"e": 4464,
"s": 4274,
"text": "You should see a map of the United States above. The next step is to create the Choropleth and add the layers to display the different colors based on the wills column from our sample data."
},
{
"code": null,
"e": 4800,
"s": 4464,
"text": "To set up the Choropleth map, we will use the foliumChoropleth() function. The most critical parameters that we need to set up correctly are the geo_data, data, columns, key_on, and fill_color. To get a better understanding of the parameters, we take a look at the documentation. According to the documentation, we learn the following:"
},
{
"code": null,
"e": 4907,
"s": 4800,
"text": "geo_data (string/object) — URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON geometries"
},
{
"code": null,
"e": 4986,
"s": 4907,
"text": "data (Pandas DataFrame or Series, default None) — Data to bind to the GeoJSON."
},
{
"code": null,
"e": 5150,
"s": 4986,
"text": "columns (dict or tuple, default None) — If the data is a Pandas DataFrame, the columns of data to be bound. Must pass column 1 as the key, and column 2 the values."
},
{
"code": null,
"e": 5360,
"s": 5150,
"text": "key_on (string, default None) — Variable in the geo_data GeoJSON file to bind the data to. Must start with ‘feature’ and be in JavaScript objection notation. Ex: ‘feature.id’ or ‘feature.properties.statename’."
},
{
"code": null,
"e": 5457,
"s": 5360,
"text": "To learn more about the other parameters that you see above, please refer to the following link:"
},
{
"code": null,
"e": 5488,
"s": 5457,
"text": "python-visualization.github.io"
},
{
"code": null,
"e": 5535,
"s": 5488,
"text": "The next step is to set up the Choropleth map."
},
{
"code": null,
"e": 5887,
"s": 5535,
"text": "# Set up Choropleth mapfolium.Choropleth(geo_data=final_df,data=final_df,columns=['state',\"wills\"],key_on=\"feature.properties.state\",fill_color='YlGnBu',fill_opacity=1,line_opacity=0.2,legend_name=\"wills\",smooth_factor=0,Highlight= True,line_color = \"#0000\",name = \"Wills\",show=False,overlay=True,nan_fill_color = \"White\").add_to(sample_map)sample_map"
},
{
"code": null,
"e": 6025,
"s": 5887,
"text": "As you can see above, the white states represent null values in the data. In the code above, I set the nan_fill_color parameter to white."
},
{
"code": null,
"e": 6648,
"s": 6025,
"text": "Up to this point, this is pretty much how you create a basic Choropleth using folium. This might be satisfying, but we should probably inform the user what the white states really mean. The legend above doesn’t tell us the information since it’s just giving us the information about the wills column. To spice things up and take this plot to another level, we should probably add another legend to this plot so that the user can tell by just looking at the map that the white states represent null values. To add a secondary legend, I came across a good example online, which I highly recommend going over. See link below:"
},
{
"code": null,
"e": 6669,
"s": 6648,
"text": "nbviewer.jupyter.org"
},
{
"code": null,
"e": 6920,
"s": 6669,
"text": "We are just not going to add a regular legend, but a draggable legend that makes your plot even more interactive. To add the draggable legend, you probably need to understand some basic HTML and JavaScript. Please see the code below for illustration."
},
{
"code": null,
"e": 9143,
"s": 6920,
"text": "# We import the required library:from branca.element import Template, MacroElementtemplate = \"\"\"{% macro html(this, kwargs) %}<!doctype html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>jQuery UI Draggable - Default functionality</title> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\"> <script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script> <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script> <script> $( function() { $( \"#maplegend\" ).draggable({ start: function (event, ui) { $(this).css({ right: \"auto\", top: \"auto\", bottom: \"auto\" }); } });}); </script></head><body> <div id='maplegend' class='maplegend' style='position: absolute; z-index:9999; border:2px solid grey; background-color:rgba(255, 255, 255, 0.8); border-radius:6px; padding: 10px; font-size:14px; right: 20px; bottom: 20px;'> <div class='legend-title'>Legend (draggable!)</div><div class='legend-scale'> <ul class='legend-labels'> <li><span style='background:white;opacity:0.7;'></span>States that have Null values.</li> </ul></div></div> </body></html><style type='text/css'> .maplegend .legend-title { text-align: left; margin-bottom: 5px; font-weight: bold; font-size: 90%; } .maplegend .legend-scale ul { margin: 0; margin-bottom: 5px; padding: 0; float: left; list-style: none; } .maplegend .legend-scale ul li { font-size: 80%; list-style: none; margin-left: 0; line-height: 18px; margin-bottom: 2px; } .maplegend ul.legend-labels li span { display: block; float: left; height: 16px; width: 30px; margin-right: 5px; margin-left: 0; border: 1px solid #999; } .maplegend .legend-source { font-size: 80%; color: #777; clear: both; } .maplegend a { color: #777; }</style>{% endmacro %}\"\"\"macro = MacroElement()macro._template = Template(template)sample_map.get_root().add_child(macro)sample_map"
},
{
"code": null,
"e": 9388,
"s": 9143,
"text": "As you can see above, we have added the draggable legend. You can click on it and drag it to the position you wish. If you aren’t familiar with HTML, I suggest you copy and paste the code to your project and pay attention to the following line:"
},
{
"code": null,
"e": 9478,
"s": 9388,
"text": "<li><span style=’background:white;opacity:0.7;’></span>States that have Null values.</li>"
},
{
"code": null,
"e": 9605,
"s": 9478,
"text": "If you want to add multiple values in the legend, just copy-paste the line above and change the background color and the name."
},
{
"code": null,
"e": 9922,
"s": 9605,
"text": "Suppose your boss doesn’t like you to have two legends, and he asks you to come up with another solution. Another option would be to add cross-hatching (crossing lines) that represents the missing values. To add patterns to the layer, we need to use the folium plugin called StripePattern. Please see below the code:"
},
{
"code": null,
"e": 10876,
"s": 9922,
"text": "# We create another map called sample_map2.sample_map2 = folium.Map(location=[48, -102], zoom_start=4)# Set up Choropleth mapfolium.Choropleth(geo_data=final_df,data=final_df,columns=['state',\"wills\"],key_on=\"feature.properties.state\",fill_color='YlGnBu',fill_opacity=1,line_opacity=0.2,legend_name=\"wills\",smooth_factor=0,Highlight= True,line_color = \"#0000\",name = \"Wills\",show=True,overlay=True,nan_fill_color = \"White\").add_to(sample_map2)# Here we add cross-hatching (crossing lines) to display the Null values.nans = final_df[final_df[\"wills\"].isnull()]['state'].valuesgdf_nans = final_df[final_df['state'].isin(nans)]sp = StripePattern(angle=45, color='grey', space_color='white')sp.add_to(sample_map2)folium.features.GeoJson(name=\"Click for Wills NaN values\",data=gdf_nans, style_function=lambda x :{'fillPattern': sp},show=True).add_to(sample_map2)# We add a layer controller. folium.LayerControl(collapsed=False).add_to(sample_map2)sample_map2"
},
{
"code": null,
"e": 10959,
"s": 10876,
"text": "To add the cross-hatching above, we look at the following lines in the code above:"
},
{
"code": null,
"e": 11304,
"s": 10959,
"text": "nans = final_df[final_df[“wills”].isnull()][‘state’].valuesgdf_nans = final_df[final_df[‘state’].isin(nans)]sp = StripePattern(angle=45, color=’grey’, space_color=’white’)sp.add_to(sample_map2)folium.features.GeoJson(name=”Click for earnings NaN values”,data=gdf_nans, style_function=lambda x :{‘fillPattern’: sp},show=True).add_to(sample_map2)"
},
{
"code": null,
"e": 11364,
"s": 11304,
"text": "nans = final_df[final_df[“wills”].isnull()][‘state’].values"
},
{
"code": null,
"e": 11414,
"s": 11364,
"text": "gdf_nans = final_df[final_df[‘state’].isin(nans)]"
},
{
"code": null,
"e": 11478,
"s": 11414,
"text": "sp = StripePattern(angle=45, color=’grey’, space_color=’white’)"
},
{
"code": null,
"e": 11501,
"s": 11478,
"text": "sp.add_to(sample_map2)"
},
{
"code": null,
"e": 11653,
"s": 11501,
"text": "folium.features.GeoJson(name=”Click for earnings NaN values”,data=gdf_nans, style_function=lambda x :{‘fillPattern’: sp},show=True).add_to(sample_map2)"
},
{
"code": null,
"e": 12094,
"s": 11653,
"text": "In number 1, we grab the states inside the wills column that have null values. In number 2, I am extracting the rows where the state is equal to the states that are inside the nans variable from number 1. In numbers 3 and 4, I set up the pattern that I would like to show for the NaN values. Lastly, in number 5, I add the NaN layer with the sp variable as the fillPattern. Note I am also adding the layer controller in the second last row."
},
{
"code": null,
"e": 12345,
"s": 12094,
"text": "The last topic that I will go over is the hover functionality. Suppose you want to hover over the states and display some data. In order to add this functionality, we will again use the folium. features.GeoJson() function as we did in the code above."
},
{
"code": null,
"e": 13207,
"s": 12345,
"text": "# Add hover functionality.style_function = lambda x: {'fillColor': '#ffffff', 'color':'#000000', 'fillOpacity': 0.1, 'weight': 0.1}highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.50, 'weight': 0.1}NIL = folium.features.GeoJson( data = final_df, style_function=style_function, control=False, highlight_function=highlight_function, tooltip=folium.features.GeoJsonTooltip( fields=['state','wills'], aliases=['state','wills'], style=(\"background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;\") ))sample_map2.add_child(NIL)sample_map2.keep_in_front(NIL)sample_map2"
},
{
"code": null,
"e": 13403,
"s": 13207,
"text": "First, we create a style_function and a highlight_function to finalize how we want our hover function to appear. Next, at the NIL variable, we need to pay attention to the right parameter values."
},
{
"code": null,
"e": 13447,
"s": 13403,
"text": "We set the data to the final_df data frame."
},
{
"code": null,
"e": 13526,
"s": 13447,
"text": "We set the style function to the style_function we created on the second line."
},
{
"code": null,
"e": 13595,
"s": 13526,
"text": "We set the highlight function to the highlight_function from line 6."
},
{
"code": null,
"e": 13785,
"s": 13595,
"text": "We use the GeoJsonTooltip function and set the fields and aliases parameters to the column names in our final_df data frame to display the desired data points when we hover over the states."
},
{
"code": null,
"e": 14041,
"s": 13785,
"text": "See the final code all together below. I have also added the light and dark mode option, to the layer controller at the bottom of the code. I am using the cartodbdark_matter layer for the light mode, and for the dark mode, I use the cartodbpositron layer."
},
{
"code": null,
"e": 16046,
"s": 14041,
"text": "# We create another map called sample_map2.sample_map2 = folium.Map(location=[48, -102], zoom_start=4)# Set up Choropleth mapfolium.Choropleth(geo_data=final_df,data=final_df,columns=['state',\"wills\"],key_on=\"feature.properties.state\",fill_color='YlGnBu',fill_opacity=1,line_opacity=0.2,legend_name=\"wills\",smooth_factor=0,Highlight= True,line_color = \"#0000\",name = \"Wills\",show=True,overlay=True,nan_fill_color = \"White\").add_to(sample_map2)# Add hover functionality.style_function = lambda x: {'fillColor': '#ffffff', 'color':'#000000', 'fillOpacity': 0.1, 'weight': 0.1}highlight_function = lambda x: {'fillColor': '#000000', 'color':'#000000', 'fillOpacity': 0.50, 'weight': 0.1}NIL = folium.features.GeoJson( data = final_df, style_function=style_function, control=False, highlight_function=highlight_function, tooltip=folium.features.GeoJsonTooltip( fields=['state','wills'], aliases=['state','wills'], style=(\"background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;\") ))sample_map2.add_child(NIL)sample_map2.keep_in_front(NIL)# Here we add cross-hatching (crossing lines) to display the Null values.nans = final_df[final_df[\"wills\"].isnull()]['state'].valuesgdf_nans = final_df[final_df['state'].isin(nans)]sp = StripePattern(angle=45, color='grey', space_color='white')sp.add_to(sample_map2)folium.features.GeoJson(name=\"Click for Wills NaN values\",data=gdf_nans, style_function=lambda x :{'fillPattern': sp},show=True).add_to(sample_map2)# Add dark and light mode. folium.TileLayer('cartodbdark_matter',name=\"dark mode\",control=True).add_to(sample_map2)folium.TileLayer('cartodbpositron',name=\"light mode\",control=True).add_to(sample_map2)# We add a layer controller. folium.LayerControl(collapsed=False).add_to(sample_map2)sample_map2"
},
{
"code": null,
"e": 16146,
"s": 16046,
"text": "Finally, let us go over the steps that we went over in this tutorial and summarize what we learned:"
},
{
"code": null,
"e": 16321,
"s": 16146,
"text": "We used NumPy, Pandas, and GeoPandas to clean the data and created a final data frame by merging the geoJSON data and our sample data to create a Choropleth map using folium."
},
{
"code": null,
"e": 16363,
"s": 16321,
"text": "We learned how to add a draggable legend."
},
{
"code": null,
"e": 16450,
"s": 16363,
"text": "We also learned how to add cross-hatching (crossing lines) to display the null values."
},
{
"code": null,
"e": 16508,
"s": 16450,
"text": "Last but not least, we went over the hover functionality."
}
] |
Clojure - Strings
|
A String literal is constructed in Clojure by enclosing the string text in quotations. Strings in Clojure need to be constructed using the double quotation marks such as “Hello World”.
Following is an example of the usage of strings in Clojure.
(ns clojure.examples.hello
(:gen-class))
(defn hello-world []
(println "Hello World")
(println "This is a demo application"))
(hello-world)
The above program produces the following output.
Hello World
This is a demo application
Clojure has a number of operations that can be performed on strings. Following are the operations.
The concatenation of strings can be done by the simple str function.
The formatting of strings can be done by the simple format function. The format function formats a string using java.lang.String.format.
Returns the number of characters in the string.
Returns the substring of ‘s’ beginning at start inclusive, and ending at end (defaults to length of string), exclusive.
Returns a negative number, zero, or a positive number when ‘x’ is logically 'less than', 'equal to', or 'greater than' ‘y’.
Converts string to all lower-case.
Converts string to all upper-case.
Returns a string of all elements in collection, as returned by (seq collection), separated by an optional separator.
Splits string on a regular expression.
Split strings is based on the escape characters \n or \r\n.
Reverses the characters in a string.
Replaces all instance of a match in a string with the replacement string.
Removes whitespace from both ends of the string.
Removes whitespace from the left hand side of the string.
Removes whitespace from the right hand side of the string.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2559,
"s": 2374,
"text": "A String literal is constructed in Clojure by enclosing the string text in quotations. Strings in Clojure need to be constructed using the double quotation marks such as “Hello World”."
},
{
"code": null,
"e": 2619,
"s": 2559,
"text": "Following is an example of the usage of strings in Clojure."
},
{
"code": null,
"e": 2768,
"s": 2619,
"text": "(ns clojure.examples.hello\n (:gen-class))\n(defn hello-world []\n (println \"Hello World\")\n (println \"This is a demo application\"))\n(hello-world)"
},
{
"code": null,
"e": 2817,
"s": 2768,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 2857,
"s": 2817,
"text": "Hello World\nThis is a demo application\n"
},
{
"code": null,
"e": 2956,
"s": 2857,
"text": "Clojure has a number of operations that can be performed on strings. Following are the operations."
},
{
"code": null,
"e": 3025,
"s": 2956,
"text": "The concatenation of strings can be done by the simple str function."
},
{
"code": null,
"e": 3162,
"s": 3025,
"text": "The formatting of strings can be done by the simple format function. The format function formats a string using java.lang.String.format."
},
{
"code": null,
"e": 3210,
"s": 3162,
"text": "Returns the number of characters in the string."
},
{
"code": null,
"e": 3330,
"s": 3210,
"text": "Returns the substring of ‘s’ beginning at start inclusive, and ending at end (defaults to length of string), exclusive."
},
{
"code": null,
"e": 3454,
"s": 3330,
"text": "Returns a negative number, zero, or a positive number when ‘x’ is logically 'less than', 'equal to', or 'greater than' ‘y’."
},
{
"code": null,
"e": 3489,
"s": 3454,
"text": "Converts string to all lower-case."
},
{
"code": null,
"e": 3524,
"s": 3489,
"text": "Converts string to all upper-case."
},
{
"code": null,
"e": 3641,
"s": 3524,
"text": "Returns a string of all elements in collection, as returned by (seq collection), separated by an optional separator."
},
{
"code": null,
"e": 3680,
"s": 3641,
"text": "Splits string on a regular expression."
},
{
"code": null,
"e": 3740,
"s": 3680,
"text": "Split strings is based on the escape characters \\n or \\r\\n."
},
{
"code": null,
"e": 3777,
"s": 3740,
"text": "Reverses the characters in a string."
},
{
"code": null,
"e": 3851,
"s": 3777,
"text": "Replaces all instance of a match in a string with the replacement string."
},
{
"code": null,
"e": 3900,
"s": 3851,
"text": "Removes whitespace from both ends of the string."
},
{
"code": null,
"e": 3958,
"s": 3900,
"text": "Removes whitespace from the left hand side of the string."
},
{
"code": null,
"e": 4017,
"s": 3958,
"text": "Removes whitespace from the right hand side of the string."
},
{
"code": null,
"e": 4024,
"s": 4017,
"text": " Print"
},
{
"code": null,
"e": 4035,
"s": 4024,
"text": " Add Notes"
}
] |
How to play background music in Android app?
|
This example demonstrates how do I play background music in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">
<Button
android:onClick="PlayBackgroundSound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Run background Sound"/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:text="Playing Music in Background"/>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void PlayBackgroundSound(View view) {
Intent intent = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(intent);
}
}
Step 4 − Create a raw Android resource file, copy-paste an audio file which you want to play in the background (audio.mp3)
Step 5 − Create a new java class (BackgroundSoundService.java and the following code −
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Playing Bohemian Rashpody in the Background", Toast.LENGTH_SHORT).show();
return startId;
}
public void onStart(Intent intent, int startId) {
}
@Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
@Override
public void onLowMemory() {
}
}
Step 6 − Add the following code to androidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".BackgroundSoundService" />
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "This example demonstrates how do I play background music in android."
},
{
"code": null,
"e": 1260,
"s": 1131,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1325,
"s": 1260,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2064,
"s": 1325,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center_horizontal\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\">\n <Button\n android:onClick=\"PlayBackgroundSound\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Run background Sound\"/>\n <TextView\n android:layout_marginTop=\"20dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:text=\"Playing Music in Background\"/>\n</LinearLayout>"
},
{
"code": null,
"e": 2121,
"s": 2064,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2635,
"s": 2121,
"text": "import android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport androidx.appcompat.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void PlayBackgroundSound(View view) {\n Intent intent = new Intent(MainActivity.this, BackgroundSoundService.class);\n startService(intent);\n }\n}"
},
{
"code": null,
"e": 2758,
"s": 2635,
"text": "Step 4 − Create a raw Android resource file, copy-paste an audio file which you want to play in the background (audio.mp3)"
},
{
"code": null,
"e": 2845,
"s": 2758,
"text": "Step 5 − Create a new java class (BackgroundSoundService.java and the following code −"
},
{
"code": null,
"e": 3883,
"s": 2845,
"text": "import android.app.Service;\nimport android.content.Intent;\nimport android.media.MediaPlayer;\nimport android.os.IBinder;\nimport android.widget.Toast;\nimport androidx.annotation.Nullable;\npublic class BackgroundSoundService extends Service {\n MediaPlayer mediaPlayer;\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @Override\n public void onCreate() {\n super.onCreate();\n mediaPlayer = MediaPlayer.create(this, R.raw.sound);\n mediaPlayer.setLooping(true); // Set looping\n mediaPlayer.setVolume(100, 100);\n }\n public int onStartCommand(Intent intent, int flags, int startId) {\n mediaPlayer.start();\n Toast.makeText(getApplicationContext(), \"Playing Bohemian Rashpody in the Background\", Toast.LENGTH_SHORT).show();\n return startId;\n }\n public void onStart(Intent intent, int startId) {\n }\n @Override\n public void onDestroy() {\n mediaPlayer.stop();\n mediaPlayer.release();\n }\n @Override\n public void onLowMemory() {\n }\n}"
},
{
"code": null,
"e": 3938,
"s": 3883,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4629,
"s": 3938,
"text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name=\".BackgroundSoundService\" />\n </application>\n</manifest>"
},
{
"code": null,
"e": 4983,
"s": 4629,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
ReactJS - Building & Deployment
|
Let us learn how to do production build and deployment of React application in this chapter.
Once a React application development is done, application needs to be bundled and deployed to a production server. Let us learn the command available to build and deploy the application in this chapter.
A single command is enough to create a production build of the application.
npm run build
> expense-manager@0.1.0 build path\to\expense-manager
> react-scripts build
Creating an optimized production build...
Compiled with warnings.
File sizes after gzip:
41.69 KB build\static\js\2.a164da11.chunk.js
2.24 KB build\static\js\main.de70a883.chunk.js
1.4 KB build\static\js\3.d8a9fc85.chunk.js
1.17 KB build\static\js\runtime-main.560bee6e.js
493 B build\static\css\main.e75e7bbe.chunk.css
The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.
The build folder is ready to be deployed.
You may serve it with a static server:
npm install -g serve
serve -s build
Find out more about deployment here:
https://cra.link/deployment
Once the application is build, the application is available under build/static folder.
By default, profiling option is disable and can be enabled through –profile command line option. –profile will include profiling information in the code. The profiling information can be used along with React DevTools to analyse the application.
npm run build -- --profile
Once the application is build, it can be deployed to any web server. Let us learn how to deploy a React application in this chapter.
Local deployment can be done using serve package. Let us first install serve package using below command −
npm install -g server
To start the application using serve, use the below command −
cd /go/to/app/root/folder
serve -s build
By default, serve serve the application using port 5000. The application can be viewed @ http://localhost:5000.
Production deployment can be easily done by copying the files under build/static folder to the production application’s root directory. It will work in all web server including Apache, IIS, Nginx, etc.
By default, the production build is created assuming that the application will be hosted in the root folder of a web application. If the application needs to be hosted in a subfolder, then use below configuration in the package.json and then build the application.
{ ... "homepage": "http://domainname.com/path/to/subfolder", ... }
20 Lectures
1.5 hours
Anadi Sharma
60 Lectures
4.5 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
63 Lectures
9.5 hours
TELCOMA Global
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2126,
"s": 2033,
"text": "Let us learn how to do production build and deployment of React application in this chapter."
},
{
"code": null,
"e": 2329,
"s": 2126,
"text": "Once a React application development is done, application needs to be bundled and deployed to a production server. Let us learn the command available to build and deploy the application in this chapter."
},
{
"code": null,
"e": 2405,
"s": 2329,
"text": "A single command is enough to create a production build of the application."
},
{
"code": null,
"e": 3164,
"s": 2405,
"text": "npm run build\n> expense-manager@0.1.0 build path\\to\\expense-manager\n> react-scripts build\n\nCreating an optimized production build...\nCompiled with warnings.\n\nFile sizes after gzip:\n\n 41.69 KB build\\static\\js\\2.a164da11.chunk.js\n 2.24 KB build\\static\\js\\main.de70a883.chunk.js\n 1.4 KB build\\static\\js\\3.d8a9fc85.chunk.js\n 1.17 KB build\\static\\js\\runtime-main.560bee6e.js\n 493 B build\\static\\css\\main.e75e7bbe.chunk.css\n\nThe project was built assuming it is hosted at /.\nYou can control this with the homepage field in your package.json.\n\nThe build folder is ready to be deployed.\nYou may serve it with a static server:\n\n npm install -g serve\n serve -s build\n\nFind out more about deployment here:\n\n https://cra.link/deployment\n"
},
{
"code": null,
"e": 3251,
"s": 3164,
"text": "Once the application is build, the application is available under build/static folder."
},
{
"code": null,
"e": 3497,
"s": 3251,
"text": "By default, profiling option is disable and can be enabled through –profile command line option. –profile will include profiling information in the code. The profiling information can be used along with React DevTools to analyse the application."
},
{
"code": null,
"e": 3525,
"s": 3497,
"text": "npm run build -- --profile\n"
},
{
"code": null,
"e": 3658,
"s": 3525,
"text": "Once the application is build, it can be deployed to any web server. Let us learn how to deploy a React application in this chapter."
},
{
"code": null,
"e": 3765,
"s": 3658,
"text": "Local deployment can be done using serve package. Let us first install serve package using below command −"
},
{
"code": null,
"e": 3788,
"s": 3765,
"text": "npm install -g server\n"
},
{
"code": null,
"e": 3850,
"s": 3788,
"text": "To start the application using serve, use the below command −"
},
{
"code": null,
"e": 3893,
"s": 3850,
"text": "cd /go/to/app/root/folder \nserve -s build\n"
},
{
"code": null,
"e": 4005,
"s": 3893,
"text": "By default, serve serve the application using port 5000. The application can be viewed @ http://localhost:5000."
},
{
"code": null,
"e": 4207,
"s": 4005,
"text": "Production deployment can be easily done by copying the files under build/static folder to the production application’s root directory. It will work in all web server including Apache, IIS, Nginx, etc."
},
{
"code": null,
"e": 4472,
"s": 4207,
"text": "By default, the production build is created assuming that the application will be hosted in the root folder of a web application. If the application needs to be hosted in a subfolder, then use below configuration in the package.json and then build the application."
},
{
"code": null,
"e": 4540,
"s": 4472,
"text": "{ ... \"homepage\": \"http://domainname.com/path/to/subfolder\", ... }\n"
},
{
"code": null,
"e": 4575,
"s": 4540,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4589,
"s": 4575,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4624,
"s": 4589,
"text": "\n 60 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4644,
"s": 4624,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4679,
"s": 4644,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4702,
"s": 4679,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 4737,
"s": 4702,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4753,
"s": 4737,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4786,
"s": 4753,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4804,
"s": 4786,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 4811,
"s": 4804,
"text": " Print"
},
{
"code": null,
"e": 4822,
"s": 4811,
"text": " Add Notes"
}
] |
How to find the action attribute and method of a form in JavaScript?
|
Action attribute and method are not inbuilt in a form, they have to be specified in a form externally. Javascript has provided document.action and document.method methods to get the action attribute and method of a form respectively. Let's discuss them individually.
In the following example, the action attribute of the form is found out using document.action attribute and displayed the result in the output.
Live Demo
<html>
<body>
<form id="frm1" action="/online_javascript_editor.php" method="get"></form>
<p id="demo"></p>
<script>
var act = document.getElementById("frm1").action;
document.getElementById("demo").innerHTML = act;
</script>
</body>
</html>
https://www.tutorialspoint.com/online_javascript_editor.php
In the following example, the method of the form is found out using document.method attribute and displayed the result in the output.
Live Demo
<html>
<body>
<form id="frm1" action="/online_javascript_editor.php" method="get"></form>
<p id="demo"></p>
<script>
var met = document.getElementById("frm1").method;
document.getElementById("demo").innerHTML = met;
</script>
</body>
</html>
get
|
[
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Action attribute and method are not inbuilt in a form, they have to be specified in a form externally. Javascript has provided document.action and document.method methods to get the action attribute and method of a form respectively. Let's discuss them individually."
},
{
"code": null,
"e": 1473,
"s": 1329,
"text": "In the following example, the action attribute of the form is found out using document.action attribute and displayed the result in the output."
},
{
"code": null,
"e": 1483,
"s": 1473,
"text": "Live Demo"
},
{
"code": null,
"e": 1731,
"s": 1483,
"text": "<html>\n<body>\n<form id=\"frm1\" action=\"/online_javascript_editor.php\" method=\"get\"></form>\n<p id=\"demo\"></p>\n<script>\n var act = document.getElementById(\"frm1\").action;\n document.getElementById(\"demo\").innerHTML = act;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1791,
"s": 1731,
"text": "https://www.tutorialspoint.com/online_javascript_editor.php"
},
{
"code": null,
"e": 1925,
"s": 1791,
"text": "In the following example, the method of the form is found out using document.method attribute and displayed the result in the output."
},
{
"code": null,
"e": 1935,
"s": 1925,
"text": "Live Demo"
},
{
"code": null,
"e": 2183,
"s": 1935,
"text": "<html>\n<body>\n<form id=\"frm1\" action=\"/online_javascript_editor.php\" method=\"get\"></form>\n<p id=\"demo\"></p>\n<script>\n var met = document.getElementById(\"frm1\").method;\n document.getElementById(\"demo\").innerHTML = met;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2187,
"s": 2183,
"text": "get"
}
] |
Java Examples - Read a file
|
How to read a file ?
This example shows how to read a file using readLine method of BufferedReader class.
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("c:\\filename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
System.out.println(str);
} catch (IOException e) {
}
}
}
The above code sample will produce the following result.
aString
The following is another sample example of read a file in Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(
new FileReader("C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\bbc.txt"))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The above code sample will produce the following result.
BUILD SUCCESSFUL
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2089,
"s": 2068,
"text": "How to read a file ?"
},
{
"code": null,
"e": 2175,
"s": 2089,
"text": "This example shows how to read a file using readLine method of BufferedReader class. "
},
{
"code": null,
"e": 2561,
"s": 2175,
"text": "import java.io.*;\n\npublic class Main {\n public static void main(String[] args) {\n try {\n BufferedReader in = new BufferedReader(new FileReader(\"c:\\\\filename\"));\n String str;\n \n while ((str = in.readLine()) != null) {\n System.out.println(str);\n }\n System.out.println(str);\n } catch (IOException e) {\n }\n }\n}"
},
{
"code": null,
"e": 2618,
"s": 2561,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2627,
"s": 2618,
"text": "aString\n"
},
{
"code": null,
"e": 2690,
"s": 2627,
"text": "The following is another sample example of read a file in Java"
},
{
"code": null,
"e": 3216,
"s": 2690,
"text": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\n\npublic class BufferedReaderExample {\n public static void main(String[] args) {\n try (BufferedReader br = new BufferedReader(\n new FileReader(\"C:\\\\\\\\Users\\\\\\\\TutorialsPoint7\\\\\\\\Desktop\\\\\\\\bbc.txt\"))) { \n \n String sCurrentLine;\n while ((sCurrentLine = br.readLine()) != null) {\n\t\t\t\tSystem.out.println(sCurrentLine);\n\t\t\t} \n } catch (IOException e) {\n e.printStackTrace();\n } \n }\n} "
},
{
"code": null,
"e": 3273,
"s": 3216,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3292,
"s": 3273,
"text": "BUILD SUCCESSFUL \n"
},
{
"code": null,
"e": 3299,
"s": 3292,
"text": " Print"
},
{
"code": null,
"e": 3310,
"s": 3299,
"text": " Add Notes"
}
] |
Understand Data Normalization in Machine Learning | by Zixuan Zhang | Towards Data Science
|
If you’re new to data science/machine learning, you probably wondered a lot about the nature and effect of the buzzword ‘feature normalization’. If you’ve read any Kaggle kernels, it is very likely that you found feature normalization in the data preprocessing section. So, what is data normalization and why the heck is it so valued by data practitioners?
There are different types of data normalization. Assume you have a dataset X, which has N rows(entries) and D columns(features). X[:,i] represent feature i and X[j,:] represent entry j. We have:
Z Normalization(Standardization):
I used to falsely think this method somehow yields a standard Gaussian result. In fact, standardization does not change the type of distribution:
This transformation sets the mean of data to 0 and the standard deviation to 1. In most cases, standardization is used feature-wise
Min-Max Normalization:
This method rescales the range of the data to [0,1]. In most cases, standardization is used feature-wise as well
Unit Vector Normalization:
Scaling to unit length shrinks/stretches a vector (a row of data can be viewed as a D-dimensional vector) to a unit sphere. When used on the entire dataset, the transformed data can be visualized as a bunch of vectors with different directions on the D-dimensional unit sphere.
Wow, normalization is indeed a broad term and each of them has pros and cons! I ’ll only focus on standardization in this article otherwise this article will go way too long.
In theory, regression is insensitive to standardization since any linear transformation of input data can be counteracted by adjusting model parameters. Let’s say we have a linear model with parameters W and B:
Column-wise change can be achieved by subtracting a matrix M and multiplying with a diagonal matrix T
It’s easy to show that we can counteract this transformation by adjusting W and B
Therefore, standardization of input data should not affect the output or accuracy. Well, if the math says standardization plays little role in regression, why is it still so popular?
a). Standardization improves the numerical stability of your model
If we have a simple one-dimensional data X and use MSE as the loss function, the gradient update using gradient descend is:
X is in the gradient descent formula, which means the value of X determines the update rate. Therefore, a larger X will lead to a greater leap in the gradient landscape. Meanwhile, a larger X leads to smaller W, given Y:
When X is large, the distance between the initial W (which is randomly picked) and the global minimum is very likely to be small. Therefore, the algorithm is more likely to fail when X is larger (learning rate is fixed) because the algorithm makes giant leaps toward the very close target W while baby steps are needed. This overshooting will make your loss oscillate or explode.
Experiment:
I artificially created a dataset using the following code:
X = np.arange(-5,5,0.1)w = 0.5b = 0.2Y = X*w+b+(np.random.rand(X.shape[0],)-0.5)#add some noise to YX.reshape(100,1)Y.reshape(100,1)
A simple linear regression code I used for the experiment:
class linear_regression: def fit(self, X,Y, lr=0.00001): epoch = 0 loss_log = [] while (epoch<8000): pred = self.predict(X) l = self.loss(pred,Y)# get loss loss_log.append(l) delta_w = 2*np.matmul((Y-pred).T, X) # gradient of w delta_b = sum(2*(Y-pred)) self.w = self.w + lr*delta_w self.b = self.b + lr*delta_b epoch = epoch+1 plt.plot(loss_log) plt.ylim([0.07,0.1]) print (loss_log[-5:-1]) def loss(self, pred,Y): error = Y-pred return sum(error**2)/error.shape[0] # MSE def predict(self, X): return X*self.w+self.b# n by 1 def __init__(self):# initial parameters self.w=0.5# fixed initialization for comparison convenience self.b=0.5
The following table shows the final MSE with respect to different learning rate and feature range.
When X has a larger coefficient(therefore large range), the model needs a smaller learning rate to keep stability.
b). Standardization may speed up the training process
A corollary to the first ‘theorem’ is that if different features have drastically different ranges, the learning rate is determined by the feature with the largest range. This leads to another advantage of standardization: speeds up the training process.
Let’s say we have two features:
The learning rate determined by X2 isn’t ‘great’ for X1 since X1 is okay with much larger learning rate. We are taking baby steps while giant leaps could have been used instead, which leads to longer training time. We can reduce the training time by standardizing these two features.
Experiment:
I artificially created a dataset with two features using the following code:
X1 = np.arange(-5,5,0.1)X2 = np.arange(-5,5,0.1)X = np.column_stack((X1,X2))W = np.array([[0.1],[0.2]])b = 0.1Y = np.matmul(X,W)+b+(np.random.rand(X.shape[0],1) -0.5)# add some noise to labels
With slightly modified linear regression code:
class linear_regression: def fit(self, X,Y, lr=1e-4): epoch = 0 loss_log = [] while (epoch<80000): pred = self.predict(X) l = self.loss(pred,Y)# get loss loss_log.append(l) if l < 0.0792: print (epoch) break delta_w = 2*np.matmul((Y-pred).T, X) # gradient of w delta_b = sum(2*(Y-pred)) self.w = self.w + lr*delta_w.T self.b = self.b + lr*delta_b epoch = epoch+1 plt.plot(loss_log) plt.ylim([0.07,0.1]) print (loss_log[-5:-1]) def loss(self, pred,Y): error = Y-pred return sum(error**2)/error.shape[0] # MSE def predict(self, X): return np.matmul(X,self.w)+self.b# n by 1 def __init__(self): self.w=np.array([[0.5],[0.5]])# for comparison convenience self.b=0.3
The following table shows the number of iterations needed to reach the global minimum for a given coefficient and learning rate:
We can see that when the data isn’t standardized, the model needs to take more iterations (training time) to complete.
Distance-based clustering algorithms such as K-mean and K-NN are very likely to be affected by standardization. Clustering algorithm needs to calculate distances between entries. The most common distance used is the Euclidean distance:
It is obvious that feature scaling will change the numeric distances between nodes.
Experiment:
Create a dataset using the following code:
def random_2D_data(x,y,size): x = (np.random.randn(size)/3.5)+x y = (np.random.randn(size)*3.5)+y return x,yx1,y1 = random_2D_data(2,20,50)x2,y2 = random_2D_data(2,-20,50)x3,y3 = random_2D_data(-2,20,50)x4,y4 = random_2D_data(-2,-20,50)x = np.concatenate((x1,x2,x3,x4))y = np.concatenate((y1,y2,y3,y4))
Cluster the data as is using K-mean:
However, doing the same thing on the standardized data yields a totally different result:
Great, we have results contradict to each other. Which result should I pick?
Standardization gives ‘equal’ considerations for each feature.
For instance, X has two feature x1 and x2
If you calculate the Euclidean distance directly, node 1 and 2 will be further apart than node 1 and 3. However, node 3 is totally different from 1 while node 2 and 1 are only different in feature 1 (6%) and the share the same feature 2. This is because feature 1 is the ‘VIP’ feature, dominating the result with its large numerical value.
Therefore, if we don’t know which features are ‘diamond’ features and which are ‘coral’ features, it is a good practice to consider them equally using standardization.
Tree-based decision algorithms like decision trees or random forests seek for the best split point in each feature. The split point is determined by the percentage of labels correctly classified using a feature, which is resilient to feature scaling. Therefore, standardization doesn’t have any significant impact on this type of ML models.
Neural networks can counteract standardization in the same way as regressions. Therefore, in theory, data standardization should not affect the performance of a neural network. However, empirical evidence shows that data standardization is beneficial in terms of accuracy [1]. Currently, I don’t yet see the reason but maybe it’s related to gradient descending.
It is easy to understand why standardization improves training time. Large input values saturate activation functions such as sigmoid or ReLu(negative input). These types of activation functions feedback small or no gradient at all in the saturated region and therefore slows down training.
Standardization is beneficial in many cases. It improves the numerical stability of the model and often reduces training time. However, standardization isn’t always great. It can harm the performance of distance-based clustering algorithms by assuming equal importance of features. If there are inherent importance differences between features, it’s generally not a good idea to do standardization.
Reference:
[1]: Shanker M, Hu MY, Hung MS, Effect of Data Standardization on Neural Network Training, https://www.sciencedirect.com/science/article/pii/0305048396000102
|
[
{
"code": null,
"e": 404,
"s": 47,
"text": "If you’re new to data science/machine learning, you probably wondered a lot about the nature and effect of the buzzword ‘feature normalization’. If you’ve read any Kaggle kernels, it is very likely that you found feature normalization in the data preprocessing section. So, what is data normalization and why the heck is it so valued by data practitioners?"
},
{
"code": null,
"e": 599,
"s": 404,
"text": "There are different types of data normalization. Assume you have a dataset X, which has N rows(entries) and D columns(features). X[:,i] represent feature i and X[j,:] represent entry j. We have:"
},
{
"code": null,
"e": 633,
"s": 599,
"text": "Z Normalization(Standardization):"
},
{
"code": null,
"e": 779,
"s": 633,
"text": "I used to falsely think this method somehow yields a standard Gaussian result. In fact, standardization does not change the type of distribution:"
},
{
"code": null,
"e": 911,
"s": 779,
"text": "This transformation sets the mean of data to 0 and the standard deviation to 1. In most cases, standardization is used feature-wise"
},
{
"code": null,
"e": 934,
"s": 911,
"text": "Min-Max Normalization:"
},
{
"code": null,
"e": 1047,
"s": 934,
"text": "This method rescales the range of the data to [0,1]. In most cases, standardization is used feature-wise as well"
},
{
"code": null,
"e": 1074,
"s": 1047,
"text": "Unit Vector Normalization:"
},
{
"code": null,
"e": 1352,
"s": 1074,
"text": "Scaling to unit length shrinks/stretches a vector (a row of data can be viewed as a D-dimensional vector) to a unit sphere. When used on the entire dataset, the transformed data can be visualized as a bunch of vectors with different directions on the D-dimensional unit sphere."
},
{
"code": null,
"e": 1527,
"s": 1352,
"text": "Wow, normalization is indeed a broad term and each of them has pros and cons! I ’ll only focus on standardization in this article otherwise this article will go way too long."
},
{
"code": null,
"e": 1738,
"s": 1527,
"text": "In theory, regression is insensitive to standardization since any linear transformation of input data can be counteracted by adjusting model parameters. Let’s say we have a linear model with parameters W and B:"
},
{
"code": null,
"e": 1840,
"s": 1738,
"text": "Column-wise change can be achieved by subtracting a matrix M and multiplying with a diagonal matrix T"
},
{
"code": null,
"e": 1922,
"s": 1840,
"text": "It’s easy to show that we can counteract this transformation by adjusting W and B"
},
{
"code": null,
"e": 2105,
"s": 1922,
"text": "Therefore, standardization of input data should not affect the output or accuracy. Well, if the math says standardization plays little role in regression, why is it still so popular?"
},
{
"code": null,
"e": 2172,
"s": 2105,
"text": "a). Standardization improves the numerical stability of your model"
},
{
"code": null,
"e": 2296,
"s": 2172,
"text": "If we have a simple one-dimensional data X and use MSE as the loss function, the gradient update using gradient descend is:"
},
{
"code": null,
"e": 2517,
"s": 2296,
"text": "X is in the gradient descent formula, which means the value of X determines the update rate. Therefore, a larger X will lead to a greater leap in the gradient landscape. Meanwhile, a larger X leads to smaller W, given Y:"
},
{
"code": null,
"e": 2897,
"s": 2517,
"text": "When X is large, the distance between the initial W (which is randomly picked) and the global minimum is very likely to be small. Therefore, the algorithm is more likely to fail when X is larger (learning rate is fixed) because the algorithm makes giant leaps toward the very close target W while baby steps are needed. This overshooting will make your loss oscillate or explode."
},
{
"code": null,
"e": 2909,
"s": 2897,
"text": "Experiment:"
},
{
"code": null,
"e": 2968,
"s": 2909,
"text": "I artificially created a dataset using the following code:"
},
{
"code": null,
"e": 3101,
"s": 2968,
"text": "X = np.arange(-5,5,0.1)w = 0.5b = 0.2Y = X*w+b+(np.random.rand(X.shape[0],)-0.5)#add some noise to YX.reshape(100,1)Y.reshape(100,1)"
},
{
"code": null,
"e": 3160,
"s": 3101,
"text": "A simple linear regression code I used for the experiment:"
},
{
"code": null,
"e": 3974,
"s": 3160,
"text": "class linear_regression: def fit(self, X,Y, lr=0.00001): epoch = 0 loss_log = [] while (epoch<8000): pred = self.predict(X) l = self.loss(pred,Y)# get loss loss_log.append(l) delta_w = 2*np.matmul((Y-pred).T, X) # gradient of w delta_b = sum(2*(Y-pred)) self.w = self.w + lr*delta_w self.b = self.b + lr*delta_b epoch = epoch+1 plt.plot(loss_log) plt.ylim([0.07,0.1]) print (loss_log[-5:-1]) def loss(self, pred,Y): error = Y-pred return sum(error**2)/error.shape[0] # MSE def predict(self, X): return X*self.w+self.b# n by 1 def __init__(self):# initial parameters self.w=0.5# fixed initialization for comparison convenience self.b=0.5"
},
{
"code": null,
"e": 4073,
"s": 3974,
"text": "The following table shows the final MSE with respect to different learning rate and feature range."
},
{
"code": null,
"e": 4188,
"s": 4073,
"text": "When X has a larger coefficient(therefore large range), the model needs a smaller learning rate to keep stability."
},
{
"code": null,
"e": 4242,
"s": 4188,
"text": "b). Standardization may speed up the training process"
},
{
"code": null,
"e": 4497,
"s": 4242,
"text": "A corollary to the first ‘theorem’ is that if different features have drastically different ranges, the learning rate is determined by the feature with the largest range. This leads to another advantage of standardization: speeds up the training process."
},
{
"code": null,
"e": 4529,
"s": 4497,
"text": "Let’s say we have two features:"
},
{
"code": null,
"e": 4813,
"s": 4529,
"text": "The learning rate determined by X2 isn’t ‘great’ for X1 since X1 is okay with much larger learning rate. We are taking baby steps while giant leaps could have been used instead, which leads to longer training time. We can reduce the training time by standardizing these two features."
},
{
"code": null,
"e": 4825,
"s": 4813,
"text": "Experiment:"
},
{
"code": null,
"e": 4902,
"s": 4825,
"text": "I artificially created a dataset with two features using the following code:"
},
{
"code": null,
"e": 5095,
"s": 4902,
"text": "X1 = np.arange(-5,5,0.1)X2 = np.arange(-5,5,0.1)X = np.column_stack((X1,X2))W = np.array([[0.1],[0.2]])b = 0.1Y = np.matmul(X,W)+b+(np.random.rand(X.shape[0],1) -0.5)# add some noise to labels"
},
{
"code": null,
"e": 5142,
"s": 5095,
"text": "With slightly modified linear regression code:"
},
{
"code": null,
"e": 6022,
"s": 5142,
"text": "class linear_regression: def fit(self, X,Y, lr=1e-4): epoch = 0 loss_log = [] while (epoch<80000): pred = self.predict(X) l = self.loss(pred,Y)# get loss loss_log.append(l) if l < 0.0792: print (epoch) break delta_w = 2*np.matmul((Y-pred).T, X) # gradient of w delta_b = sum(2*(Y-pred)) self.w = self.w + lr*delta_w.T self.b = self.b + lr*delta_b epoch = epoch+1 plt.plot(loss_log) plt.ylim([0.07,0.1]) print (loss_log[-5:-1]) def loss(self, pred,Y): error = Y-pred return sum(error**2)/error.shape[0] # MSE def predict(self, X): return np.matmul(X,self.w)+self.b# n by 1 def __init__(self): self.w=np.array([[0.5],[0.5]])# for comparison convenience self.b=0.3"
},
{
"code": null,
"e": 6151,
"s": 6022,
"text": "The following table shows the number of iterations needed to reach the global minimum for a given coefficient and learning rate:"
},
{
"code": null,
"e": 6270,
"s": 6151,
"text": "We can see that when the data isn’t standardized, the model needs to take more iterations (training time) to complete."
},
{
"code": null,
"e": 6506,
"s": 6270,
"text": "Distance-based clustering algorithms such as K-mean and K-NN are very likely to be affected by standardization. Clustering algorithm needs to calculate distances between entries. The most common distance used is the Euclidean distance:"
},
{
"code": null,
"e": 6590,
"s": 6506,
"text": "It is obvious that feature scaling will change the numeric distances between nodes."
},
{
"code": null,
"e": 6602,
"s": 6590,
"text": "Experiment:"
},
{
"code": null,
"e": 6645,
"s": 6602,
"text": "Create a dataset using the following code:"
},
{
"code": null,
"e": 6957,
"s": 6645,
"text": "def random_2D_data(x,y,size): x = (np.random.randn(size)/3.5)+x y = (np.random.randn(size)*3.5)+y return x,yx1,y1 = random_2D_data(2,20,50)x2,y2 = random_2D_data(2,-20,50)x3,y3 = random_2D_data(-2,20,50)x4,y4 = random_2D_data(-2,-20,50)x = np.concatenate((x1,x2,x3,x4))y = np.concatenate((y1,y2,y3,y4))"
},
{
"code": null,
"e": 6994,
"s": 6957,
"text": "Cluster the data as is using K-mean:"
},
{
"code": null,
"e": 7084,
"s": 6994,
"text": "However, doing the same thing on the standardized data yields a totally different result:"
},
{
"code": null,
"e": 7161,
"s": 7084,
"text": "Great, we have results contradict to each other. Which result should I pick?"
},
{
"code": null,
"e": 7224,
"s": 7161,
"text": "Standardization gives ‘equal’ considerations for each feature."
},
{
"code": null,
"e": 7266,
"s": 7224,
"text": "For instance, X has two feature x1 and x2"
},
{
"code": null,
"e": 7606,
"s": 7266,
"text": "If you calculate the Euclidean distance directly, node 1 and 2 will be further apart than node 1 and 3. However, node 3 is totally different from 1 while node 2 and 1 are only different in feature 1 (6%) and the share the same feature 2. This is because feature 1 is the ‘VIP’ feature, dominating the result with its large numerical value."
},
{
"code": null,
"e": 7774,
"s": 7606,
"text": "Therefore, if we don’t know which features are ‘diamond’ features and which are ‘coral’ features, it is a good practice to consider them equally using standardization."
},
{
"code": null,
"e": 8115,
"s": 7774,
"text": "Tree-based decision algorithms like decision trees or random forests seek for the best split point in each feature. The split point is determined by the percentage of labels correctly classified using a feature, which is resilient to feature scaling. Therefore, standardization doesn’t have any significant impact on this type of ML models."
},
{
"code": null,
"e": 8477,
"s": 8115,
"text": "Neural networks can counteract standardization in the same way as regressions. Therefore, in theory, data standardization should not affect the performance of a neural network. However, empirical evidence shows that data standardization is beneficial in terms of accuracy [1]. Currently, I don’t yet see the reason but maybe it’s related to gradient descending."
},
{
"code": null,
"e": 8768,
"s": 8477,
"text": "It is easy to understand why standardization improves training time. Large input values saturate activation functions such as sigmoid or ReLu(negative input). These types of activation functions feedback small or no gradient at all in the saturated region and therefore slows down training."
},
{
"code": null,
"e": 9167,
"s": 8768,
"text": "Standardization is beneficial in many cases. It improves the numerical stability of the model and often reduces training time. However, standardization isn’t always great. It can harm the performance of distance-based clustering algorithms by assuming equal importance of features. If there are inherent importance differences between features, it’s generally not a good idea to do standardization."
},
{
"code": null,
"e": 9178,
"s": 9167,
"text": "Reference:"
}
] |
JasperReports - Crosstabs
|
Crosstab (cross-tabulation) reports are the reports containing tables that arrange data across rows and columns in a tabular form. Crosstab object is used for inserting a crosstab report within the main report. Crosstabs can be used with any level of data (nominal, ordinal, interval, or ratio), and usually display the summarized data, contained in the report variables, in the form of a dynamic table. Variables are used to display aggregate data such as sums, counts, average values.
JRXML element <crosstab> is used to insert a crosstab into a report.
Following is a list of attribute of a <crosstab> element −
isRepeatColumnHeaders − Indicates whether the column headers should be reprinted after a page break. The default value is true.
isRepeatColumnHeaders − Indicates whether the column headers should be reprinted after a page break. The default value is true.
isRepeatRowHeaders − Indicates whether the row headers should be reprinted after a crosstab column break. The default value is true.
isRepeatRowHeaders − Indicates whether the row headers should be reprinted after a crosstab column break. The default value is true.
columnBreakOffset − When a column break occurs, indicates the amount of vertical space, measured in pixels, before the subsequent crosstab piece to be placed below the previous one on the same page. The default value is 10.
columnBreakOffset − When a column break occurs, indicates the amount of vertical space, measured in pixels, before the subsequent crosstab piece to be placed below the previous one on the same page. The default value is 10.
runDirection − Indicates whether the crosstab data should be filled from left to right (LTR) or from right to left (RTL). The default value is LTR.
runDirection − Indicates whether the crosstab data should be filled from left to right (LTR) or from right to left (RTL). The default value is LTR.
ignoreWidth − Indicates whether the crosstab will stretch beyond the initial crosstab width limit and don't generate column breaks. Else it will stop rendering columns within the crosstab width limit and continue with the remaining columns only after all rows have started rendering. The default value is false.
ignoreWidth − Indicates whether the crosstab will stretch beyond the initial crosstab width limit and don't generate column breaks. Else it will stop rendering columns within the crosstab width limit and continue with the remaining columns only after all rows have started rendering. The default value is false.
A <crosstab> element has following sub elements −
<reportElement> − This element defines the position, width, and height of the crosstab within its enclosing. Attributes for this element include all standard <reportElement> attributes.
<reportElement> − This element defines the position, width, and height of the crosstab within its enclosing. Attributes for this element include all standard <reportElement> attributes.
<crosstabParameter> − This element is used to access report variables and parameters from within the crosstab. Attributes for this element include −
name − This defines the parameter name.
class − This indicates the parameter class.
<crosstabParameter> − This element is used to access report variables and parameters from within the crosstab. Attributes for this element include −
name − This defines the parameter name.
name − This defines the parameter name.
class − This indicates the parameter class.
class − This indicates the parameter class.
<parametersMapExpression> − This element is used to pass a report variable or parameter containing an instance of java.util.Map, as a set of parameters for the crosstab. This element contains
no attributes.
<parametersMapExpression> − This element is used to pass a report variable or parameter containing an instance of java.util.Map, as a set of parameters for the crosstab. This element contains
no attributes.
<crosstabDataset> − This element defines the dataset to use to populate the crosstab (see next section for a detailed explanation). Attributes for this element include −
isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false.
<crosstabDataset> − This element defines the dataset to use to populate the crosstab (see next section for a detailed explanation). Attributes for this element include −
isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false.
isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false.
<crosstabHeaderCell> − This element defines the content of the region found at the upper-left corner of the crosstab where column headers and row headers meet. The size of this cell is calculated automatically based on the defined row and column widths and heights.
<crosstabHeaderCell> − This element defines the content of the region found at the upper-left corner of the crosstab where column headers and row headers meet. The size of this cell is calculated automatically based on the defined row and column widths and heights.
<rowGroup> − This element defines a group used to split the data into rows. Attributes for this element include −
name − This defines the name of the row group.
width − This defines the width of the row group.
headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch).
totalPosition − This defines the position of the entire column (Start, End, None).
This element contains the following sub elements −
<bucket>
<crosstabRowHeader>
<crosstabTotalRowHeader>
<rowGroup> − This element defines a group used to split the data into rows. Attributes for this element include −
name − This defines the name of the row group.
name − This defines the name of the row group.
width − This defines the width of the row group.
width − This defines the width of the row group.
headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch).
headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch).
totalPosition − This defines the position of the entire column (Start, End, None).
totalPosition − This defines the position of the entire column (Start, End, None).
This element contains the following sub elements −
<bucket>
<bucket>
<crosstabRowHeader>
<crosstabRowHeader>
<crosstabTotalRowHeader>
<crosstabTotalRowHeader>
<columnGroup> − This element defines a group used to split the data into columns. Attributes for this element include −
name − This defines the column group name.
height − This defines the height of the column group header.
headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch).
totalPosition − This defines the position of the entire column (Start, End, None).
This element contains the following sub elements −
<bucket>
<crosstabColumnHeader>
<crosstabTotalColumnHeader>
<columnGroup> − This element defines a group used to split the data into columns. Attributes for this element include −
name − This defines the column group name.
name − This defines the column group name.
height − This defines the height of the column group header.
height − This defines the height of the column group header.
headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch).
headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch).
totalPosition − This defines the position of the entire column (Start, End, None).
totalPosition − This defines the position of the entire column (Start, End, None).
This element contains the following sub elements −
<bucket>
<bucket>
<crosstabColumnHeader>
<crosstabColumnHeader>
<crosstabTotalColumnHeader>
<crosstabTotalColumnHeader>
<measure> − This element defines the calculation to be performed across rows and columns. Attributes for this element include −
name − This defines the measure name.
class − This indicates the measure class.
calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing.
<measure> − This element defines the calculation to be performed across rows and columns. Attributes for this element include −
name − This defines the measure name.
name − This defines the measure name.
class − This indicates the measure class.
class − This indicates the measure class.
calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing.
calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing.
<crosstabCell> − This element defines how data in non-header cells will be laid out. Attributes for this element include −
columnTotalGroup − This indicates the group to use to calculate the column total.
height − This defines the height of the cell.
rowTotalGroup − This indicates the group to use to calculate the row total.
width − This defines the width of the cell.
<crosstabCell> − This element defines how data in non-header cells will be laid out. Attributes for this element include −
columnTotalGroup − This indicates the group to use to calculate the column total.
columnTotalGroup − This indicates the group to use to calculate the column total.
height − This defines the height of the cell.
height − This defines the height of the cell.
rowTotalGroup − This indicates the group to use to calculate the row total.
rowTotalGroup − This indicates the group to use to calculate the row total.
width − This defines the width of the cell.
width − This defines the width of the cell.
<whenNoDataCell> − This element defines what to display on an empty crosstab cell. This element contains no attributes.
<whenNoDataCell> − This element defines what to display on an empty crosstab cell. This element contains no attributes.
The crosstab calculation engine aggregates data by iterating through the associated dataset records. In order to aggregate data, one needs to group them first. In a crosstab, rows and columns are based on specific group items, called buckets. A bucket definition should contain −
bucketExpression − The expression to be evaluated in order to obtain data group items.
bucketExpression − The expression to be evaluated in order to obtain data group items.
comparatorExpression − Needed in the case the natural ordering of the values is not the best choice.
comparatorExpression − Needed in the case the natural ordering of the values is not the best choice.
orderByExpression − Indicates the value used to sort data.
orderByExpression − Indicates the value used to sort data.
Row and column groups (defined above) in a crosstab rely on buckets.
Below is a list of current value of measure and totals of different levels corresponding to the cell can be accessed through variables named according to the following scheme −
The current value of a measure calculation is stored in a variable having the same name as the measure.
The current value of a measure calculation is stored in a variable having the same name as the measure.
<Measure>_<Column Group>_ALL − This yields the total for all the entries in the column group from the same row.
<Measure>_<Column Group>_ALL − This yields the total for all the entries in the column group from the same row.
<Measure>_<Row Group>_ALL − This yields the total for all the entries in the row group from the same column.
<Measure>_<Row Group>_ALL − This yields the total for all the entries in the row group from the same column.
<Measure>_<Row Group>_<Column Group>_ALL − This yields the combined total corresponding to all the entries in both row and column groups.
<Measure>_<Row Group>_<Column Group>_ALL − This yields the combined total corresponding to all the entries in both row and column groups.
To demonstrate the crosstabs, let's write a new report template (jasper_report_template.jrxml). Here, we will add the crosstab to summary section. Save it to the directory C:\tools\jasperreports-5.0.1\test. The contents of the file are as given below −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" language = "groovy" pageWidth = "595"
pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
topMargin = "20" bottomMargin = "20">
<parameter name = "ReportTitle" class = "java.lang.String"/>
<parameter name = "Author" class = "java.lang.String"/>
<field name = "name" class = "java.lang.String"/>
<field name = "country" class = "java.lang.String"/>
<title>
<band height = "70">
<line>
<reportElement x = "0" y = "0" width = "515" height = "1"/>
</line>
<textField isBlankWhenNull = "true" bookmarkLevel = "1">
<reportElement x = "0" y = "10" width = "515" height = "30"/>
<textElement textAlignment = "Center">
<font size = "22"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{ReportTitle}]]>
</textFieldExpression>
<anchorNameExpression>
<![CDATA["Title"]]>
</anchorNameExpression>
</textField>
<textField isBlankWhenNull = "true">
<reportElement x = "0" y = "40" width = "515" height = "20"/>
<textElement textAlignment = "Center">
<font size = "10"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$P{Author}]]>
</textFieldExpression>
</textField>
</band>
</title>
<summary>
<band height = "60">
<crosstab>
<reportElement width = "782" y = "0" x = "0" height = "60"/>
<rowGroup name = "nameGroup" width = "100">
<bucket>
<bucketExpression class = "java.lang.String">
<![CDATA[$F{name}]]>
</bucketExpression>
</bucket>
<crosstabRowHeader>
<cellContents>
<box border = "Thin" borderColor = "black"/>
<textField>
<reportElement width = "100" y = "0" x = "0" height = "20"/>
<textElement textAlignment = "Right"
verticalAlignment = "Middle"/>
<textFieldExpression>
<![CDATA[$V{nameGroup}]]>
</textFieldExpression>
</textField>
</cellContents>
</crosstabRowHeader>
</rowGroup>
<columnGroup name = "countryGroup" height = "20">
<bucket>
<bucketExpression class = "java.lang.String">
$F{country}
</bucketExpression>
</bucket>
<crosstabColumnHeader>
<cellContents>
<box border = "Thin" borderColor = "black"/>
<textField isStretchWithOverflow = "true">
<reportElement width = "60" y = "0" x = "0" height = "20"/>
<textElement verticalAlignment = "Bottom"/>
<textFieldExpression>
<![CDATA[$V{countryGroup}]]>
</textFieldExpression>
</textField>
</cellContents>
</crosstabColumnHeader>
</columnGroup>
<measure name = "tailNumCount" class = "java.lang.Integer"
calculation = "Count">
<measureExpression>$F{country}</measureExpression>
</measure>
<crosstabCell height = "20" width = "60">
<cellContents backcolor = "#FFFFFF">
<box borderColor = "black" border = "Thin"/>
<textField>
<reportElement x = "5" y = "0" width = "55" height = "20"/>
<textElement textAlignment = "Left"
verticalAlignment = "Bottom"/>
<textFieldExpression class = "java.lang.Integer">
$V{tailNumCount}
</textFieldExpression>
</textField>
</cellContents>
</crosstabCell>
</crosstab>
</band>
</summary>
</jasperReport>
The details of the above file are as follows −
Crosstab is defined by the <crosstab> element.
Crosstab is defined by the <crosstab> element.
<rowGroup> element defines a group to split the data into rows. Here, each row will display data for a different name.
<rowGroup> element defines a group to split the data into rows. Here, each row will display data for a different name.
The <bucket> and <bucketExpression> elements define what report expression to use as a group delimiter for <rowGroup>. Here, we used the name field as a delimiter, in order to split the rows by name.
The <bucket> and <bucketExpression> elements define what report expression to use as a group delimiter for <rowGroup>. Here, we used the name field as a delimiter, in order to split the rows by name.
The <crosstabRowHeader> element defines the expression to be used as a row header. It contains a single sub-element, namely <cellContents>, which acts like an inner band inside crosstab. Instead of defining variable name for the text field inside <crosstabRowHeader>, we have assigned the name to <rowGroup> (via its name attribute), hence it creates an implicit variable. The <crosstabRowHeader> element defines the contents of the header cell for the entire row. It takes a single <cellContents> element as its only sub-element.
The <crosstabRowHeader> element defines the expression to be used as a row header. It contains a single sub-element, namely <cellContents>, which acts like an inner band inside crosstab. Instead of defining variable name for the text field inside <crosstabRowHeader>, we have assigned the name to <rowGroup> (via its name attribute), hence it creates an implicit variable. The <crosstabRowHeader> element defines the contents of the header cell for the entire row. It takes a single <cellContents> element as its only sub-element.
The <columnGroup> element as well as its sub-elements is analogous to the <rowGroup> element, except that it influences columns instead of rows.
The <columnGroup> element as well as its sub-elements is analogous to the <rowGroup> element, except that it influences columns instead of rows.
The <measure> element defines the calculation to be performed across rows and columns. The calculation attribute is set to Count.
The <measure> element defines the calculation to be performed across rows and columns. The calculation attribute is set to Count.
The <crosstabCell> element defines how data in non-header cells will be laid out. This element also contains a single <crosstabCell> element as its only sub-element.
The <crosstabCell> element defines how data in non-header cells will be laid out. This element also contains a single <crosstabCell> element as its only sub-element.
The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class JasperReportFill {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String sourceFileName =
"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";
DataBeanList DataBeanList = new DataBeanList();
ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource =
new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
/**
* Passing ReportTitle and Author as parameters
*/
parameters.put("ReportTitle", "List of Contacts");
parameters.put("Author", "Prepared By Manisha");
try {
JasperFillManager.fillReportToFile(
sourceFileName, parameters, beanColDataSource);
} catch (JRException e) {
e.printStackTrace();
}
}
}
The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as follows −
package com.tutorialspoint;
public class DataBean {
private String name;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as follows −
package com.tutorialspoint;
import java.util.ArrayList;
public class DataBeanList {
public ArrayList<DataBean> getDataBeanList() {
ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();
dataBeanList.add(produce("Manisha", "India"));
dataBeanList.add(produce("Dennis Ritchie", "USA"));
dataBeanList.add(produce("V.Anand", "India"));
dataBeanList.add(produce("Shrinath", "California"));
return dataBeanList;
}
/**
* This method returns a DataBean object,
* with name and country set in it.
*/
private DataBean produce(String name, String country) {
DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setCountry(country);
return dataBean;
}
}
Next, let's compile and execute the above files using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.
The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewFillReport" depends = "compile,compilereportdesing,run"
description = "Launches the report viewer to preview the
report stored in the .JRprint file.">
<java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
<arg value = "-F${file.name}.JRprint" />
<classpath refid = "classpath" />
</java>
</target>
<target name = "compilereportdesing" description = "Compiles the JXML file and
produces the .jasper file.">
<taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −
C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
clean-sample:
[delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
[delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper
compile:
[mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
warning: 'includeantruntime' was not set, defaulting to
[javac] Compiling 3 source files to C:\tools\jasperreports-5.0.1\test\classes
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
for more info.
[jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK.
run:
[echo] Runnin class : com.tutorialspoint.JasperReportFill
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
viewFillReport:
[java] log4j:WARN No appenders could be found for logger (
net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
BUILD SUCCESSFUL
Total time: 20 minutes 53 seconds
As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −
Here, we see that each country and name are tabulated.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2742,
"s": 2254,
"text": "Crosstab (cross-tabulation) reports are the reports containing tables that arrange data across rows and columns in a tabular form. Crosstab object is used for inserting a crosstab report within the main report. Crosstabs can be used with any level of data (nominal, ordinal, interval, or ratio), and usually display the summarized data, contained in the report variables, in the form of a dynamic table. Variables are used to display aggregate data such as sums, counts, average values."
},
{
"code": null,
"e": 2811,
"s": 2742,
"text": "JRXML element <crosstab> is used to insert a crosstab into a report."
},
{
"code": null,
"e": 2870,
"s": 2811,
"text": "Following is a list of attribute of a <crosstab> element −"
},
{
"code": null,
"e": 2998,
"s": 2870,
"text": "isRepeatColumnHeaders − Indicates whether the column headers should be reprinted after a page break. The default value is true."
},
{
"code": null,
"e": 3126,
"s": 2998,
"text": "isRepeatColumnHeaders − Indicates whether the column headers should be reprinted after a page break. The default value is true."
},
{
"code": null,
"e": 3259,
"s": 3126,
"text": "isRepeatRowHeaders − Indicates whether the row headers should be reprinted after a crosstab column break. The default value is true."
},
{
"code": null,
"e": 3392,
"s": 3259,
"text": "isRepeatRowHeaders − Indicates whether the row headers should be reprinted after a crosstab column break. The default value is true."
},
{
"code": null,
"e": 3616,
"s": 3392,
"text": "columnBreakOffset − When a column break occurs, indicates the amount of vertical space, measured in pixels, before the subsequent crosstab piece to be placed below the previous one on the same page. The default value is 10."
},
{
"code": null,
"e": 3840,
"s": 3616,
"text": "columnBreakOffset − When a column break occurs, indicates the amount of vertical space, measured in pixels, before the subsequent crosstab piece to be placed below the previous one on the same page. The default value is 10."
},
{
"code": null,
"e": 3988,
"s": 3840,
"text": "runDirection − Indicates whether the crosstab data should be filled from left to right (LTR) or from right to left (RTL). The default value is LTR."
},
{
"code": null,
"e": 4136,
"s": 3988,
"text": "runDirection − Indicates whether the crosstab data should be filled from left to right (LTR) or from right to left (RTL). The default value is LTR."
},
{
"code": null,
"e": 4448,
"s": 4136,
"text": "ignoreWidth − Indicates whether the crosstab will stretch beyond the initial crosstab width limit and don't generate column breaks. Else it will stop rendering columns within the crosstab width limit and continue with the remaining columns only after all rows have started rendering. The default value is false."
},
{
"code": null,
"e": 4760,
"s": 4448,
"text": "ignoreWidth − Indicates whether the crosstab will stretch beyond the initial crosstab width limit and don't generate column breaks. Else it will stop rendering columns within the crosstab width limit and continue with the remaining columns only after all rows have started rendering. The default value is false."
},
{
"code": null,
"e": 4810,
"s": 4760,
"text": "A <crosstab> element has following sub elements −"
},
{
"code": null,
"e": 4996,
"s": 4810,
"text": "<reportElement> − This element defines the position, width, and height of the crosstab within its enclosing. Attributes for this element include all standard <reportElement> attributes."
},
{
"code": null,
"e": 5182,
"s": 4996,
"text": "<reportElement> − This element defines the position, width, and height of the crosstab within its enclosing. Attributes for this element include all standard <reportElement> attributes."
},
{
"code": null,
"e": 5418,
"s": 5182,
"text": "<crosstabParameter> − This element is used to access report variables and parameters from within the crosstab. Attributes for this element include −\n\nname − This defines the parameter name.\nclass − This indicates the parameter class.\n\n"
},
{
"code": null,
"e": 5567,
"s": 5418,
"text": "<crosstabParameter> − This element is used to access report variables and parameters from within the crosstab. Attributes for this element include −"
},
{
"code": null,
"e": 5607,
"s": 5567,
"text": "name − This defines the parameter name."
},
{
"code": null,
"e": 5647,
"s": 5607,
"text": "name − This defines the parameter name."
},
{
"code": null,
"e": 5691,
"s": 5647,
"text": "class − This indicates the parameter class."
},
{
"code": null,
"e": 5735,
"s": 5691,
"text": "class − This indicates the parameter class."
},
{
"code": null,
"e": 5942,
"s": 5735,
"text": "<parametersMapExpression> − This element is used to pass a report variable or parameter containing an instance of java.util.Map, as a set of parameters for the crosstab. This element contains\nno attributes."
},
{
"code": null,
"e": 6149,
"s": 5942,
"text": "<parametersMapExpression> − This element is used to pass a report variable or parameter containing an instance of java.util.Map, as a set of parameters for the crosstab. This element contains\nno attributes."
},
{
"code": null,
"e": 6426,
"s": 6149,
"text": "<crosstabDataset> − This element defines the dataset to use to populate the crosstab (see next section for a detailed explanation). Attributes for this element include −\n\nisDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false.\n\n"
},
{
"code": null,
"e": 6596,
"s": 6426,
"text": "<crosstabDataset> − This element defines the dataset to use to populate the crosstab (see next section for a detailed explanation). Attributes for this element include −"
},
{
"code": null,
"e": 6700,
"s": 6596,
"text": "isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false."
},
{
"code": null,
"e": 6804,
"s": 6700,
"text": "isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false."
},
{
"code": null,
"e": 7070,
"s": 6804,
"text": "<crosstabHeaderCell> − This element defines the content of the region found at the upper-left corner of the crosstab where column headers and row headers meet. The size of this cell is calculated automatically based on the defined row and column widths and heights."
},
{
"code": null,
"e": 7336,
"s": 7070,
"text": "<crosstabHeaderCell> − This element defines the content of the region found at the upper-left corner of the crosstab where column headers and row headers meet. The size of this cell is calculated automatically based on the defined row and column widths and heights."
},
{
"code": null,
"e": 7837,
"s": 7336,
"text": "<rowGroup> − This element defines a group used to split the data into rows. Attributes for this element include −\n\nname − This defines the name of the row group.\nwidth − This defines the width of the row group.\nheaderPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch).\ntotalPosition − This defines the position of the entire column (Start, End, None).\n\nThis element contains the following sub elements −\n\n<bucket>\n<crosstabRowHeader>\n<crosstabTotalRowHeader>\n\n"
},
{
"code": null,
"e": 7951,
"s": 7837,
"text": "<rowGroup> − This element defines a group used to split the data into rows. Attributes for this element include −"
},
{
"code": null,
"e": 7998,
"s": 7951,
"text": "name − This defines the name of the row group."
},
{
"code": null,
"e": 8045,
"s": 7998,
"text": "name − This defines the name of the row group."
},
{
"code": null,
"e": 8094,
"s": 8045,
"text": "width − This defines the width of the row group."
},
{
"code": null,
"e": 8143,
"s": 8094,
"text": "width − This defines the width of the row group."
},
{
"code": null,
"e": 8241,
"s": 8143,
"text": "headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch)."
},
{
"code": null,
"e": 8339,
"s": 8241,
"text": "headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch)."
},
{
"code": null,
"e": 8422,
"s": 8339,
"text": "totalPosition − This defines the position of the entire column (Start, End, None)."
},
{
"code": null,
"e": 8505,
"s": 8422,
"text": "totalPosition − This defines the position of the entire column (Start, End, None)."
},
{
"code": null,
"e": 8556,
"s": 8505,
"text": "This element contains the following sub elements −"
},
{
"code": null,
"e": 8565,
"s": 8556,
"text": "<bucket>"
},
{
"code": null,
"e": 8574,
"s": 8565,
"text": "<bucket>"
},
{
"code": null,
"e": 8594,
"s": 8574,
"text": "<crosstabRowHeader>"
},
{
"code": null,
"e": 8614,
"s": 8594,
"text": "<crosstabRowHeader>"
},
{
"code": null,
"e": 8639,
"s": 8614,
"text": "<crosstabTotalRowHeader>"
},
{
"code": null,
"e": 8664,
"s": 8639,
"text": "<crosstabTotalRowHeader>"
},
{
"code": null,
"e": 9185,
"s": 8664,
"text": "<columnGroup> − This element defines a group used to split the data into columns. Attributes for this element include −\n\nname − This defines the column group name.\nheight − This defines the height of the column group header.\nheaderPosition − This defines the position of the header contents (Right, Left, Center, Stretch).\ntotalPosition − This defines the position of the entire column (Start, End, None).\n\nThis element contains the following sub elements −\n\n<bucket>\n<crosstabColumnHeader>\n<crosstabTotalColumnHeader>\n\n"
},
{
"code": null,
"e": 9305,
"s": 9185,
"text": "<columnGroup> − This element defines a group used to split the data into columns. Attributes for this element include −"
},
{
"code": null,
"e": 9348,
"s": 9305,
"text": "name − This defines the column group name."
},
{
"code": null,
"e": 9391,
"s": 9348,
"text": "name − This defines the column group name."
},
{
"code": null,
"e": 9452,
"s": 9391,
"text": "height − This defines the height of the column group header."
},
{
"code": null,
"e": 9513,
"s": 9452,
"text": "height − This defines the height of the column group header."
},
{
"code": null,
"e": 9611,
"s": 9513,
"text": "headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch)."
},
{
"code": null,
"e": 9709,
"s": 9611,
"text": "headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch)."
},
{
"code": null,
"e": 9792,
"s": 9709,
"text": "totalPosition − This defines the position of the entire column (Start, End, None)."
},
{
"code": null,
"e": 9875,
"s": 9792,
"text": "totalPosition − This defines the position of the entire column (Start, End, None)."
},
{
"code": null,
"e": 9926,
"s": 9875,
"text": "This element contains the following sub elements −"
},
{
"code": null,
"e": 9935,
"s": 9926,
"text": "<bucket>"
},
{
"code": null,
"e": 9944,
"s": 9935,
"text": "<bucket>"
},
{
"code": null,
"e": 9967,
"s": 9944,
"text": "<crosstabColumnHeader>"
},
{
"code": null,
"e": 9990,
"s": 9967,
"text": "<crosstabColumnHeader>"
},
{
"code": null,
"e": 10018,
"s": 9990,
"text": "<crosstabTotalColumnHeader>"
},
{
"code": null,
"e": 10046,
"s": 10018,
"text": "<crosstabTotalColumnHeader>"
},
{
"code": null,
"e": 10512,
"s": 10046,
"text": "<measure> − This element defines the calculation to be performed across rows and columns. Attributes for this element include −\n\nname − This defines the measure name.\nclass − This indicates the measure class.\ncalculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing.\n\n"
},
{
"code": null,
"e": 10640,
"s": 10512,
"text": "<measure> − This element defines the calculation to be performed across rows and columns. Attributes for this element include −"
},
{
"code": null,
"e": 10678,
"s": 10640,
"text": "name − This defines the measure name."
},
{
"code": null,
"e": 10716,
"s": 10678,
"text": "name − This defines the measure name."
},
{
"code": null,
"e": 10758,
"s": 10716,
"text": "class − This indicates the measure class."
},
{
"code": null,
"e": 10800,
"s": 10758,
"text": "class − This indicates the measure class."
},
{
"code": null,
"e": 11055,
"s": 10800,
"text": "calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing."
},
{
"code": null,
"e": 11310,
"s": 11055,
"text": "calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these - Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing."
},
{
"code": null,
"e": 11684,
"s": 11310,
"text": "<crosstabCell> − This element defines how data in non-header cells will be laid out. Attributes for this element include −\n\ncolumnTotalGroup − This indicates the group to use to calculate the column total.\nheight − This defines the height of the cell.\nrowTotalGroup − This indicates the group to use to calculate the row total.\nwidth − This defines the width of the cell.\n\n"
},
{
"code": null,
"e": 11807,
"s": 11684,
"text": "<crosstabCell> − This element defines how data in non-header cells will be laid out. Attributes for this element include −"
},
{
"code": null,
"e": 11889,
"s": 11807,
"text": "columnTotalGroup − This indicates the group to use to calculate the column total."
},
{
"code": null,
"e": 11971,
"s": 11889,
"text": "columnTotalGroup − This indicates the group to use to calculate the column total."
},
{
"code": null,
"e": 12017,
"s": 11971,
"text": "height − This defines the height of the cell."
},
{
"code": null,
"e": 12063,
"s": 12017,
"text": "height − This defines the height of the cell."
},
{
"code": null,
"e": 12139,
"s": 12063,
"text": "rowTotalGroup − This indicates the group to use to calculate the row total."
},
{
"code": null,
"e": 12215,
"s": 12139,
"text": "rowTotalGroup − This indicates the group to use to calculate the row total."
},
{
"code": null,
"e": 12259,
"s": 12215,
"text": "width − This defines the width of the cell."
},
{
"code": null,
"e": 12303,
"s": 12259,
"text": "width − This defines the width of the cell."
},
{
"code": null,
"e": 12423,
"s": 12303,
"text": "<whenNoDataCell> − This element defines what to display on an empty crosstab cell. This element contains no attributes."
},
{
"code": null,
"e": 12543,
"s": 12423,
"text": "<whenNoDataCell> − This element defines what to display on an empty crosstab cell. This element contains no attributes."
},
{
"code": null,
"e": 12823,
"s": 12543,
"text": "The crosstab calculation engine aggregates data by iterating through the associated dataset records. In order to aggregate data, one needs to group them first. In a crosstab, rows and columns are based on specific group items, called buckets. A bucket definition should contain −"
},
{
"code": null,
"e": 12910,
"s": 12823,
"text": "bucketExpression − The expression to be evaluated in order to obtain data group items."
},
{
"code": null,
"e": 12997,
"s": 12910,
"text": "bucketExpression − The expression to be evaluated in order to obtain data group items."
},
{
"code": null,
"e": 13098,
"s": 12997,
"text": "comparatorExpression − Needed in the case the natural ordering of the values is not the best choice."
},
{
"code": null,
"e": 13199,
"s": 13098,
"text": "comparatorExpression − Needed in the case the natural ordering of the values is not the best choice."
},
{
"code": null,
"e": 13258,
"s": 13199,
"text": "orderByExpression − Indicates the value used to sort data."
},
{
"code": null,
"e": 13317,
"s": 13258,
"text": "orderByExpression − Indicates the value used to sort data."
},
{
"code": null,
"e": 13386,
"s": 13317,
"text": "Row and column groups (defined above) in a crosstab rely on buckets."
},
{
"code": null,
"e": 13563,
"s": 13386,
"text": "Below is a list of current value of measure and totals of different levels corresponding to the cell can be accessed through variables named according to the following scheme −"
},
{
"code": null,
"e": 13667,
"s": 13563,
"text": "The current value of a measure calculation is stored in a variable having the same name as the measure."
},
{
"code": null,
"e": 13771,
"s": 13667,
"text": "The current value of a measure calculation is stored in a variable having the same name as the measure."
},
{
"code": null,
"e": 13883,
"s": 13771,
"text": "<Measure>_<Column Group>_ALL − This yields the total for all the entries in the column group from the same row."
},
{
"code": null,
"e": 13995,
"s": 13883,
"text": "<Measure>_<Column Group>_ALL − This yields the total for all the entries in the column group from the same row."
},
{
"code": null,
"e": 14104,
"s": 13995,
"text": "<Measure>_<Row Group>_ALL − This yields the total for all the entries in the row group from the same column."
},
{
"code": null,
"e": 14213,
"s": 14104,
"text": "<Measure>_<Row Group>_ALL − This yields the total for all the entries in the row group from the same column."
},
{
"code": null,
"e": 14351,
"s": 14213,
"text": "<Measure>_<Row Group>_<Column Group>_ALL − This yields the combined total corresponding to all the entries in both row and column groups."
},
{
"code": null,
"e": 14489,
"s": 14351,
"text": "<Measure>_<Row Group>_<Column Group>_ALL − This yields the combined total corresponding to all the entries in both row and column groups."
},
{
"code": null,
"e": 14742,
"s": 14489,
"text": "To demonstrate the crosstabs, let's write a new report template (jasper_report_template.jrxml). Here, we will add the crosstab to summary section. Save it to the directory C:\\tools\\jasperreports-5.0.1\\test. The contents of the file are as given below −"
},
{
"code": null,
"e": 19648,
"s": 14742,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE jasperReport PUBLIC \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\t\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" language = \"groovy\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"555\" leftMargin = \"20\" rightMargin = \"20\"\n topMargin = \"20\" bottomMargin = \"20\">\n\n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n \n <field name = \"name\" class = \"java.lang.String\"/>\n <field name = \"country\" class = \"java.lang.String\"/>\n \n <title>\n <band height = \"70\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n \n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </title>\n \n <summary>\n <band height = \"60\">\n \n <crosstab>\n <reportElement width = \"782\" y = \"0\" x = \"0\" height = \"60\"/>\n \n <rowGroup name = \"nameGroup\" width = \"100\">\n \n <bucket>\n <bucketExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </bucketExpression>\n </bucket>\n \n <crosstabRowHeader>\n \n <cellContents>\n <box border = \"Thin\" borderColor = \"black\"/>\n \n <textField>\n <reportElement width = \"100\" y = \"0\" x = \"0\" height = \"20\"/>\n <textElement textAlignment = \"Right\" \n verticalAlignment = \"Middle\"/>\n \n <textFieldExpression>\n <![CDATA[$V{nameGroup}]]>\n </textFieldExpression>\n </textField>\n \n </cellContents>\n \n </crosstabRowHeader>\n\n </rowGroup>\n \n <columnGroup name = \"countryGroup\" height = \"20\">\n <bucket>\n \n <bucketExpression class = \"java.lang.String\">\n $F{country}\n </bucketExpression>\n </bucket>\n \n <crosstabColumnHeader>\n <cellContents>\n <box border = \"Thin\" borderColor = \"black\"/>\n <textField isStretchWithOverflow = \"true\">\n <reportElement width = \"60\" y = \"0\" x = \"0\" height = \"20\"/>\n <textElement verticalAlignment = \"Bottom\"/>\n <textFieldExpression>\n <![CDATA[$V{countryGroup}]]>\n </textFieldExpression>\n </textField>\n </cellContents>\n </crosstabColumnHeader>\n\n </columnGroup>\n \n <measure name = \"tailNumCount\" class = \"java.lang.Integer\" \n calculation = \"Count\">\n <measureExpression>$F{country}</measureExpression>\n </measure>\n \n <crosstabCell height = \"20\" width = \"60\">\n <cellContents backcolor = \"#FFFFFF\">\n <box borderColor = \"black\" border = \"Thin\"/>\n <textField>\n <reportElement x = \"5\" y = \"0\" width = \"55\" height = \"20\"/>\n <textElement textAlignment = \"Left\" \n verticalAlignment = \"Bottom\"/>\n <textFieldExpression class = \"java.lang.Integer\">\n $V{tailNumCount}\n </textFieldExpression>\n </textField>\n </cellContents>\n </crosstabCell>\n \n </crosstab>\n \n </band>\n </summary>\n\t\n</jasperReport>"
},
{
"code": null,
"e": 19695,
"s": 19648,
"text": "The details of the above file are as follows −"
},
{
"code": null,
"e": 19742,
"s": 19695,
"text": "Crosstab is defined by the <crosstab> element."
},
{
"code": null,
"e": 19789,
"s": 19742,
"text": "Crosstab is defined by the <crosstab> element."
},
{
"code": null,
"e": 19908,
"s": 19789,
"text": "<rowGroup> element defines a group to split the data into rows. Here, each row will display data for a different name."
},
{
"code": null,
"e": 20027,
"s": 19908,
"text": "<rowGroup> element defines a group to split the data into rows. Here, each row will display data for a different name."
},
{
"code": null,
"e": 20227,
"s": 20027,
"text": "The <bucket> and <bucketExpression> elements define what report expression to use as a group delimiter for <rowGroup>. Here, we used the name field as a delimiter, in order to split the rows by name."
},
{
"code": null,
"e": 20427,
"s": 20227,
"text": "The <bucket> and <bucketExpression> elements define what report expression to use as a group delimiter for <rowGroup>. Here, we used the name field as a delimiter, in order to split the rows by name."
},
{
"code": null,
"e": 20958,
"s": 20427,
"text": "The <crosstabRowHeader> element defines the expression to be used as a row header. It contains a single sub-element, namely <cellContents>, which acts like an inner band inside crosstab. Instead of defining variable name for the text field inside <crosstabRowHeader>, we have assigned the name to <rowGroup> (via its name attribute), hence it creates an implicit variable. The <crosstabRowHeader> element defines the contents of the header cell for the entire row. It takes a single <cellContents> element as its only sub-element."
},
{
"code": null,
"e": 21489,
"s": 20958,
"text": "The <crosstabRowHeader> element defines the expression to be used as a row header. It contains a single sub-element, namely <cellContents>, which acts like an inner band inside crosstab. Instead of defining variable name for the text field inside <crosstabRowHeader>, we have assigned the name to <rowGroup> (via its name attribute), hence it creates an implicit variable. The <crosstabRowHeader> element defines the contents of the header cell for the entire row. It takes a single <cellContents> element as its only sub-element."
},
{
"code": null,
"e": 21634,
"s": 21489,
"text": "The <columnGroup> element as well as its sub-elements is analogous to the <rowGroup> element, except that it influences columns instead of rows."
},
{
"code": null,
"e": 21779,
"s": 21634,
"text": "The <columnGroup> element as well as its sub-elements is analogous to the <rowGroup> element, except that it influences columns instead of rows."
},
{
"code": null,
"e": 21909,
"s": 21779,
"text": "The <measure> element defines the calculation to be performed across rows and columns. The calculation attribute is set to Count."
},
{
"code": null,
"e": 22039,
"s": 21909,
"text": "The <measure> element defines the calculation to be performed across rows and columns. The calculation attribute is set to Count."
},
{
"code": null,
"e": 22205,
"s": 22039,
"text": "The <crosstabCell> element defines how data in non-header cells will be laid out. This element also contains a single <crosstabCell> element as its only sub-element."
},
{
"code": null,
"e": 22371,
"s": 22205,
"text": "The <crosstabCell> element defines how data in non-header cells will be laid out. This element also contains a single <crosstabCell> element as its only sub-element."
},
{
"code": null,
"e": 22549,
"s": 22371,
"text": "The java codes for report filling remains unchanged. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as given below −"
},
{
"code": null,
"e": 23687,
"s": 22549,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName = \n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource =\n new JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 23805,
"s": 23687,
"text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as follows −"
},
{
"code": null,
"e": 24173,
"s": 23805,
"text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}"
},
{
"code": null,
"e": 24290,
"s": 24173,
"text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as follows −"
},
{
"code": null,
"e": 25054,
"s": 24290,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}"
},
{
"code": null,
"e": 25252,
"s": 25054,
"text": "Next, let's compile and execute the above files using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below."
},
{
"code": null,
"e": 25393,
"s": 25252,
"text": "The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml."
},
{
"code": null,
"e": 26469,
"s": 25393,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview the \n report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n\t\t\n </target>\n\t\n</project>"
},
{
"code": null,
"e": 26691,
"s": 26469,
"text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −"
},
{
"code": null,
"e": 28230,
"s": 26691,
"text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28:\n warning: 'includeantruntime' was not set, defaulting to\n [javac] Compiling 3 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig \n for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger (\n net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 20 minutes 53 seconds\n"
},
{
"code": null,
"e": 28332,
"s": 28230,
"text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −"
},
{
"code": null,
"e": 28387,
"s": 28332,
"text": "Here, we see that each country and name are tabulated."
},
{
"code": null,
"e": 28394,
"s": 28387,
"text": " Print"
},
{
"code": null,
"e": 28405,
"s": 28394,
"text": " Add Notes"
}
] |
Analyzing Video Games Data in R. Being a gamer myself, I had a lot of... | by Hamza Rafiq | Towards Data Science
|
Being a gamer myself, I had a lot of fun analyzing this dataset. Actually, this dataset was made from merging two different datasets: Tidytuesday and Kaggle. Reason for using two datasets is because the Tidytuesday dataset didn't have enough information for an interesting analysis. That is why I merged the two to get more interesting data and insights out of it. This is also my first article in which I applied some machine learning using the Tidymodels meta-package.
Loading Librarieslibrary(tidyverse) ## For data wrangling and visualizationlibrary(lubridate) ## To work with dateslibrary(ggpubr) ## Extra visualizations and themeslibrary(patchwork) ## Patch visualizations togetherlibrary(hrbrthemes)## Extra themes and formattinglibrary(ggalt) ## Extra visualizationslibrary(vapoRwave) ## Retro themeslibrary(extrafont) ## Exta fontsLoading Datavideo_games <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-07-30/video_games.csv") %>% mutate(release_date = as.Date(release_date, "%b %d, %Y")) %>% distinct(game, developer, publisher, .keep_all = TRUE)metacritic_games <- read_csv("C:\\Users\\ACER\\Downloads\\metacritic-games-stats-20112019\\metacritic_games.csv",trim_ws = TRUE)Cleaning and mergin the datasets togethergames_final <- metacritic_games %>% filter(platform=="PS4") %>% inner_join(video_games,by = "game") %>% mutate(owners=parse_number(owners,trim_ws = TRUE)) %>% mutate(publisher = case_when(str_detect(publisher,pattern = "Warner Bros|WB")~"Warner Brothers",TRUE~publisher)) %>% select(-c(release_date.x,developer.y,number_players,number,metascore.y))
After the reading in the video_games data, I used the mutate function to convert the release_date column to date type
Since some games had multiple developers and genres, I used the distinct function to get a unique game per row
For this analysis, I am only interested in PS4 games. That is why I filtered the metacritic_games dataset to only PS4 games before doing an inner_join with the video_games dataset
Used the parse function to get the upper-range value from the owners column for each game as a numeric
Since there were multiple Warner Bros. publishers, I used the case_when function to lump them together as one
Lastly, I deselected the duplicate columns
After some investigation, I realized that there was too much junk in the data and to do an insightful analysis on a game level, I decided to only look at the top 50 publishers based on the total number of people who own their games
Calculating top 50 publisherstop_50_publishers <- games_final %>% group_by(publisher) %>% summarise(Owners=sum(owners)) %>% top_n(50)Filtering games_final based on top 50 publisherstop_50_filtered <- games_final %>% semi_join(top_50_publishers)
First, I group by publisher in the games_final dataset to get total owners for each publisher and then use the top_n function to get the top 50 publishers based on owners
Then I use the semi_join function between the games_final and the top_50_publishers datasets. What this does is that it filters out the games_final data based on the top 50 publishers that are in top_50_publishers
This dataset is a lot smaller than the original but it allows me to only look at mainstream games
Do note that this filtered data is only till 2018 in case you are wondering why aren't any of your favorite games which came out in 2019 like God of War, Spiderman or Red Dead Redemption 2 in this list
top_50_filtered %>% filter(!is.na(publisher)) %>% group_by(publisher) %>% summarise(owners=sum(owners)) %>% ggplot(aes(reorder(publisher,owners),owners))+ geom_bar(fill="#8B2E8B",stat = "identity",color="black")+ coord_flip()+ geom_text(aes(label=paste0(round(owners/1000000,digits = 1)," ","M")),color="white",fontface="bold",hjust=1)+ new_retro()+ scale_color_hotlineBling()+ labs(x=" ")+ scale_y_comma()+ theme(legend.position = "none",axis.text.y = element_text(colour = "white",family = "SF Alien Encounters"))
Started by removing NA publishers
Performed the same group by function to get total owners against each publisher
Used ggplot and geom_bar to make a standard barplot and used the coord_flip function to flip axes. Note the reorder function within ggplot allows to plot a sorted barplot from largest to lowest values
Since the owners variable is in millions, I divided it by a million and concatenated an “M” at the end using paste0 to label total owners for each publisher without messing the aesthetics
A lot of familiar faces in there like Ubisoft, Rockstar Games, etc but honestly I did not know about Digital Extremes — sitting at the top
They are actually responsible for a really popular online free-to-play, role-playing shooter called Warframe which came out in 2013
top_50_filtered %>% ggplot(aes(user_score,metascore.x))+ geom_point(color="green")+ geom_text(aes(label=game),check_overlap = TRUE,color="turquoise",size=3)+ vapoRwave::new_retro()+ scale_color_newRetro()+ labs(title = "Relationship between Userscore and Metascore",x="USERSCORE",y="METASCORE")
There is a general trend between User Score and Metascore. Games like The Witcher 3, GTA V, Rayman Legends and Rocket League scored high in both and deservedly so
The games that are encircled are the ones that were hyped but failed in meeting expectations. Although I am surprised that Shadow of War had such a low user score, that game was sick!
One game that caught my attention is Mad Max. It received lukewarm reviews from critics but the users liked it. I actually never played it because of the former but this might change my mind
top_50_filtered %>% top_n(30,user_score) %>% ggplot(aes(reorder(game,user_score),user_score))+ geom_lollipop(color="white")+ coord_flip()+ geom_text(aes(label=user_score),color="white",hjust=-1)+ new_retro()+ scale_y_continuous(limits = c(0,100))+ labs(x=" ",title = "Top 30 Games by User Score")
Used the top_n function to filter out the top 30 games based on user_score
reorder function within ggplot to sort the plot from largest value to lowest
geom_lollipop to make a lollipop chart
Not surprised to see The Witcher 3 at the top. The game was a masterpiece
Although I am surprised to see The Evil Within 2 at second place. It was a really good game but I didn't realize it would score so high, more than games like GTA V
So the sequel to Shadow of War, Middle Earth: Shadow of Mordor scored a lot better with the users. I personally liked the prequel better but both were good games
I am surprised to see Batman: Arkham Knight lower than expected. It is one of my all-time favorite games on the PS4 and the best in the Batman Arkham trilogy in my opinion. I think the low score could be attributed to people being annoyed by the batmobile mechanics and underwhelming boss fights
top_50_filtered %>% top_n(30,metascore.x) %>% ggplot(aes(reorder(game,metascore.x),metascore.x))+ geom_lollipop(color="light blue")+ coord_flip()+ geom_text(aes(label=metascore.x),color="light blue",hjust=-1)+ new_retro()+ scale_y_continuous(limits = c(0,100))+ labs(x=" ",y=" ",title = "Top 30 Games by Meta Score")
Same code as before. Just replaced user score with metascore
You can clearly see that a lot of the games have shifted when we move from user score to Metascore. Using the anti_join function we can see which games present in the top 30 games by user score were not in the top 30 games by meta score
top_50_filtered %>% top_n(30,user_score) %>% anti_join(top_50_filtered %>% top_n(30,metascore.x))
The anti_join function here automatically detects the common column between the two data frames — game and shows the top 30 user games that are not present in the top 30 games by metascore
Most of these games do not have a major difference between their user score and Metascore with the exception of Evil Within 2 and Mad Max
top_50_filtered %>% filter(!is.na(publisher)) %>% ggplot(aes(reorder(publisher,user_score,FUN = mean),user_score))+ geom_boxplot(color="purple")+ geom_hline(yintercept = 80,color="white")+ coord_flip()+ new_retro()+ labs(x=" ")
Plotting a boxplot to visualize the distribution of user score for the top 50 publishers
Used the reorder function to sort the boxplots by the average user score
Added a vertical line at 80 as a threshold for what is considered a great game
I can see why Ubisoft scores so low here. Their recent games in the Far Cry and Assassin’s Creed series have been pretty underwhelming
Rockstar never disappoints. Every game they make is a masterpiece
Activision is all over the place. Maybe people are finally getting tired of the Call of Duty series
Capcom is really low. This is probably due to releasing an incomplete Street Fighter V game and charging full price for it. But 2019 has been an amazing year for Capcom with games like Monster Hunter, Resident Evil 2: Remake and Devil May Cry 5 being huge hits for them
top_50_filtered %>% filter(!is.na(publisher)) %>% ggplot(aes(reorder(publisher,metascore.x,FUN = mean),metascore.x))+ geom_boxplot(color="green")+ geom_hline(yintercept = 80,color="white")+ coord_flip()+ new_retro()+ labs(x=" ",y="Metascore")
Seems like publishers do a lot better when it comes to Metascore compared to their user scores
top_50_filtered %>% top_n(30,average_playtime) %>% ggplot(aes(reorder(game,average_playtime/60),average_playtime/60))+ geom_lollipop(color="purple")+ coord_flip()+ geom_text(aes(label= round(average_playtime/60)),color="white",hjust=-1)+ vapoRwave::new_retro()+ scale_y_continuous(limits = c(0,40))+ labs(x=" ",y="Average playtime in 2 weeks - (hrs)")
The average playtime for each game measures how long did users play the game for two weeks on average in minutes
Used top_n function to only look at the top 30 longest games
when plotting, divided average_playtime by 60 to convert it into hrs
geom_text to label the average_playtime in hrs
Most of the top longest games are open-world like Just Cause 4, Far Cry 5, Mad Max, Assassin’s Creed, GTA V, and Witcher 3
Surprised to see Prey number 3. I didn't play it but I don't think it was open-world
top_50_filtered %>% mutate(percentage_positive_users=positive_users/(positive_users+negative_users+neutral_users), percentage_positive_critics =positive_critics/(positive_critics+negative_critics+neutral_critics)) %>% filter(positive_users>=10,percentage_positive_users>=0.5) %>% top_n(30,percentage_positive_users) %>% ggplot(aes(reorder(game,percentage_positive_users),percentage_positive_users))+ geom_lollipop(color="white")+ coord_flip()+ labs(x=" ")+ new_retro()
Used the mutate function to create two new columns: percentage_positive_users and percentage_positive_critics
Since there are some games who received very few total scores, I used the filter function to show only those who had at least 10 positive user scores and had an overall percentage of positive users ≥ 50%
Rest is the same code that we have used for previous lollipop charts
Wow! surprised to see GTA V so low
Mad Max and Dying Light are one of those games that were really good but went under the radar
Sword Art Online received horrendous reviews from the critics but looks like the users liked it
top_50_filtered %>% mutate(percentage_positive_users=positive_users/(positive_users+negative_users+neutral_users), percentage_positive_critics =positive_critics/(positive_critics+negative_critics+neutral_critics)) %>% filter(positive_critics>=10,percentage_positive_critics>=0.5) %>% top_n(30,percentage_positive_critics) %>% ggplot(aes(reorder(game,percentage_positive_critics),percentage_positive_critics))+ geom_lollipop(color="white")+ coord_flip()+ labs(x=" ")+ new_retro()
NBA 2k16 and NBA 2k17 received good reviews from the critics but low scores from the users
Honestly, I have not heard about the top 4 games but these aren't considered AAA games due to their small scale
Predicting the Metascore is not practical since it is calculated based on a formula of all the numerical variables provided in the dataset. Predicting user score is more interesting. For this, I will be using the Tidymodels meta-package. It is a collection of packages that allows you to create a seamless data pipeline from preprocessing your data, tuning your models, modeling your data , making predictions and measuring your model performance while adhering to the “tidy” principles of the Tidyverse
library(tidymodels)ratings_data <- top_50_filtered %>% mutate(percentage_positive_users=positive_users/(positive_users+negative_users+neutral_users), percentage_negative_users =negative_users/(positive_users+negative_users+neutral_users), percentage_positive_critics =positive_critics/(positive_critics+negative_critics+neutral_critics), percentage_negative_critics =negative_critics/(positive_critics+negative_critics+neutral_critics)) %>% drop_na()Splitting the datasplit <- initial_split(ratings_data,prop = 0.6,)train_games <- split %>% training() %>%test_games <- split %>% testing()
Used the mutate function to create new variables that will be used as predictors for user_score
Drop any missing values
Use the intial_split function from rsample library to create a split parameter for our train and test splits
Chain it with the training and testing functions from rsample to create our train and test datasets
Creating Recipenorm_recipe <- recipe(user_score~percentage_positive_critics+percentage_negative_critics+percentage_positive_users+ percentage_negative_users+price+genre+rating+publisher,data = train_games) %>% step_naomit(all_numeric(),all_nominal()) %>% step_dummy(all_nominal(),,one_hot = TRUE) %>% step_normalize(all_predictors(),na_rm = TRUE) %>% step_corr(all_predictors()) %>% prep()Applying Recipe on Train and Test setstrain_prepped <- juice(norm_recipe)test_prepped <- norm_recipe %>% bake(test_game)
Using the Recipes package, I am a creating a “recipe” which is basically a pipeline of how I want to process the variables in my data
we start with defining the relationship between the dependent and independent variables
The “step” functions are the data transforming functions
step_naomit removes missing values from both nominal and numeric variables
step_dummy does one-hot encoding on all the categorical variables
step_normalize normalizes all the numeric predictors
step_corr removes any independent variables that have a high correlation with each other
prep function basically finalizes and prepares the recipe
juice function, when applied on norm_recipe, gives us the transformed version of the training set
bake function chained together with norm_recipe and applied on the test data give us the transformed version
ranger <- rand_forest(trees = 100,mode = "regression") %>% set_engine("ranger") %>% fit(user_score~.,data=train_prepped)
For defining our model we use the Parsnip package to define a randomforest regression model
Set the engine to ranger
Use the fit function to define our formula and supplied the transformed training data
Converting NAs to 0test_prepped <- test_prepped %>% mutate_all(~replace(.,is.na(.),0))Making predictionsranger %>% predict(test_prepped) %>% bind_cols(test_games) %>% select(game,.pred,user_score)Measuring Model Accuracyranger %>% predict(test_prepped) %>% bind_cols(test_games) %>% metrics(truth=user_score,estimate=.pred)
Before applying predictions on the prepped test set, I had to convert some NAs to 0 otherwise the randomforest model will throw an error
Finally, we use the ranger model to predict on our prepped test set and joined the predictions with the original test data to see the predicted and actual user scores for each game
Once we have made predictions, I used the metrics function from the yardstick package to calculate the model's accuracy by supplying it both actual and predicted user scores
rsq measures how much the variation in our dependent variable — user_score can be explained by the independent variables in our dataset. In our case, it is not too bad considering the type of data we had and it was a very small dataset
It could be improved by hyperparameter tuning and cross-validation but that is beyond the scope of this article. Also, these features are still under development in Tidymodels as of now, there is no seamless to integrate them in our analysis
I had a lot of fun doing an end-to-end analysis on this data and being able to apply some basic machine learning using the Tidymodels package was good practice. Although, it is important to note to not draw any major conclusions from this data as we looked at a very small subset of our original data sources. I think this analysis could be made even more interesting if we gathered more data on all the different videogames.
|
[
{
"code": null,
"e": 642,
"s": 171,
"text": "Being a gamer myself, I had a lot of fun analyzing this dataset. Actually, this dataset was made from merging two different datasets: Tidytuesday and Kaggle. Reason for using two datasets is because the Tidytuesday dataset didn't have enough information for an interesting analysis. That is why I merged the two to get more interesting data and insights out of it. This is also my first article in which I applied some machine learning using the Tidymodels meta-package."
},
{
"code": null,
"e": 1810,
"s": 642,
"text": "Loading Librarieslibrary(tidyverse) ## For data wrangling and visualizationlibrary(lubridate) ## To work with dateslibrary(ggpubr) ## Extra visualizations and themeslibrary(patchwork) ## Patch visualizations togetherlibrary(hrbrthemes)## Extra themes and formattinglibrary(ggalt) ## Extra visualizationslibrary(vapoRwave) ## Retro themeslibrary(extrafont) ## Exta fontsLoading Datavideo_games <- read_csv(\"https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-07-30/video_games.csv\") %>% mutate(release_date = as.Date(release_date, \"%b %d, %Y\")) %>% distinct(game, developer, publisher, .keep_all = TRUE)metacritic_games <- read_csv(\"C:\\\\Users\\\\ACER\\\\Downloads\\\\metacritic-games-stats-20112019\\\\metacritic_games.csv\",trim_ws = TRUE)Cleaning and mergin the datasets togethergames_final <- metacritic_games %>% filter(platform==\"PS4\") %>% inner_join(video_games,by = \"game\") %>% mutate(owners=parse_number(owners,trim_ws = TRUE)) %>% mutate(publisher = case_when(str_detect(publisher,pattern = \"Warner Bros|WB\")~\"Warner Brothers\",TRUE~publisher)) %>% select(-c(release_date.x,developer.y,number_players,number,metascore.y))"
},
{
"code": null,
"e": 1928,
"s": 1810,
"text": "After the reading in the video_games data, I used the mutate function to convert the release_date column to date type"
},
{
"code": null,
"e": 2039,
"s": 1928,
"text": "Since some games had multiple developers and genres, I used the distinct function to get a unique game per row"
},
{
"code": null,
"e": 2219,
"s": 2039,
"text": "For this analysis, I am only interested in PS4 games. That is why I filtered the metacritic_games dataset to only PS4 games before doing an inner_join with the video_games dataset"
},
{
"code": null,
"e": 2322,
"s": 2219,
"text": "Used the parse function to get the upper-range value from the owners column for each game as a numeric"
},
{
"code": null,
"e": 2432,
"s": 2322,
"text": "Since there were multiple Warner Bros. publishers, I used the case_when function to lump them together as one"
},
{
"code": null,
"e": 2475,
"s": 2432,
"text": "Lastly, I deselected the duplicate columns"
},
{
"code": null,
"e": 2707,
"s": 2475,
"text": "After some investigation, I realized that there was too much junk in the data and to do an insightful analysis on a game level, I decided to only look at the top 50 publishers based on the total number of people who own their games"
},
{
"code": null,
"e": 2960,
"s": 2707,
"text": "Calculating top 50 publisherstop_50_publishers <- games_final %>% group_by(publisher) %>% summarise(Owners=sum(owners)) %>% top_n(50)Filtering games_final based on top 50 publisherstop_50_filtered <- games_final %>% semi_join(top_50_publishers)"
},
{
"code": null,
"e": 3131,
"s": 2960,
"text": "First, I group by publisher in the games_final dataset to get total owners for each publisher and then use the top_n function to get the top 50 publishers based on owners"
},
{
"code": null,
"e": 3345,
"s": 3131,
"text": "Then I use the semi_join function between the games_final and the top_50_publishers datasets. What this does is that it filters out the games_final data based on the top 50 publishers that are in top_50_publishers"
},
{
"code": null,
"e": 3443,
"s": 3345,
"text": "This dataset is a lot smaller than the original but it allows me to only look at mainstream games"
},
{
"code": null,
"e": 3645,
"s": 3443,
"text": "Do note that this filtered data is only till 2018 in case you are wondering why aren't any of your favorite games which came out in 2019 like God of War, Spiderman or Red Dead Redemption 2 in this list"
},
{
"code": null,
"e": 4176,
"s": 3645,
"text": "top_50_filtered %>% filter(!is.na(publisher)) %>% group_by(publisher) %>% summarise(owners=sum(owners)) %>% ggplot(aes(reorder(publisher,owners),owners))+ geom_bar(fill=\"#8B2E8B\",stat = \"identity\",color=\"black\")+ coord_flip()+ geom_text(aes(label=paste0(round(owners/1000000,digits = 1),\" \",\"M\")),color=\"white\",fontface=\"bold\",hjust=1)+ new_retro()+ scale_color_hotlineBling()+ labs(x=\" \")+ scale_y_comma()+ theme(legend.position = \"none\",axis.text.y = element_text(colour = \"white\",family = \"SF Alien Encounters\"))"
},
{
"code": null,
"e": 4210,
"s": 4176,
"text": "Started by removing NA publishers"
},
{
"code": null,
"e": 4290,
"s": 4210,
"text": "Performed the same group by function to get total owners against each publisher"
},
{
"code": null,
"e": 4491,
"s": 4290,
"text": "Used ggplot and geom_bar to make a standard barplot and used the coord_flip function to flip axes. Note the reorder function within ggplot allows to plot a sorted barplot from largest to lowest values"
},
{
"code": null,
"e": 4679,
"s": 4491,
"text": "Since the owners variable is in millions, I divided it by a million and concatenated an “M” at the end using paste0 to label total owners for each publisher without messing the aesthetics"
},
{
"code": null,
"e": 4818,
"s": 4679,
"text": "A lot of familiar faces in there like Ubisoft, Rockstar Games, etc but honestly I did not know about Digital Extremes — sitting at the top"
},
{
"code": null,
"e": 4950,
"s": 4818,
"text": "They are actually responsible for a really popular online free-to-play, role-playing shooter called Warframe which came out in 2013"
},
{
"code": null,
"e": 5252,
"s": 4950,
"text": "top_50_filtered %>% ggplot(aes(user_score,metascore.x))+ geom_point(color=\"green\")+ geom_text(aes(label=game),check_overlap = TRUE,color=\"turquoise\",size=3)+ vapoRwave::new_retro()+ scale_color_newRetro()+ labs(title = \"Relationship between Userscore and Metascore\",x=\"USERSCORE\",y=\"METASCORE\")"
},
{
"code": null,
"e": 5415,
"s": 5252,
"text": "There is a general trend between User Score and Metascore. Games like The Witcher 3, GTA V, Rayman Legends and Rocket League scored high in both and deservedly so"
},
{
"code": null,
"e": 5599,
"s": 5415,
"text": "The games that are encircled are the ones that were hyped but failed in meeting expectations. Although I am surprised that Shadow of War had such a low user score, that game was sick!"
},
{
"code": null,
"e": 5790,
"s": 5599,
"text": "One game that caught my attention is Mad Max. It received lukewarm reviews from critics but the users liked it. I actually never played it because of the former but this might change my mind"
},
{
"code": null,
"e": 6098,
"s": 5790,
"text": "top_50_filtered %>% top_n(30,user_score) %>% ggplot(aes(reorder(game,user_score),user_score))+ geom_lollipop(color=\"white\")+ coord_flip()+ geom_text(aes(label=user_score),color=\"white\",hjust=-1)+ new_retro()+ scale_y_continuous(limits = c(0,100))+ labs(x=\" \",title = \"Top 30 Games by User Score\")"
},
{
"code": null,
"e": 6173,
"s": 6098,
"text": "Used the top_n function to filter out the top 30 games based on user_score"
},
{
"code": null,
"e": 6250,
"s": 6173,
"text": "reorder function within ggplot to sort the plot from largest value to lowest"
},
{
"code": null,
"e": 6289,
"s": 6250,
"text": "geom_lollipop to make a lollipop chart"
},
{
"code": null,
"e": 6363,
"s": 6289,
"text": "Not surprised to see The Witcher 3 at the top. The game was a masterpiece"
},
{
"code": null,
"e": 6527,
"s": 6363,
"text": "Although I am surprised to see The Evil Within 2 at second place. It was a really good game but I didn't realize it would score so high, more than games like GTA V"
},
{
"code": null,
"e": 6689,
"s": 6527,
"text": "So the sequel to Shadow of War, Middle Earth: Shadow of Mordor scored a lot better with the users. I personally liked the prequel better but both were good games"
},
{
"code": null,
"e": 6985,
"s": 6689,
"text": "I am surprised to see Batman: Arkham Knight lower than expected. It is one of my all-time favorite games on the PS4 and the best in the Batman Arkham trilogy in my opinion. I think the low score could be attributed to people being annoyed by the batmobile mechanics and underwhelming boss fights"
},
{
"code": null,
"e": 7314,
"s": 6985,
"text": "top_50_filtered %>% top_n(30,metascore.x) %>% ggplot(aes(reorder(game,metascore.x),metascore.x))+ geom_lollipop(color=\"light blue\")+ coord_flip()+ geom_text(aes(label=metascore.x),color=\"light blue\",hjust=-1)+ new_retro()+ scale_y_continuous(limits = c(0,100))+ labs(x=\" \",y=\" \",title = \"Top 30 Games by Meta Score\")"
},
{
"code": null,
"e": 7375,
"s": 7314,
"text": "Same code as before. Just replaced user score with metascore"
},
{
"code": null,
"e": 7612,
"s": 7375,
"text": "You can clearly see that a lot of the games have shifted when we move from user score to Metascore. Using the anti_join function we can see which games present in the top 30 games by user score were not in the top 30 games by meta score"
},
{
"code": null,
"e": 7726,
"s": 7612,
"text": "top_50_filtered %>% top_n(30,user_score) %>% anti_join(top_50_filtered %>% top_n(30,metascore.x))"
},
{
"code": null,
"e": 7915,
"s": 7726,
"text": "The anti_join function here automatically detects the common column between the two data frames — game and shows the top 30 user games that are not present in the top 30 games by metascore"
},
{
"code": null,
"e": 8053,
"s": 7915,
"text": "Most of these games do not have a major difference between their user score and Metascore with the exception of Evil Within 2 and Mad Max"
},
{
"code": null,
"e": 8289,
"s": 8053,
"text": "top_50_filtered %>% filter(!is.na(publisher)) %>% ggplot(aes(reorder(publisher,user_score,FUN = mean),user_score))+ geom_boxplot(color=\"purple\")+ geom_hline(yintercept = 80,color=\"white\")+ coord_flip()+ new_retro()+ labs(x=\" \")"
},
{
"code": null,
"e": 8378,
"s": 8289,
"text": "Plotting a boxplot to visualize the distribution of user score for the top 50 publishers"
},
{
"code": null,
"e": 8451,
"s": 8378,
"text": "Used the reorder function to sort the boxplots by the average user score"
},
{
"code": null,
"e": 8530,
"s": 8451,
"text": "Added a vertical line at 80 as a threshold for what is considered a great game"
},
{
"code": null,
"e": 8665,
"s": 8530,
"text": "I can see why Ubisoft scores so low here. Their recent games in the Far Cry and Assassin’s Creed series have been pretty underwhelming"
},
{
"code": null,
"e": 8731,
"s": 8665,
"text": "Rockstar never disappoints. Every game they make is a masterpiece"
},
{
"code": null,
"e": 8831,
"s": 8731,
"text": "Activision is all over the place. Maybe people are finally getting tired of the Call of Duty series"
},
{
"code": null,
"e": 9101,
"s": 8831,
"text": "Capcom is really low. This is probably due to releasing an incomplete Street Fighter V game and charging full price for it. But 2019 has been an amazing year for Capcom with games like Monster Hunter, Resident Evil 2: Remake and Devil May Cry 5 being huge hits for them"
},
{
"code": null,
"e": 9352,
"s": 9101,
"text": "top_50_filtered %>% filter(!is.na(publisher)) %>% ggplot(aes(reorder(publisher,metascore.x,FUN = mean),metascore.x))+ geom_boxplot(color=\"green\")+ geom_hline(yintercept = 80,color=\"white\")+ coord_flip()+ new_retro()+ labs(x=\" \",y=\"Metascore\")"
},
{
"code": null,
"e": 9447,
"s": 9352,
"text": "Seems like publishers do a lot better when it comes to Metascore compared to their user scores"
},
{
"code": null,
"e": 9807,
"s": 9447,
"text": "top_50_filtered %>% top_n(30,average_playtime) %>% ggplot(aes(reorder(game,average_playtime/60),average_playtime/60))+ geom_lollipop(color=\"purple\")+ coord_flip()+ geom_text(aes(label= round(average_playtime/60)),color=\"white\",hjust=-1)+ vapoRwave::new_retro()+ scale_y_continuous(limits = c(0,40))+ labs(x=\" \",y=\"Average playtime in 2 weeks - (hrs)\")"
},
{
"code": null,
"e": 9920,
"s": 9807,
"text": "The average playtime for each game measures how long did users play the game for two weeks on average in minutes"
},
{
"code": null,
"e": 9981,
"s": 9920,
"text": "Used top_n function to only look at the top 30 longest games"
},
{
"code": null,
"e": 10050,
"s": 9981,
"text": "when plotting, divided average_playtime by 60 to convert it into hrs"
},
{
"code": null,
"e": 10097,
"s": 10050,
"text": "geom_text to label the average_playtime in hrs"
},
{
"code": null,
"e": 10220,
"s": 10097,
"text": "Most of the top longest games are open-world like Just Cause 4, Far Cry 5, Mad Max, Assassin’s Creed, GTA V, and Witcher 3"
},
{
"code": null,
"e": 10305,
"s": 10220,
"text": "Surprised to see Prey number 3. I didn't play it but I don't think it was open-world"
},
{
"code": null,
"e": 10790,
"s": 10305,
"text": "top_50_filtered %>% mutate(percentage_positive_users=positive_users/(positive_users+negative_users+neutral_users), percentage_positive_critics =positive_critics/(positive_critics+negative_critics+neutral_critics)) %>% filter(positive_users>=10,percentage_positive_users>=0.5) %>% top_n(30,percentage_positive_users) %>% ggplot(aes(reorder(game,percentage_positive_users),percentage_positive_users))+ geom_lollipop(color=\"white\")+ coord_flip()+ labs(x=\" \")+ new_retro()"
},
{
"code": null,
"e": 10900,
"s": 10790,
"text": "Used the mutate function to create two new columns: percentage_positive_users and percentage_positive_critics"
},
{
"code": null,
"e": 11104,
"s": 10900,
"text": "Since there are some games who received very few total scores, I used the filter function to show only those who had at least 10 positive user scores and had an overall percentage of positive users ≥ 50%"
},
{
"code": null,
"e": 11173,
"s": 11104,
"text": "Rest is the same code that we have used for previous lollipop charts"
},
{
"code": null,
"e": 11208,
"s": 11173,
"text": "Wow! surprised to see GTA V so low"
},
{
"code": null,
"e": 11302,
"s": 11208,
"text": "Mad Max and Dying Light are one of those games that were really good but went under the radar"
},
{
"code": null,
"e": 11398,
"s": 11302,
"text": "Sword Art Online received horrendous reviews from the critics but looks like the users liked it"
},
{
"code": null,
"e": 11893,
"s": 11398,
"text": "top_50_filtered %>% mutate(percentage_positive_users=positive_users/(positive_users+negative_users+neutral_users), percentage_positive_critics =positive_critics/(positive_critics+negative_critics+neutral_critics)) %>% filter(positive_critics>=10,percentage_positive_critics>=0.5) %>% top_n(30,percentage_positive_critics) %>% ggplot(aes(reorder(game,percentage_positive_critics),percentage_positive_critics))+ geom_lollipop(color=\"white\")+ coord_flip()+ labs(x=\" \")+ new_retro()"
},
{
"code": null,
"e": 11984,
"s": 11893,
"text": "NBA 2k16 and NBA 2k17 received good reviews from the critics but low scores from the users"
},
{
"code": null,
"e": 12096,
"s": 11984,
"text": "Honestly, I have not heard about the top 4 games but these aren't considered AAA games due to their small scale"
},
{
"code": null,
"e": 12600,
"s": 12096,
"text": "Predicting the Metascore is not practical since it is calculated based on a formula of all the numerical variables provided in the dataset. Predicting user score is more interesting. For this, I will be using the Tidymodels meta-package. It is a collection of packages that allows you to create a seamless data pipeline from preprocessing your data, tuning your models, modeling your data , making predictions and measuring your model performance while adhering to the “tidy” principles of the Tidyverse"
},
{
"code": null,
"e": 13217,
"s": 12600,
"text": "library(tidymodels)ratings_data <- top_50_filtered %>% mutate(percentage_positive_users=positive_users/(positive_users+negative_users+neutral_users), percentage_negative_users =negative_users/(positive_users+negative_users+neutral_users), percentage_positive_critics =positive_critics/(positive_critics+negative_critics+neutral_critics), percentage_negative_critics =negative_critics/(positive_critics+negative_critics+neutral_critics)) %>% drop_na()Splitting the datasplit <- initial_split(ratings_data,prop = 0.6,)train_games <- split %>% training() %>%test_games <- split %>% testing()"
},
{
"code": null,
"e": 13313,
"s": 13217,
"text": "Used the mutate function to create new variables that will be used as predictors for user_score"
},
{
"code": null,
"e": 13337,
"s": 13313,
"text": "Drop any missing values"
},
{
"code": null,
"e": 13446,
"s": 13337,
"text": "Use the intial_split function from rsample library to create a split parameter for our train and test splits"
},
{
"code": null,
"e": 13546,
"s": 13446,
"text": "Chain it with the training and testing functions from rsample to create our train and test datasets"
},
{
"code": null,
"e": 14073,
"s": 13546,
"text": "Creating Recipenorm_recipe <- recipe(user_score~percentage_positive_critics+percentage_negative_critics+percentage_positive_users+ percentage_negative_users+price+genre+rating+publisher,data = train_games) %>% step_naomit(all_numeric(),all_nominal()) %>% step_dummy(all_nominal(),,one_hot = TRUE) %>% step_normalize(all_predictors(),na_rm = TRUE) %>% step_corr(all_predictors()) %>% prep()Applying Recipe on Train and Test setstrain_prepped <- juice(norm_recipe)test_prepped <- norm_recipe %>% bake(test_game)"
},
{
"code": null,
"e": 14207,
"s": 14073,
"text": "Using the Recipes package, I am a creating a “recipe” which is basically a pipeline of how I want to process the variables in my data"
},
{
"code": null,
"e": 14295,
"s": 14207,
"text": "we start with defining the relationship between the dependent and independent variables"
},
{
"code": null,
"e": 14352,
"s": 14295,
"text": "The “step” functions are the data transforming functions"
},
{
"code": null,
"e": 14427,
"s": 14352,
"text": "step_naomit removes missing values from both nominal and numeric variables"
},
{
"code": null,
"e": 14493,
"s": 14427,
"text": "step_dummy does one-hot encoding on all the categorical variables"
},
{
"code": null,
"e": 14546,
"s": 14493,
"text": "step_normalize normalizes all the numeric predictors"
},
{
"code": null,
"e": 14635,
"s": 14546,
"text": "step_corr removes any independent variables that have a high correlation with each other"
},
{
"code": null,
"e": 14693,
"s": 14635,
"text": "prep function basically finalizes and prepares the recipe"
},
{
"code": null,
"e": 14791,
"s": 14693,
"text": "juice function, when applied on norm_recipe, gives us the transformed version of the training set"
},
{
"code": null,
"e": 14900,
"s": 14791,
"text": "bake function chained together with norm_recipe and applied on the test data give us the transformed version"
},
{
"code": null,
"e": 15025,
"s": 14900,
"text": "ranger <- rand_forest(trees = 100,mode = \"regression\") %>% set_engine(\"ranger\") %>% fit(user_score~.,data=train_prepped)"
},
{
"code": null,
"e": 15117,
"s": 15025,
"text": "For defining our model we use the Parsnip package to define a randomforest regression model"
},
{
"code": null,
"e": 15142,
"s": 15117,
"text": "Set the engine to ranger"
},
{
"code": null,
"e": 15228,
"s": 15142,
"text": "Use the fit function to define our formula and supplied the transformed training data"
},
{
"code": null,
"e": 15567,
"s": 15228,
"text": "Converting NAs to 0test_prepped <- test_prepped %>% mutate_all(~replace(.,is.na(.),0))Making predictionsranger %>% predict(test_prepped) %>% bind_cols(test_games) %>% select(game,.pred,user_score)Measuring Model Accuracyranger %>% predict(test_prepped) %>% bind_cols(test_games) %>% metrics(truth=user_score,estimate=.pred)"
},
{
"code": null,
"e": 15704,
"s": 15567,
"text": "Before applying predictions on the prepped test set, I had to convert some NAs to 0 otherwise the randomforest model will throw an error"
},
{
"code": null,
"e": 15885,
"s": 15704,
"text": "Finally, we use the ranger model to predict on our prepped test set and joined the predictions with the original test data to see the predicted and actual user scores for each game"
},
{
"code": null,
"e": 16059,
"s": 15885,
"text": "Once we have made predictions, I used the metrics function from the yardstick package to calculate the model's accuracy by supplying it both actual and predicted user scores"
},
{
"code": null,
"e": 16295,
"s": 16059,
"text": "rsq measures how much the variation in our dependent variable — user_score can be explained by the independent variables in our dataset. In our case, it is not too bad considering the type of data we had and it was a very small dataset"
},
{
"code": null,
"e": 16537,
"s": 16295,
"text": "It could be improved by hyperparameter tuning and cross-validation but that is beyond the scope of this article. Also, these features are still under development in Tidymodels as of now, there is no seamless to integrate them in our analysis"
}
] |
Create a Pandas DataFrame from Lists - GeeksforGeeks
|
02 Jun, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Creating Pandas Dataframe can be achieved in multiple ways. Let’s see how can we create a Pandas DataFrame from Lists.
YouTubeGeeksforGeeks502K subscribersCreating a Pandas DataFrame From Lists | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GOBzqpdZX5A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Code #1: Basic example
# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)df
Output: Code #2: Dataframe using list with index and column names
# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on list# with indices and columns specifieddf = pd.DataFrame(lst, index =['a', 'b', 'c', 'd', 'e', 'f', 'g'], columns =['Names'])df
Output: Code #3: Using zip() for zipping two lists
# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # list of intlst2 = [11, 22, 33, 44, 55, 66, 77] # Calling DataFrame constructor after zipping# both lists, with columns specifieddf = pd.DataFrame(list(zip(lst, lst2)), columns =['Name', 'val'])df
Output: Code #4: Creating DataFrame using multi-dimensional list
# import pandas as pdimport pandas as pd # List1 lst = [['tom', 25], ['krish', 30], ['nick', 26], ['juli', 22]] df = pd.DataFrame(lst, columns =['Name', 'Age'])df
Output: Code #5: Using multi-dimensional list with column name and dtype specified.
# import pandas as pdimport pandas as pd # List1 lst = [['tom', 'reacher', 25], ['krish', 'pete', 30], ['nick', 'wilson', 26], ['juli', 'williams', 22]] df = pd.DataFrame(lst, columns =['FName', 'LName', 'Age'], dtype = float)df
Output: Code #6: Using lists in dictionary to create dataframe
# importing pandas as pd import pandas as pd # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) df
Output:
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python
sum() function in Python
|
[
{
"code": null,
"e": 24827,
"s": 24799,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 25041,
"s": 24827,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 25160,
"s": 25041,
"text": "Creating Pandas Dataframe can be achieved in multiple ways. Let’s see how can we create a Pandas DataFrame from Lists."
},
{
"code": null,
"e": 25997,
"s": 25160,
"text": "YouTubeGeeksforGeeks502K subscribersCreating a Pandas DataFrame From Lists | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:05•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=GOBzqpdZX5A\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 26020,
"s": 25997,
"text": "Code #1: Basic example"
},
{
"code": "# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on listdf = pd.DataFrame(lst)df",
"e": 26220,
"s": 26020,
"text": null
},
{
"code": null,
"e": 26286,
"s": 26220,
"text": "Output: Code #2: Dataframe using list with index and column names"
},
{
"code": "# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # Calling DataFrame constructor on list# with indices and columns specifieddf = pd.DataFrame(lst, index =['a', 'b', 'c', 'd', 'e', 'f', 'g'], columns =['Names'])df",
"e": 26619,
"s": 26286,
"text": null
},
{
"code": null,
"e": 26670,
"s": 26619,
"text": "Output: Code #3: Using zip() for zipping two lists"
},
{
"code": "# import pandas as pdimport pandas as pd # list of stringslst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] # list of intlst2 = [11, 22, 33, 44, 55, 66, 77] # Calling DataFrame constructor after zipping# both lists, with columns specifieddf = pd.DataFrame(list(zip(lst, lst2)), columns =['Name', 'val'])df",
"e": 27007,
"s": 26670,
"text": null
},
{
"code": null,
"e": 27072,
"s": 27007,
"text": "Output: Code #4: Creating DataFrame using multi-dimensional list"
},
{
"code": "# import pandas as pdimport pandas as pd # List1 lst = [['tom', 25], ['krish', 30], ['nick', 26], ['juli', 22]] df = pd.DataFrame(lst, columns =['Name', 'Age'])df",
"e": 27248,
"s": 27072,
"text": null
},
{
"code": null,
"e": 27332,
"s": 27248,
"text": "Output: Code #5: Using multi-dimensional list with column name and dtype specified."
},
{
"code": "# import pandas as pdimport pandas as pd # List1 lst = [['tom', 'reacher', 25], ['krish', 'pete', 30], ['nick', 'wilson', 26], ['juli', 'williams', 22]] df = pd.DataFrame(lst, columns =['FName', 'LName', 'Age'], dtype = float)df",
"e": 27574,
"s": 27332,
"text": null
},
{
"code": null,
"e": 27637,
"s": 27574,
"text": "Output: Code #6: Using lists in dictionary to create dataframe"
},
{
"code": "# importing pandas as pd import pandas as pd # list of name, degree, scorenme = [\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"]deg = [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"]scr = [90, 40, 80, 98] # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr} df = pd.DataFrame(dict) df ",
"e": 27926,
"s": 27637,
"text": null
},
{
"code": null,
"e": 27934,
"s": 27926,
"text": "Output:"
},
{
"code": null,
"e": 27959,
"s": 27934,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 27983,
"s": 27959,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27997,
"s": 27983,
"text": "Python-pandas"
},
{
"code": null,
"e": 28004,
"s": 27997,
"text": "Python"
},
{
"code": null,
"e": 28102,
"s": 28004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28120,
"s": 28102,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28155,
"s": 28120,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28177,
"s": 28155,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28209,
"s": 28177,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28239,
"s": 28209,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28281,
"s": 28239,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28324,
"s": 28281,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28368,
"s": 28324,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28397,
"s": 28368,
"text": "*args and **kwargs in Python"
}
] |
How to create a Dice Rolling App using ReactJS ? - GeeksforGeeks
|
22 Apr, 2022
Suppose there are two dice and a button to roll the dices. As we click the button both dices shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers shown on the upper face generates randomly each time we roll the dice.
There are two components Die and RollDice. The Die component is responsible to show one individual Dice. It is a stateless component. It uses the font-awesome library to show the standard dots on the upper face of the dice. RollDice component contains all the logic to generate random numbers to show on the upper face of the dice, roll each dice upon click on the roll button. There are two states involved in the RollDice component named ‘die1’ and ‘die2’. Each one has initialized with the value one i.e. each die shows one(one dot) when the application first starts.
Now, we set the click event handler to the roll dice button and when anyone clicks on the button we change the state of both die1 and die2 to some random number using setState from one to six (we use a number as a word since font-awesome library deals with word number to show the exact number of dots). We also make sure when the dice is rolling user can’t click on the button again. For this purpose we use a state ‘rolling’ initially set to false and when the dice are rolling set rolling to true and start a timer of one second. After one second again set the rolling state to false’. Disable the button when a rolling state is set to true.
This is a rough overview of the application. Let’s implement it to understand it better.
Modules required
npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
npm install --save @fortawesome/react-fontawesome
Example:
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js: App component renders a single RollDice component only
Javascript
import React from 'react';import RollDice from './RollDice'import { library } from '@fortawesome/fontawesome-svg-core'import { fas } from '@fortawesome/free-solid-svg-icons'library.add(fas) function App() { return ( <div> <RollDice /> </div> );} export default App;
RollDice.js : It contains all the behind the logic. The setting event handler, updating all the states according to the user’s interaction render Die component. This file has to be created by you.
Javascript
import React,{ Component } from 'react'import './RollDice.css'import Die from './Die' class RollDice extends Component{ // Face numbers passes as default props static defaultProps = { sides : ['one', 'two', 'three', 'four', 'five', 'six'] } constructor(props){ super(props) // States this.state = { die1 : 'one', die2 : 'one', rolling: false } this.roll = this.roll.bind(this) } roll(){ const {sides} = this.props this.setState({ // Changing state upon click die1 : sides[Math.floor(Math.random() * sides.length)], die2 : sides[Math.floor(Math.random() * sides.length)], rolling:true }) // Start timer of one sec when rolling start setTimeout(() => { // Set rolling to false again when time over this.setState({rolling:false}) },1000) } render(){ const handleBtn = this.state.rolling ? 'RollDice-rolling' : '' const {die1, die2, rolling} = this.state return( <div className='RollDice'> <div className='RollDice-container'> <Die face={die1} rolling={rolling}/> <Die face={die2} rolling={rolling}/> </div> <button className={handleBtn} disabled={this.state.rolling} onClick={this.roll}> {this.state.rolling ? 'Rolling' : 'Roll Dice!'} </button> </div> ) }} export default RollDice
Die.js: Responsible to show single-die component only with correct dotted number face as communicated by the parent RollDice component. This file has to be created by you.
Javascript
import React, {Component} from 'react'import React, {Component} from 'react'import './Die.css'import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' class Die extends Component{render(){ const {face, rolling} = this.props // Using font awesome icon to show // the exactnumber of dots return ( <div> <FontAwesomeIcon icon={['fas', `fa-dice-${face}`]} className={`Die ${rolling && 'Die-shaking'}`} /> </div > )}} export default Die
RollDice.css : Styling RollDice component contents
CSS
.RollDice{ display: flex; flex-flow: column nowrap; min-height: 100vh;} /* Shows each dice in one row */.RollDice-container{ display: flex; justify-content: center; align-content: center;}/* Styling rolldice button */.RollDice button{ width:15em; padding:1.5em; border: 0px; border-radius: 10px; color:white; background-color:black; margin-top: 3em; align-self: center;} /* Setting hover effect on button */.RollDice button:hover{ cursor: pointer;} .RollDice-rolling{ border: 0px; border-radius: 10px; background-color:darkslateblue !important; opacity:0.7}
Die.css: Styling each die component and setting animation effect to it.
CSS
/* Styling each Die */.Die{ font-size:10em; padding:0.25em; color:slateblue;} /* Applying Animation */.Die-shaking{ animation-name:wobble; animation-duration: 1s;} /* Setting Animation effect to the dice using css keyframe */@keyframes wobble { from { transform: translate3d(0, 0, 0); } 15% { transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg); } 30% { transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg); } 45% { transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg); } 60% { transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg); } 75% { transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg); } to { transform: translate3d(0, 0, 0); }}
Output :
ruhelaa48
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 26775,
"s": 26747,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 27061,
"s": 26775,
"text": "Suppose there are two dice and a button to roll the dices. As we click the button both dices shake and generate a new number that shows on the upper face of the dice (in dotted form as a standard dice). The numbers shown on the upper face generates randomly each time we roll the dice."
},
{
"code": null,
"e": 27633,
"s": 27061,
"text": "There are two components Die and RollDice. The Die component is responsible to show one individual Dice. It is a stateless component. It uses the font-awesome library to show the standard dots on the upper face of the dice. RollDice component contains all the logic to generate random numbers to show on the upper face of the dice, roll each dice upon click on the roll button. There are two states involved in the RollDice component named ‘die1’ and ‘die2’. Each one has initialized with the value one i.e. each die shows one(one dot) when the application first starts. "
},
{
"code": null,
"e": 28278,
"s": 27633,
"text": "Now, we set the click event handler to the roll dice button and when anyone clicks on the button we change the state of both die1 and die2 to some random number using setState from one to six (we use a number as a word since font-awesome library deals with word number to show the exact number of dots). We also make sure when the dice is rolling user can’t click on the button again. For this purpose we use a state ‘rolling’ initially set to false and when the dice are rolling set rolling to true and start a timer of one second. After one second again set the rolling state to false’. Disable the button when a rolling state is set to true."
},
{
"code": null,
"e": 28367,
"s": 28278,
"text": "This is a rough overview of the application. Let’s implement it to understand it better."
},
{
"code": null,
"e": 28384,
"s": 28367,
"text": "Modules required"
},
{
"code": null,
"e": 28535,
"s": 28384,
"text": "npm i --save @fortawesome/fontawesome-svg-core\nnpm install --save @fortawesome/free-solid-svg-icons\nnpm install --save @fortawesome/react-fontawesome\n"
},
{
"code": null,
"e": 28544,
"s": 28535,
"text": "Example:"
},
{
"code": null,
"e": 28554,
"s": 28544,
"text": "index.js:"
},
{
"code": null,
"e": 28565,
"s": 28554,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 28705,
"s": 28565,
"text": null
},
{
"code": null,
"e": 28769,
"s": 28705,
"text": "App.js: App component renders a single RollDice component only"
},
{
"code": null,
"e": 28780,
"s": 28769,
"text": "Javascript"
},
{
"code": "import React from 'react';import RollDice from './RollDice'import { library } from '@fortawesome/fontawesome-svg-core'import { fas } from '@fortawesome/free-solid-svg-icons'library.add(fas) function App() { return ( <div> <RollDice /> </div> );} export default App;",
"e": 29061,
"s": 28780,
"text": null
},
{
"code": null,
"e": 29258,
"s": 29061,
"text": "RollDice.js : It contains all the behind the logic. The setting event handler, updating all the states according to the user’s interaction render Die component. This file has to be created by you."
},
{
"code": null,
"e": 29269,
"s": 29258,
"text": "Javascript"
},
{
"code": "import React,{ Component } from 'react'import './RollDice.css'import Die from './Die' class RollDice extends Component{ // Face numbers passes as default props static defaultProps = { sides : ['one', 'two', 'three', 'four', 'five', 'six'] } constructor(props){ super(props) // States this.state = { die1 : 'one', die2 : 'one', rolling: false } this.roll = this.roll.bind(this) } roll(){ const {sides} = this.props this.setState({ // Changing state upon click die1 : sides[Math.floor(Math.random() * sides.length)], die2 : sides[Math.floor(Math.random() * sides.length)], rolling:true }) // Start timer of one sec when rolling start setTimeout(() => { // Set rolling to false again when time over this.setState({rolling:false}) },1000) } render(){ const handleBtn = this.state.rolling ? 'RollDice-rolling' : '' const {die1, die2, rolling} = this.state return( <div className='RollDice'> <div className='RollDice-container'> <Die face={die1} rolling={rolling}/> <Die face={die2} rolling={rolling}/> </div> <button className={handleBtn} disabled={this.state.rolling} onClick={this.roll}> {this.state.rolling ? 'Rolling' : 'Roll Dice!'} </button> </div> ) }} export default RollDice",
"e": 30711,
"s": 29269,
"text": null
},
{
"code": null,
"e": 30883,
"s": 30711,
"text": "Die.js: Responsible to show single-die component only with correct dotted number face as communicated by the parent RollDice component. This file has to be created by you."
},
{
"code": null,
"e": 30894,
"s": 30883,
"text": "Javascript"
},
{
"code": "import React, {Component} from 'react'import React, {Component} from 'react'import './Die.css'import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' class Die extends Component{render(){ const {face, rolling} = this.props // Using font awesome icon to show // the exactnumber of dots return ( <div> <FontAwesomeIcon icon={['fas', `fa-dice-${face}`]} className={`Die ${rolling && 'Die-shaking'}`} /> </div > )}} export default Die",
"e": 31414,
"s": 30894,
"text": null
},
{
"code": null,
"e": 31465,
"s": 31414,
"text": "RollDice.css : Styling RollDice component contents"
},
{
"code": null,
"e": 31469,
"s": 31465,
"text": "CSS"
},
{
"code": ".RollDice{ display: flex; flex-flow: column nowrap; min-height: 100vh;} /* Shows each dice in one row */.RollDice-container{ display: flex; justify-content: center; align-content: center;}/* Styling rolldice button */.RollDice button{ width:15em; padding:1.5em; border: 0px; border-radius: 10px; color:white; background-color:black; margin-top: 3em; align-self: center;} /* Setting hover effect on button */.RollDice button:hover{ cursor: pointer;} .RollDice-rolling{ border: 0px; border-radius: 10px; background-color:darkslateblue !important; opacity:0.7}",
"e": 32049,
"s": 31469,
"text": null
},
{
"code": null,
"e": 32121,
"s": 32049,
"text": "Die.css: Styling each die component and setting animation effect to it."
},
{
"code": null,
"e": 32125,
"s": 32121,
"text": "CSS"
},
{
"code": "/* Styling each Die */.Die{ font-size:10em; padding:0.25em; color:slateblue;} /* Applying Animation */.Die-shaking{ animation-name:wobble; animation-duration: 1s;} /* Setting Animation effect to the dice using css keyframe */@keyframes wobble { from { transform: translate3d(0, 0, 0); } 15% { transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg); } 30% { transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg); } 45% { transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg); } 60% { transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg); } 75% { transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg); } to { transform: translate3d(0, 0, 0); }}",
"e": 32912,
"s": 32125,
"text": null
},
{
"code": null,
"e": 32921,
"s": 32912,
"text": "Output :"
},
{
"code": null,
"e": 32931,
"s": 32921,
"text": "ruhelaa48"
},
{
"code": null,
"e": 32940,
"s": 32931,
"text": "react-js"
},
{
"code": null,
"e": 32957,
"s": 32940,
"text": "Web Technologies"
},
{
"code": null,
"e": 33055,
"s": 32957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33064,
"s": 33055,
"text": "Comments"
},
{
"code": null,
"e": 33077,
"s": 33064,
"text": "Old Comments"
},
{
"code": null,
"e": 33133,
"s": 33077,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 33166,
"s": 33133,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33228,
"s": 33166,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33271,
"s": 33228,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33321,
"s": 33271,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 33382,
"s": 33321,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33427,
"s": 33382,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33487,
"s": 33427,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 33545,
"s": 33487,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
How to use the Reverse() method of array class in C#
|
The Reverse() method in array class reverses the sequence of the elements in the entire one-dimensional Array.
To reverse an array, just use the Array.Reverse() method −
Array.Reverse(temp);
Within the reverse method, set the elements like the following code snippet.
int[] list = { 29, 15, 30, 98};
int[] temp = list;
You can try to run the following code to implement Reverse() method in C#.
Live Demo
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
int[] list = { 29, 15, 30, 98};
int[] temp = list;
Console.Write("Original Array: ");
foreach (int i in list) {
Console.Write(i + " ");
}
Console.WriteLine();
// reverse the array
Array.Reverse(temp);
Console.Write("Reversed Array: ");
foreach (int i in temp) {
Console.Write(i + " ");
}
Console.ReadKey();
}
}
}
Original Array: 29 15 30 98
Reversed Array: 98 30 15 29
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The Reverse() method in array class reverses the sequence of the elements in the entire one-dimensional Array."
},
{
"code": null,
"e": 1232,
"s": 1173,
"text": "To reverse an array, just use the Array.Reverse() method −"
},
{
"code": null,
"e": 1253,
"s": 1232,
"text": "Array.Reverse(temp);"
},
{
"code": null,
"e": 1330,
"s": 1253,
"text": "Within the reverse method, set the elements like the following code snippet."
},
{
"code": null,
"e": 1381,
"s": 1330,
"text": "int[] list = { 29, 15, 30, 98};\nint[] temp = list;"
},
{
"code": null,
"e": 1456,
"s": 1381,
"text": "You can try to run the following code to implement Reverse() method in C#."
},
{
"code": null,
"e": 1467,
"s": 1456,
"text": " Live Demo"
},
{
"code": null,
"e": 2011,
"s": 1467,
"text": "using System;\nnamespace Demo {\n class MyArray {\n static void Main(string[] args) {\n int[] list = { 29, 15, 30, 98};\n int[] temp = list;\n Console.Write(\"Original Array: \");\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n Console.WriteLine();\n // reverse the array\n Array.Reverse(temp);\n Console.Write(\"Reversed Array: \");\n foreach (int i in temp) {\n Console.Write(i + \" \");\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2067,
"s": 2011,
"text": "Original Array: 29 15 30 98\nReversed Array: 98 30 15 29"
}
] |
Exploratory Data Analysis using Pandas | by Mamtha | Towards Data Science
|
In this article we will focus on ‘Brazil’s Amazon Forest Fires Dataset’ and perform some basic analysis using Pandas library and visualise data using Matplotlib and Seaborn libraries.
Pandas is a most powerful tool of Python that allows us to do anything and everything with datasets such as — analysing the data, organising, cleaning, sorting, filtering, aggregating, calculating and more!, which makes data analysis very easy.
In this post, we will go over the ‘Amazon fires dataset’ (downloaded from Kaggle.com) and explore pandas functionalities which will help us to do Exploratory Data Analysis(EDA) by doing few exercises and then visualising the data using python’s visualisation libraries.
First, let’s dig into our Kaggle Dataset - Forest Fires in Brazil (amazon.csv), which you can download here.
For those who are not aware of Kaggle.com, let me give you some idea..
Kaggle is a most popular online community for data scientists and machine learners who can participate in analytical competitions, build predictive models and is a great place for users looking for interesting datasets. We can find all varieties of data including image datasets, CSVs, time-series datasets etc. , which are free to download.
What is this dataset about?
This dataset contains 10 years of data which has total number of forest fires occurred in Amazon rainforest (Brazil states) for the period 1998 to 2017.
The Amazon is a vast region that spans across eight rapidly developing countries: Brazil, Bolivia, Peru, Ecuador, Colombia, Venezuela, Guyana, Suriname and French Guiana. The majority of the amazon forest is contained within Brazil, with 60% of the rainforest.
Now, let’s start our pandas exercises to explore this dataset and draw some insights.
Let’s follow below steps :
First we will import all the required python libraries.
Download dataset from kaggle, save it to our desktop and extract it to Jupyter notebook using python.
Analyse few questions and visualise the data.
Before importing our libraries, let’s install them using pip install command to our python Jupyter notebook or any other python interface where we do our coding.
Pandas : pip install pandasNumpy : pip install numpyMatplotlib : pip install matplotlibSeaborn : pip install seaborn
Let’s read the csv file using pandas and save it to the dataframe
Now, let’s quickly check top 10 rows of our dataset
Dataset description:
Column 1- ‘year’ : Year when forest fires happened
Column 2- ‘state’ : Brazilian State
Column 3- ‘month’ : Month when forest fires happened
Column 4- ‘number’ : Number of forest fires reported
Column 5- ‘date’ : Date when forest fires were reported
info()method gives us the quick overview of our dataset like total number of rows and columns, datatypes and number of null values if any
From above output it is clear that we have total of 6454 rows(includes header), 5 columns and no null fields(which is a good sign for our analysis 🙂)
Let’s have a look at the statistical summary about our dataset ( for numeric values) using describe() method
Data Cleaning :
Cleaning up data is the first and most important step, as it ensures the quality of the data is met to prepare data for visualisation. From above dataset after thorough check we see that ‘number’ column(number of forest fires reported) which is of float type has values in decimal point such as 18.566, 14.59, 11.068 ... That means this value is not rounded and it doesn't make any sense to the number of forest fires reported . So let’s clean up this data using round function and store the data back to our main dataframe .
First let’s apply round() function for sample data...
Before :
After :
Now we will apply round() method to entire dataset using numpy
Exercise 1 : To check minimum and maximum of ‘year’ column
Exercise 2 : To find out total number of fires in ‘Acre’ state and visualising data based on each ‘year’
Before jumping into this exercise, I would like to deep dive into an important concept called ‘Boolean Indexing’ in Pandas which will be of very much help when dealing with subsets of data based on the actual values of the data.
Boolean Indexing :
Boolean indexing as the name suggests, is used when we want to extract subsets of data from the dataframe based on some conditions. We can also have multiple conditions which can be grouped in brackets and apply to the dataframe.
Let’s look at below example of how boolean indexing works in pandas. In our example, we’ll work with the dataframe of employees and their salary :
import pandas as pddf = pd.DataFrame({'EmployeeName': ['John','Sam','Sara','Nick','Bob','Julie'], 'Salary':[5000,8000,7000,10000,3000,5000]})
Let’s check which employee have a salary of 5000. First, we will perform a vectorised boolean operation that produces a boolean series:
salary_bool = df['Salary'] == 5000
Now, we can use this series to index the whole dataframe, leaving us with the rows that correspond only to employees whose salary is 5000
salary_5000 = df[salary_bool] # that means it returns only those rows which are 'True'
I hope now you have some idea how boolean indexing works..You can find more info about Boolean Indexing tutorial here..
Now, let’s get started with our actual exercise i.e, to find the total number of forest fires in ‘Acre’ state:
It’s clear from above output that total number of fires reported in ‘Acre’ state are 18463 . Yes, this is too much to understand for the first time :). So let me break this code and explain it step by step.
Step 1 : Let’s use boolean indexing to get only ‘Acre’ state subset and assign it to variable called ‘amazon_acre’
amazon_acre = amazon['state'] == 'Acre'
‘amazon_acre’ will generate a series for us which shows True and False for each row based on our condition.
Step 2: Let’s use this series to index the entire dataset and assign it to variable called ‘amazon_acre_data’
amazon_acre_data = amazon[amazon_acre] # total 239 entries
Step 3 : Next let’s display only ‘number’ column from above dataset
amazon_acre_number = amazon_acre_data['number'] # this will display only ‘number’ column values.
Step 4 : Now we can use sum() function to amazon_acre_number variable to find total number of fires.
There you go.!! It’s always a best practice to break the code when we are experimenting the data for the first time. But, eventually to gain better programming skills we shall work on minimising the coding lines.
Now let’s use groupby() method on ‘year’ column and get total number of fires for each year.
Here in output, we see that ‘year’ is marked as index and ‘number’ as column. Just to make it more simple for visualising data, we can use reset_index() method to make index to be treated as a column.
Visualisation of above dataset:
Matplotlib is python’s data visualisation library, which allows us to visualise the data and is very easy to get started for simple plots. Matplotlib consists of several plots like line, bar, scatter, histogram etc., I recommend you to explore the official Matplotlib webpage for more info.
Seaborn is python’s most popular statistical visualisation library which is built on top of Matplotlib. Check out seaborn official webpage for all different types of seaborn plots.
Let’s visualise ‘acre_fires_year’ dataset using matplotlib and seaborn(barplot)
Note: plt.figure() creates a figure object, which we here used to customise the size of the chart.
Exercise 3 : To find out total number of fires in all states
For this, let’s use groupby() on ‘state’ column and find out total number of fires.
It’s clear from above plot that most forest fires occurred in ‘Mato Grosso’, followed by ‘Paraiba’ and ‘Sao Paulo’ states.
Exercise 4 : To find out total number of fires in 2017 and visualising data based on each ‘month’
Exercise 5 : To find out average number of fires occurred
Exercise 6 : To find out the state names where fires occurred in ‘December’ month
That’s all for this post... You should now have a good knowledge of what pandas, matplotlib and seaborn are and how to use them for data preparation and data visualisation.
Well, thank you for reading my first article :). I hope you found this article useful and please feel free to comment in comments section below if you have any questions and guide me with some suggestions and inputs 🙂
|
[
{
"code": null,
"e": 356,
"s": 172,
"text": "In this article we will focus on ‘Brazil’s Amazon Forest Fires Dataset’ and perform some basic analysis using Pandas library and visualise data using Matplotlib and Seaborn libraries."
},
{
"code": null,
"e": 601,
"s": 356,
"text": "Pandas is a most powerful tool of Python that allows us to do anything and everything with datasets such as — analysing the data, organising, cleaning, sorting, filtering, aggregating, calculating and more!, which makes data analysis very easy."
},
{
"code": null,
"e": 871,
"s": 601,
"text": "In this post, we will go over the ‘Amazon fires dataset’ (downloaded from Kaggle.com) and explore pandas functionalities which will help us to do Exploratory Data Analysis(EDA) by doing few exercises and then visualising the data using python’s visualisation libraries."
},
{
"code": null,
"e": 980,
"s": 871,
"text": "First, let’s dig into our Kaggle Dataset - Forest Fires in Brazil (amazon.csv), which you can download here."
},
{
"code": null,
"e": 1051,
"s": 980,
"text": "For those who are not aware of Kaggle.com, let me give you some idea.."
},
{
"code": null,
"e": 1393,
"s": 1051,
"text": "Kaggle is a most popular online community for data scientists and machine learners who can participate in analytical competitions, build predictive models and is a great place for users looking for interesting datasets. We can find all varieties of data including image datasets, CSVs, time-series datasets etc. , which are free to download."
},
{
"code": null,
"e": 1421,
"s": 1393,
"text": "What is this dataset about?"
},
{
"code": null,
"e": 1574,
"s": 1421,
"text": "This dataset contains 10 years of data which has total number of forest fires occurred in Amazon rainforest (Brazil states) for the period 1998 to 2017."
},
{
"code": null,
"e": 1835,
"s": 1574,
"text": "The Amazon is a vast region that spans across eight rapidly developing countries: Brazil, Bolivia, Peru, Ecuador, Colombia, Venezuela, Guyana, Suriname and French Guiana. The majority of the amazon forest is contained within Brazil, with 60% of the rainforest."
},
{
"code": null,
"e": 1921,
"s": 1835,
"text": "Now, let’s start our pandas exercises to explore this dataset and draw some insights."
},
{
"code": null,
"e": 1948,
"s": 1921,
"text": "Let’s follow below steps :"
},
{
"code": null,
"e": 2004,
"s": 1948,
"text": "First we will import all the required python libraries."
},
{
"code": null,
"e": 2106,
"s": 2004,
"text": "Download dataset from kaggle, save it to our desktop and extract it to Jupyter notebook using python."
},
{
"code": null,
"e": 2152,
"s": 2106,
"text": "Analyse few questions and visualise the data."
},
{
"code": null,
"e": 2314,
"s": 2152,
"text": "Before importing our libraries, let’s install them using pip install command to our python Jupyter notebook or any other python interface where we do our coding."
},
{
"code": null,
"e": 2443,
"s": 2314,
"text": "Pandas : pip install pandasNumpy : pip install numpyMatplotlib : pip install matplotlibSeaborn : pip install seaborn"
},
{
"code": null,
"e": 2509,
"s": 2443,
"text": "Let’s read the csv file using pandas and save it to the dataframe"
},
{
"code": null,
"e": 2561,
"s": 2509,
"text": "Now, let’s quickly check top 10 rows of our dataset"
},
{
"code": null,
"e": 2582,
"s": 2561,
"text": "Dataset description:"
},
{
"code": null,
"e": 2633,
"s": 2582,
"text": "Column 1- ‘year’ : Year when forest fires happened"
},
{
"code": null,
"e": 2669,
"s": 2633,
"text": "Column 2- ‘state’ : Brazilian State"
},
{
"code": null,
"e": 2722,
"s": 2669,
"text": "Column 3- ‘month’ : Month when forest fires happened"
},
{
"code": null,
"e": 2775,
"s": 2722,
"text": "Column 4- ‘number’ : Number of forest fires reported"
},
{
"code": null,
"e": 2831,
"s": 2775,
"text": "Column 5- ‘date’ : Date when forest fires were reported"
},
{
"code": null,
"e": 2969,
"s": 2831,
"text": "info()method gives us the quick overview of our dataset like total number of rows and columns, datatypes and number of null values if any"
},
{
"code": null,
"e": 3119,
"s": 2969,
"text": "From above output it is clear that we have total of 6454 rows(includes header), 5 columns and no null fields(which is a good sign for our analysis 🙂)"
},
{
"code": null,
"e": 3228,
"s": 3119,
"text": "Let’s have a look at the statistical summary about our dataset ( for numeric values) using describe() method"
},
{
"code": null,
"e": 3244,
"s": 3228,
"text": "Data Cleaning :"
},
{
"code": null,
"e": 3770,
"s": 3244,
"text": "Cleaning up data is the first and most important step, as it ensures the quality of the data is met to prepare data for visualisation. From above dataset after thorough check we see that ‘number’ column(number of forest fires reported) which is of float type has values in decimal point such as 18.566, 14.59, 11.068 ... That means this value is not rounded and it doesn't make any sense to the number of forest fires reported . So let’s clean up this data using round function and store the data back to our main dataframe ."
},
{
"code": null,
"e": 3824,
"s": 3770,
"text": "First let’s apply round() function for sample data..."
},
{
"code": null,
"e": 3833,
"s": 3824,
"text": "Before :"
},
{
"code": null,
"e": 3841,
"s": 3833,
"text": "After :"
},
{
"code": null,
"e": 3904,
"s": 3841,
"text": "Now we will apply round() method to entire dataset using numpy"
},
{
"code": null,
"e": 3963,
"s": 3904,
"text": "Exercise 1 : To check minimum and maximum of ‘year’ column"
},
{
"code": null,
"e": 4068,
"s": 3963,
"text": "Exercise 2 : To find out total number of fires in ‘Acre’ state and visualising data based on each ‘year’"
},
{
"code": null,
"e": 4297,
"s": 4068,
"text": "Before jumping into this exercise, I would like to deep dive into an important concept called ‘Boolean Indexing’ in Pandas which will be of very much help when dealing with subsets of data based on the actual values of the data."
},
{
"code": null,
"e": 4316,
"s": 4297,
"text": "Boolean Indexing :"
},
{
"code": null,
"e": 4546,
"s": 4316,
"text": "Boolean indexing as the name suggests, is used when we want to extract subsets of data from the dataframe based on some conditions. We can also have multiple conditions which can be grouped in brackets and apply to the dataframe."
},
{
"code": null,
"e": 4693,
"s": 4546,
"text": "Let’s look at below example of how boolean indexing works in pandas. In our example, we’ll work with the dataframe of employees and their salary :"
},
{
"code": null,
"e": 4854,
"s": 4693,
"text": "import pandas as pddf = pd.DataFrame({'EmployeeName': ['John','Sam','Sara','Nick','Bob','Julie'], 'Salary':[5000,8000,7000,10000,3000,5000]})"
},
{
"code": null,
"e": 4990,
"s": 4854,
"text": "Let’s check which employee have a salary of 5000. First, we will perform a vectorised boolean operation that produces a boolean series:"
},
{
"code": null,
"e": 5025,
"s": 4990,
"text": "salary_bool = df['Salary'] == 5000"
},
{
"code": null,
"e": 5163,
"s": 5025,
"text": "Now, we can use this series to index the whole dataframe, leaving us with the rows that correspond only to employees whose salary is 5000"
},
{
"code": null,
"e": 5250,
"s": 5163,
"text": "salary_5000 = df[salary_bool] # that means it returns only those rows which are 'True'"
},
{
"code": null,
"e": 5370,
"s": 5250,
"text": "I hope now you have some idea how boolean indexing works..You can find more info about Boolean Indexing tutorial here.."
},
{
"code": null,
"e": 5481,
"s": 5370,
"text": "Now, let’s get started with our actual exercise i.e, to find the total number of forest fires in ‘Acre’ state:"
},
{
"code": null,
"e": 5688,
"s": 5481,
"text": "It’s clear from above output that total number of fires reported in ‘Acre’ state are 18463 . Yes, this is too much to understand for the first time :). So let me break this code and explain it step by step."
},
{
"code": null,
"e": 5803,
"s": 5688,
"text": "Step 1 : Let’s use boolean indexing to get only ‘Acre’ state subset and assign it to variable called ‘amazon_acre’"
},
{
"code": null,
"e": 5844,
"s": 5803,
"text": "amazon_acre = amazon['state'] == 'Acre' "
},
{
"code": null,
"e": 5952,
"s": 5844,
"text": "‘amazon_acre’ will generate a series for us which shows True and False for each row based on our condition."
},
{
"code": null,
"e": 6062,
"s": 5952,
"text": "Step 2: Let’s use this series to index the entire dataset and assign it to variable called ‘amazon_acre_data’"
},
{
"code": null,
"e": 6121,
"s": 6062,
"text": "amazon_acre_data = amazon[amazon_acre] # total 239 entries"
},
{
"code": null,
"e": 6189,
"s": 6121,
"text": "Step 3 : Next let’s display only ‘number’ column from above dataset"
},
{
"code": null,
"e": 6286,
"s": 6189,
"text": "amazon_acre_number = amazon_acre_data['number'] # this will display only ‘number’ column values."
},
{
"code": null,
"e": 6387,
"s": 6286,
"text": "Step 4 : Now we can use sum() function to amazon_acre_number variable to find total number of fires."
},
{
"code": null,
"e": 6600,
"s": 6387,
"text": "There you go.!! It’s always a best practice to break the code when we are experimenting the data for the first time. But, eventually to gain better programming skills we shall work on minimising the coding lines."
},
{
"code": null,
"e": 6693,
"s": 6600,
"text": "Now let’s use groupby() method on ‘year’ column and get total number of fires for each year."
},
{
"code": null,
"e": 6894,
"s": 6693,
"text": "Here in output, we see that ‘year’ is marked as index and ‘number’ as column. Just to make it more simple for visualising data, we can use reset_index() method to make index to be treated as a column."
},
{
"code": null,
"e": 6926,
"s": 6894,
"text": "Visualisation of above dataset:"
},
{
"code": null,
"e": 7217,
"s": 6926,
"text": "Matplotlib is python’s data visualisation library, which allows us to visualise the data and is very easy to get started for simple plots. Matplotlib consists of several plots like line, bar, scatter, histogram etc., I recommend you to explore the official Matplotlib webpage for more info."
},
{
"code": null,
"e": 7398,
"s": 7217,
"text": "Seaborn is python’s most popular statistical visualisation library which is built on top of Matplotlib. Check out seaborn official webpage for all different types of seaborn plots."
},
{
"code": null,
"e": 7478,
"s": 7398,
"text": "Let’s visualise ‘acre_fires_year’ dataset using matplotlib and seaborn(barplot)"
},
{
"code": null,
"e": 7577,
"s": 7478,
"text": "Note: plt.figure() creates a figure object, which we here used to customise the size of the chart."
},
{
"code": null,
"e": 7638,
"s": 7577,
"text": "Exercise 3 : To find out total number of fires in all states"
},
{
"code": null,
"e": 7722,
"s": 7638,
"text": "For this, let’s use groupby() on ‘state’ column and find out total number of fires."
},
{
"code": null,
"e": 7845,
"s": 7722,
"text": "It’s clear from above plot that most forest fires occurred in ‘Mato Grosso’, followed by ‘Paraiba’ and ‘Sao Paulo’ states."
},
{
"code": null,
"e": 7943,
"s": 7845,
"text": "Exercise 4 : To find out total number of fires in 2017 and visualising data based on each ‘month’"
},
{
"code": null,
"e": 8001,
"s": 7943,
"text": "Exercise 5 : To find out average number of fires occurred"
},
{
"code": null,
"e": 8083,
"s": 8001,
"text": "Exercise 6 : To find out the state names where fires occurred in ‘December’ month"
},
{
"code": null,
"e": 8256,
"s": 8083,
"text": "That’s all for this post... You should now have a good knowledge of what pandas, matplotlib and seaborn are and how to use them for data preparation and data visualisation."
}
] |
JavaScript Sleep() function?
|
With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and
Php we would call sleep(sec). Java has thread.sleep(), python has time.sleep() and GO has time.Sleep(2 * time.Second).
javascript doesn't have these kinds of sleep functions. But we should thank promises and async/await function in ES 2018. Because these features have helped us to use sleep() as easy as possible. Let's discuss it in a nutshell.
sleep(Time in ms).then(() => {
//// code
})
We can use the sleep function with then call back as shown above.
const work = async () => {
await sleep(Time in ms)
//code
}
work()
We can use the sleep function with async/await function as shown above.
In the following example, we have used the sleep() with async/await function. Here sleep function is accompanied with await to continue the proceedings. Initially the text in the async function "Hello Tutorix" is displayed once the function is started. Later on, the function is paused using sleep function for 3 seconds. Once the time period is completed, the text("Welcome to ........") following the sleep function is displayed. It is repeated until the loop terminates, meaning that in total the text is going to be repeated for 19 times as shown in the output.
<html>
<body>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function Tutor() {
document.write('Hello Toturix');
for (let i = 1; i <20 ; i++) {
await sleep(3000);
document.write( i +" "+"Welcome to tutorix" + " " + "</br>");
}
}
Tutor()
</script>
</body>
</html>
Hello Tutorix
// after 3 secs
1 Welcome to tutorix
// after 3sec...and the text will repeat until the loop terminates for every 3 sec
2 Welcome to tutorix
3 Welcome to tutorix
4 Welcome to tutorix
5 Welcome to tutorix
6 Welcome to tutorix
7 Welcome to tutorix
8 Welcome to tutorix
9 Welcome to tutorix
10 Welcome to tutorix
11 Welcome to tutorix
12 Welcome to tutorix
13 Welcome to tutorix
14 Welcome to tutorix
15 Welcome to tutorix
16 Welcome to tutorix
17 Welcome to tutorix
18 Welcome to tutorix
19 Welcome to tutorix
|
[
{
"code": null,
"e": 1315,
"s": 1062,
"text": "With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and\nPhp we would call sleep(sec). Java has thread.sleep(), python has time.sleep() and GO has time.Sleep(2 * time.Second)."
},
{
"code": null,
"e": 1543,
"s": 1315,
"text": "javascript doesn't have these kinds of sleep functions. But we should thank promises and async/await function in ES 2018. Because these features have helped us to use sleep() as easy as possible. Let's discuss it in a nutshell."
},
{
"code": null,
"e": 1587,
"s": 1543,
"text": "sleep(Time in ms).then(() => {\n//// code\n})"
},
{
"code": null,
"e": 1653,
"s": 1587,
"text": "We can use the sleep function with then call back as shown above."
},
{
"code": null,
"e": 1720,
"s": 1653,
"text": "const work = async () => {\nawait sleep(Time in ms)\n//code\n}\nwork()"
},
{
"code": null,
"e": 1792,
"s": 1720,
"text": "We can use the sleep function with async/await function as shown above."
},
{
"code": null,
"e": 2359,
"s": 1792,
"text": "In the following example, we have used the sleep() with async/await function. Here sleep function is accompanied with await to continue the proceedings. Initially the text in the async function \"Hello Tutorix\" is displayed once the function is started. Later on, the function is paused using sleep function for 3 seconds. Once the time period is completed, the text(\"Welcome to ........\") following the sleep function is displayed. It is repeated until the loop terminates, meaning that in total the text is going to be repeated for 19 times as shown in the output. "
},
{
"code": null,
"e": 2734,
"s": 2359,
"text": "<html>\n<body>\n<script>\n function sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n async function Tutor() {\n document.write('Hello Toturix');\n for (let i = 1; i <20 ; i++) { \n await sleep(3000);\n document.write( i +\" \"+\"Welcome to tutorix\" + \" \" + \"</br>\");\n }\n }\n Tutor()\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3256,
"s": 2734,
"text": "Hello Tutorix\n// after 3 secs\n1 Welcome to tutorix\n// after 3sec...and the text will repeat until the loop terminates for every 3 sec\n2 Welcome to tutorix\n3 Welcome to tutorix\n4 Welcome to tutorix\n5 Welcome to tutorix\n6 Welcome to tutorix\n7 Welcome to tutorix\n8 Welcome to tutorix\n9 Welcome to tutorix\n10 Welcome to tutorix\n11 Welcome to tutorix\n12 Welcome to tutorix\n13 Welcome to tutorix\n14 Welcome to tutorix\n15 Welcome to tutorix\n16 Welcome to tutorix\n17 Welcome to tutorix\n18 Welcome to tutorix\n19 Welcome to tutorix"
}
] |
Java Program to convert java.util.Date to LocalDate
|
At first set the date with java.util.Date −
java.util.Date date = new Date();
Now, convert the date to LocalDate −
Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("LocalDate = "+LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate());
Live Demo
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
java.util.Date date = new Date();
System.out.println("Date = "+date);
Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("LocalDate = "+LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate());
}
}
Date = Thu Apr 18 23:51:06 IST 2019
LocalDate = 2019-04-18
|
[
{
"code": null,
"e": 1106,
"s": 1062,
"text": "At first set the date with java.util.Date −"
},
{
"code": null,
"e": 1140,
"s": 1106,
"text": "java.util.Date date = new Date();"
},
{
"code": null,
"e": 1177,
"s": 1140,
"text": "Now, convert the date to LocalDate −"
},
{
"code": null,
"e": 1340,
"s": 1177,
"text": "Instant instant = Instant.ofEpochMilli(date.getTime());\nSystem.out.println(\"LocalDate = \"+LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate());"
},
{
"code": null,
"e": 1351,
"s": 1340,
"text": " Live Demo"
},
{
"code": null,
"e": 1785,
"s": 1351,
"text": "import java.time.Instant;\nimport java.time.LocalDateTime;\nimport java.time.ZoneId;\nimport java.util.Date;\npublic class Demo {\n public static void main(String[] args) {\n java.util.Date date = new Date();\n System.out.println(\"Date = \"+date);\n Instant instant = Instant.ofEpochMilli(date.getTime());\n System.out.println(\"LocalDate = \"+LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate());\n }\n}"
},
{
"code": null,
"e": 1844,
"s": 1785,
"text": "Date = Thu Apr 18 23:51:06 IST 2019\nLocalDate = 2019-04-18"
}
] |
Yii - Error Handling
|
Yii includes a built-in error handler. The Yii error handler does the following −
Converts all non-fatal PHP errors into catchable exceptions.
Displays all errors and exceptions with a detailed call stack.
Supports different error formats.
Supports using a controller action to display errors.
To disable the error handler, you should define the YII_ENABLE_ERROR_HANDLER constant to be false in the entry script. The error handler is registered as an application component.
Step 1 − You can configure it in the following way.
return [
'components' => [
'errorHandler' => [
'maxSourceLines' => 10,
],
],
];
The above configuration sets the number of source code lines to be displayed to 10. The error handler converts all non-fatal PHP errors into catchable exceptions.
Step 2 − Add a new function called actionShowError() to the SiteController.
public function actionShowError() {
try {
5/0;
} catch (ErrorException $e) {
Yii::warning("Ooops...division by zero.");
}
// execution continues...
}
Step 3 − Go to the URL http://localhost:8080/index.php?r=site/show-error. You will see a warning message.
If you want to show the user that his request is invalid, you may throw the yii\web\NotFoundHttpException.
Step 4 − Modify the actionShowError() function.
public function actionShowError() {
throw new NotFoundHttpException("Something unexpected happened");
}
Step 5 − Type the address http://localhost:8080/index.php?r=site/show-error in the address bar. You will see the following HTTP error.
When the YII_DEBUG constant is true, the error handler will display errors with a detailed call stack. When the constant is false, only the error message will be displayed. By default, the error handler shows errors using these views −
@yii/views/errorHandler/exception.php − the view file is used when errors should be displayed with call stack information.
@yii/views/errorHandler/exception.php − the view file is used when errors should be displayed with call stack information.
@yii/views/errorHandler/error.php − the view file is used when errors should be displayed without call stack information.
@yii/views/errorHandler/error.php − the view file is used when errors should be displayed without call stack information.
You can use dedicated error actions to customize the error display.
Step 6 − Modify the errorHandler application component in the config/web.php file.
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this
//is required by cookie validation
'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
//other components...
'db' => require(__DIR__ . '/db.php'),
],
'modules' => [
'hello' => [
'class' => 'app\modules\hello\Hello',
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
?>
The above configuration defines that when an error needs to be displayed without the call stack, the site/error action will be executed.
Step 7 − Modify the actions() method of the SiteController.
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
The above code defines, that when an error occurs, the error view will be rendered.
Step 8 − Create a file called error.php under the views/site directory.
<?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
use yii\helpers\Html;
$this->title = $name;
?>
<div class = "site-error">
<h2>customized error</h2>
<h1><?= Html::encode($this->title) ?></h1>
<div class = "alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
</div>
Step 9 − Go to the address http://localhost:8080/index.php?r=site/show-error, you will see the customized error view.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2915,
"s": 2833,
"text": "Yii includes a built-in error handler. The Yii error handler does the following −"
},
{
"code": null,
"e": 2976,
"s": 2915,
"text": "Converts all non-fatal PHP errors into catchable exceptions."
},
{
"code": null,
"e": 3039,
"s": 2976,
"text": "Displays all errors and exceptions with a detailed call stack."
},
{
"code": null,
"e": 3073,
"s": 3039,
"text": "Supports different error formats."
},
{
"code": null,
"e": 3127,
"s": 3073,
"text": "Supports using a controller action to display errors."
},
{
"code": null,
"e": 3307,
"s": 3127,
"text": "To disable the error handler, you should define the YII_ENABLE_ERROR_HANDLER constant to be false in the entry script. The error handler is registered as an application component."
},
{
"code": null,
"e": 3359,
"s": 3307,
"text": "Step 1 − You can configure it in the following way."
},
{
"code": null,
"e": 3466,
"s": 3359,
"text": "return [\n 'components' => [\n 'errorHandler' => [\n 'maxSourceLines' => 10,\n ],\n ],\n];"
},
{
"code": null,
"e": 3629,
"s": 3466,
"text": "The above configuration sets the number of source code lines to be displayed to 10. The error handler converts all non-fatal PHP errors into catchable exceptions."
},
{
"code": null,
"e": 3705,
"s": 3629,
"text": "Step 2 − Add a new function called actionShowError() to the SiteController."
},
{
"code": null,
"e": 3879,
"s": 3705,
"text": "public function actionShowError() {\n try {\n 5/0;\n } catch (ErrorException $e) {\n Yii::warning(\"Ooops...division by zero.\");\n }\n // execution continues...\n}"
},
{
"code": null,
"e": 3985,
"s": 3879,
"text": "Step 3 − Go to the URL http://localhost:8080/index.php?r=site/show-error. You will see a warning message."
},
{
"code": null,
"e": 4092,
"s": 3985,
"text": "If you want to show the user that his request is invalid, you may throw the yii\\web\\NotFoundHttpException."
},
{
"code": null,
"e": 4140,
"s": 4092,
"text": "Step 4 − Modify the actionShowError() function."
},
{
"code": null,
"e": 4247,
"s": 4140,
"text": "public function actionShowError() {\n throw new NotFoundHttpException(\"Something unexpected happened\");\n}"
},
{
"code": null,
"e": 4382,
"s": 4247,
"text": "Step 5 − Type the address http://localhost:8080/index.php?r=site/show-error in the address bar. You will see the following HTTP error."
},
{
"code": null,
"e": 4618,
"s": 4382,
"text": "When the YII_DEBUG constant is true, the error handler will display errors with a detailed call stack. When the constant is false, only the error message will be displayed. By default, the error handler shows errors using these views −"
},
{
"code": null,
"e": 4741,
"s": 4618,
"text": "@yii/views/errorHandler/exception.php − the view file is used when errors should be displayed with call stack information."
},
{
"code": null,
"e": 4864,
"s": 4741,
"text": "@yii/views/errorHandler/exception.php − the view file is used when errors should be displayed with call stack information."
},
{
"code": null,
"e": 4986,
"s": 4864,
"text": "@yii/views/errorHandler/error.php − the view file is used when errors should be displayed without call stack information."
},
{
"code": null,
"e": 5108,
"s": 4986,
"text": "@yii/views/errorHandler/error.php − the view file is used when errors should be displayed without call stack information."
},
{
"code": null,
"e": 5176,
"s": 5108,
"text": "You can use dedicated error actions to customize the error display."
},
{
"code": null,
"e": 5259,
"s": 5176,
"text": "Step 6 − Modify the errorHandler application component in the config/web.php file."
},
{
"code": null,
"e": 6560,
"s": 5259,
"text": "<?php\n $params = require(__DIR__ . '/params.php');\n $config = [\n 'id' => 'basic',\n 'basePath' => dirname(__DIR__),\n 'bootstrap' => ['log'],\n 'components' => [\n 'request' => [\n // !!! insert a secret key in the following (if it is empty) - this\n //is required by cookie validation\n 'cookieValidationKey' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',\n ],\n 'cache' => [\n 'class' => 'yii\\caching\\FileCache',\n ],\n 'user' => [\n 'identityClass' => 'app\\models\\User',\n 'enableAutoLogin' => true,\n ],\n 'errorHandler' => [\n 'errorAction' => 'site/error',\n ],\n //other components...\n 'db' => require(__DIR__ . '/db.php'),\n ],\n 'modules' => [\n 'hello' => [\n 'class' => 'app\\modules\\hello\\Hello',\n ],\n ],\n 'params' => $params,\n ];\n if (YII_ENV_DEV) {\n // configuration adjustments for 'dev' environment\n $config['bootstrap'][] = 'debug';\n $config['modules']['debug'] = [\n 'class' => 'yii\\debug\\Module',\n ];\n $config['bootstrap'][] = 'gii';\n $config['modules']['gii'] = [\n 'class' => 'yii\\gii\\Module',\n ];\n }\n return $config;\n?>"
},
{
"code": null,
"e": 6697,
"s": 6560,
"text": "The above configuration defines that when an error needs to be displayed without the call stack, the site/error action will be executed."
},
{
"code": null,
"e": 6757,
"s": 6697,
"text": "Step 7 − Modify the actions() method of the SiteController."
},
{
"code": null,
"e": 6876,
"s": 6757,
"text": "public function actions() {\n return [\n 'error' => [\n 'class' => 'yii\\web\\ErrorAction',\n ],\n ];\n}"
},
{
"code": null,
"e": 6960,
"s": 6876,
"text": "The above code defines, that when an error occurs, the error view will be rendered."
},
{
"code": null,
"e": 7032,
"s": 6960,
"text": "Step 8 − Create a file called error.php under the views/site directory."
},
{
"code": null,
"e": 7612,
"s": 7032,
"text": "<?php\n /* @var $this yii\\web\\View */\n /* @var $name string */\n /* @var $message string */\n /* @var $exception Exception */\n use yii\\helpers\\Html;\n $this->title = $name;\n?>\n\n<div class = \"site-error\">\n <h2>customized error</h2>\n <h1><?= Html::encode($this->title) ?></h1>\n \n <div class = \"alert alert-danger\">\n <?= nl2br(Html::encode($message)) ?>\n </div>\n \n <p>\n The above error occurred while the Web server was processing your request.\n </p>\n \n <p>\n Please contact us if you think this is a server error. Thank you.\n </p>\n</div>"
},
{
"code": null,
"e": 7730,
"s": 7612,
"text": "Step 9 − Go to the address http://localhost:8080/index.php?r=site/show-error, you will see the customized error view."
},
{
"code": null,
"e": 7737,
"s": 7730,
"text": " Print"
},
{
"code": null,
"e": 7748,
"s": 7737,
"text": " Add Notes"
}
] |
How to compare two dates in String format in Java?
|
The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string.
One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object.
To parse/convert a string as a Date object Instantiate this class by passing desired format string.
Parse the date string using the parse() method.
The util.Date class represents a specific instant time This class provides various methods such as before(), after() and, equals() to compare two dates
Once you create date objects from strings you can compare them using either of these methods as shown below −
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String args[])throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM");
String dateStr1 = "2007-11-25";
String dateStr2 = "1999-9-12";
//Parsing the given String to Date object
Date date1 = formatter.parse(dateStr1);
Date date2 = formatter.parse(dateStr2);
Boolean bool1 = date1.after(date2);
Boolean bool2 = date1.before(date2);
Boolean bool3 = date1.equals(date2);
if(bool1){
System.out.println(dateStr1+" is after "+dateStr2);
}else if(bool2){
System.out.println(dateStr1+" is before "+dateStr2);
}else if(bool3){
System.out.println(dateStr1+" is equals to "+dateStr2);
}
}
}
2007-11-25 is after 1999-9-12
2007-11-25 is after 1999-9-12
The parse() method of the LocalDate class accepts a String value representing a date and returns a LocalDate object.
Live Demo
import java.time.LocalDate;
public class Test {
public static void main(String args[]){
String dateStr1 = "2007-11-25";
String dateStr2 = "1999-9-12";
LocalDate date1 = LocalDate.parse(dateStr1);
LocalDate date2 = LocalDate.parse(dateStr1);
Boolean bool1 = date1.isAfter(date2);
Boolean bool2 = date1.isBefore(date2);
Boolean bool3 = date1.isEqual(date2);
if(bool1){
System.out.println(dateStr1+" is after "+dateStr2);
}else if(bool2){
System.out.println(dateStr1+" is before "+dateStr2);
}else if(bool3){
System.out.println(dateStr1+" is equal to "+dateStr2);
}
}
}
2007-11-25 is equal to 1999-9-12
2007-11-25 is equal to 1999-9-12
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string."
},
{
"code": null,
"e": 1300,
"s": 1164,
"text": "One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. "
},
{
"code": null,
"e": 1400,
"s": 1300,
"text": "To parse/convert a string as a Date object Instantiate this class by passing desired format string."
},
{
"code": null,
"e": 1448,
"s": 1400,
"text": "Parse the date string using the parse() method."
},
{
"code": null,
"e": 1600,
"s": 1448,
"text": "The util.Date class represents a specific instant time This class provides various methods such as before(), after() and, equals() to compare two dates"
},
{
"code": null,
"e": 1710,
"s": 1600,
"text": "Once you create date objects from strings you can compare them using either of these methods as shown below −"
},
{
"code": null,
"e": 1720,
"s": 1710,
"text": "Live Demo"
},
{
"code": null,
"e": 2595,
"s": 1720,
"text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class Demo {\n public static void main(String args[])throws ParseException { \n SimpleDateFormat formatter = new SimpleDateFormat(\"yyyy-dd-MM\"); \n String dateStr1 = \"2007-11-25\";\n String dateStr2 = \"1999-9-12\";\n //Parsing the given String to Date object\n Date date1 = formatter.parse(dateStr1); \n Date date2 = formatter.parse(dateStr2); \n Boolean bool1 = date1.after(date2); \n Boolean bool2 = date1.before(date2);\n Boolean bool3 = date1.equals(date2);\n if(bool1){\n System.out.println(dateStr1+\" is after \"+dateStr2);\n }else if(bool2){\n System.out.println(dateStr1+\" is before \"+dateStr2);\n }else if(bool3){\n System.out.println(dateStr1+\" is equals to \"+dateStr2);\n }\n }\n}"
},
{
"code": null,
"e": 2625,
"s": 2595,
"text": "2007-11-25 is after 1999-9-12"
},
{
"code": null,
"e": 2655,
"s": 2625,
"text": "2007-11-25 is after 1999-9-12"
},
{
"code": null,
"e": 2772,
"s": 2655,
"text": "The parse() method of the LocalDate class accepts a String value representing a date and returns a LocalDate object."
},
{
"code": null,
"e": 2782,
"s": 2772,
"text": "Live Demo"
},
{
"code": null,
"e": 3457,
"s": 2782,
"text": "import java.time.LocalDate;\npublic class Test {\n public static void main(String args[]){\n String dateStr1 = \"2007-11-25\";\n String dateStr2 = \"1999-9-12\";\n LocalDate date1 = LocalDate.parse(dateStr1);\n LocalDate date2 = LocalDate.parse(dateStr1);\n Boolean bool1 = date1.isAfter(date2); \n Boolean bool2 = date1.isBefore(date2);\n Boolean bool3 = date1.isEqual(date2);\n if(bool1){\n System.out.println(dateStr1+\" is after \"+dateStr2);\n }else if(bool2){\n System.out.println(dateStr1+\" is before \"+dateStr2);\n }else if(bool3){\n System.out.println(dateStr1+\" is equal to \"+dateStr2);\n }\n }\n}"
},
{
"code": null,
"e": 3490,
"s": 3457,
"text": "2007-11-25 is equal to 1999-9-12"
},
{
"code": null,
"e": 3523,
"s": 3490,
"text": "2007-11-25 is equal to 1999-9-12"
}
] |
Java Program to adjust LocalDate to last Day of Month with TemporalAdjusters class
|
Let us first set a date:
LocalDate localDate = LocalDate.of(2019, Month.JUNE, 15)
Now, adjust LocalDate to last Day of month;
LocalDate day = localDate.with(TemporalAdjusters.lastDayOfMonth());
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
public class Demo {
public static void main(String[] args) {
LocalDate localDate = LocalDate.of(2019, Month.JUNE, 15);
System.out.println("Current Date = "+localDate);
System.out.println("Current Month = "+localDate.getMonth());
LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());
System.out.println("First day of month = "+day);
day = localDate.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("Last day of month = "+day);
day = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println("First day of next month = "+day);
}
}
Current Date = 2019-06-15
Current Month = JUNE
First day of month = 2019-06-01
Last day of month = 2019-06-30
First day of next month = 2019-07-01
|
[
{
"code": null,
"e": 1087,
"s": 1062,
"text": "Let us first set a date:"
},
{
"code": null,
"e": 1144,
"s": 1087,
"text": "LocalDate localDate = LocalDate.of(2019, Month.JUNE, 15)"
},
{
"code": null,
"e": 1188,
"s": 1144,
"text": "Now, adjust LocalDate to last Day of month;"
},
{
"code": null,
"e": 1256,
"s": 1188,
"text": "LocalDate day = localDate.with(TemporalAdjusters.lastDayOfMonth());"
},
{
"code": null,
"e": 1987,
"s": 1256,
"text": "import java.time.LocalDate;\nimport java.time.Month;\nimport java.time.temporal.TemporalAdjusters;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate localDate = LocalDate.of(2019, Month.JUNE, 15);\n System.out.println(\"Current Date = \"+localDate);\n System.out.println(\"Current Month = \"+localDate.getMonth());\n LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());\n System.out.println(\"First day of month = \"+day);\n day = localDate.with(TemporalAdjusters.lastDayOfMonth());\n System.out.println(\"Last day of month = \"+day);\n day = localDate.with(TemporalAdjusters.firstDayOfNextMonth());\n System.out.println(\"First day of next month = \"+day);\n }\n}"
},
{
"code": null,
"e": 2134,
"s": 1987,
"text": "Current Date = 2019-06-15\nCurrent Month = JUNE\nFirst day of month = 2019-06-01\nLast day of month = 2019-06-30\nFirst day of next month = 2019-07-01"
}
] |
How to center a JLabel in a JPanel with GridBagLayout in Java?
|
Center a component in a JPanel with GridBagLayout. Let us first create a JFrame and JPanel inside it -
JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();
Now, we will add our components −
JLabel label = new JLabel("Demo Label (Centered)");
label.setForeground(Color.white);
JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");
Set the layout −
panel.setLayout(new GridBagLayout());
The following is an example to center a label in a panel with GridBagLayout −
package my;
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo Frame");
JPanel panel = new JPanel();
JLabel label = new JLabel("Demo Label (Centered)");
label.setForeground(Color.white);
JCheckBox checkBox = new JCheckBox("Checkbox (Centered)");
panel.setLayout(new GridBagLayout());
panel.add(label);
panel.add(checkBox);
panel.setBackground(Color.blue);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(600, 400);
frame.setVisible(true);
}
}
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "Center a component in a JPanel with GridBagLayout. Let us first create a JFrame and JPanel inside it -"
},
{
"code": null,
"e": 1235,
"s": 1165,
"text": "JFrame frame = new JFrame(\"Demo Frame\");\nJPanel panel = new JPanel();"
},
{
"code": null,
"e": 1269,
"s": 1235,
"text": "Now, we will add our components −"
},
{
"code": null,
"e": 1414,
"s": 1269,
"text": "JLabel label = new JLabel(\"Demo Label (Centered)\");\nlabel.setForeground(Color.white);\nJCheckBox checkBox = new JCheckBox(\"Checkbox (Centered)\");"
},
{
"code": null,
"e": 1431,
"s": 1414,
"text": "Set the layout −"
},
{
"code": null,
"e": 1469,
"s": 1431,
"text": "panel.setLayout(new GridBagLayout());"
},
{
"code": null,
"e": 1547,
"s": 1469,
"text": "The following is an example to center a label in a panel with GridBagLayout −"
},
{
"code": null,
"e": 2369,
"s": 1547,
"text": "package my;\nimport java.awt.Color;\nimport java.awt.GridBagLayout;\nimport javax.swing.JCheckBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Demo Frame\");\n JPanel panel = new JPanel();\n JLabel label = new JLabel(\"Demo Label (Centered)\");\n label.setForeground(Color.white);\n JCheckBox checkBox = new JCheckBox(\"Checkbox (Centered)\");\n panel.setLayout(new GridBagLayout());\n panel.add(label);\n panel.add(checkBox);\n panel.setBackground(Color.blue);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.add(panel);\n frame.setSize(600, 400);\n frame.setVisible(true);\n }\n}"
}
] |
Plot Arrows Between Points in a Graph in R Programming - arrows() Function - GeeksforGeeks
|
25 Jun, 2020
arrows() function in R Language is used to create arrows between the points on the graph specified.
Syntax: arrows(x0, y0, x1, y1, length)
Parameters:x0: represents x-coordinate of point from which to draw the arrowy0: represents y-coordinate of point from which to draw the arrowx1: represents x-coordinate of point to which the arrow is drawny1: represents y-coordinate of point to which the arrow is drawnlength: represents length of the edge of the arrow head (in inches)
Example 1:
# Specifying pointsx0 <- 1y0 <- 1x1 <- 5y1 <- 5x <- c(x0, x1)y <- c(y0, y1) # Output to be present as PNG filepng(file = "arrows1GFG.png") # Create plot graphplot(x, y, main = "Arrows Function") # Create arrow between the pointsarrows(x0, y0, x1, y1) # Saving the filedev.off()
Output:
Example 2:
# Specifying pointsx <- runif(10, 0, 1)y <- runif(10, 1, 5) # Output to be present as PNG filepng(file = "arrows2GFG.png") # Create plot graphplot(x, y, main = "Arrows Function") # Create arrow between the pointss <- seq(length(x) - 1)arrows(x[s], y[s], x[s + 1], y[s + 1]) # Saving the filedev.off()
Output:
R Plot-Function
R Language
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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
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?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 24951,
"s": 24851,
"text": "arrows() function in R Language is used to create arrows between the points on the graph specified."
},
{
"code": null,
"e": 24990,
"s": 24951,
"text": "Syntax: arrows(x0, y0, x1, y1, length)"
},
{
"code": null,
"e": 25327,
"s": 24990,
"text": "Parameters:x0: represents x-coordinate of point from which to draw the arrowy0: represents y-coordinate of point from which to draw the arrowx1: represents x-coordinate of point to which the arrow is drawny1: represents y-coordinate of point to which the arrow is drawnlength: represents length of the edge of the arrow head (in inches)"
},
{
"code": null,
"e": 25338,
"s": 25327,
"text": "Example 1:"
},
{
"code": "# Specifying pointsx0 <- 1y0 <- 1x1 <- 5y1 <- 5x <- c(x0, x1)y <- c(y0, y1) # Output to be present as PNG filepng(file = \"arrows1GFG.png\") # Create plot graphplot(x, y, main = \"Arrows Function\") # Create arrow between the pointsarrows(x0, y0, x1, y1) # Saving the filedev.off()",
"e": 25620,
"s": 25338,
"text": null
},
{
"code": null,
"e": 25628,
"s": 25620,
"text": "Output:"
},
{
"code": null,
"e": 25639,
"s": 25628,
"text": "Example 2:"
},
{
"code": "# Specifying pointsx <- runif(10, 0, 1)y <- runif(10, 1, 5) # Output to be present as PNG filepng(file = \"arrows2GFG.png\") # Create plot graphplot(x, y, main = \"Arrows Function\") # Create arrow between the pointss <- seq(length(x) - 1)arrows(x[s], y[s], x[s + 1], y[s + 1]) # Saving the filedev.off()",
"e": 25944,
"s": 25639,
"text": null
},
{
"code": null,
"e": 25952,
"s": 25944,
"text": "Output:"
},
{
"code": null,
"e": 25968,
"s": 25952,
"text": "R Plot-Function"
},
{
"code": null,
"e": 25979,
"s": 25968,
"text": "R Language"
},
{
"code": null,
"e": 26077,
"s": 25979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26086,
"s": 26077,
"text": "Comments"
},
{
"code": null,
"e": 26099,
"s": 26086,
"text": "Old Comments"
},
{
"code": null,
"e": 26151,
"s": 26099,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26189,
"s": 26151,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26224,
"s": 26189,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26282,
"s": 26224,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26325,
"s": 26282,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26374,
"s": 26325,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26424,
"s": 26374,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26441,
"s": 26424,
"text": "R - if statement"
},
{
"code": null,
"e": 26478,
"s": 26441,
"text": "How to import an Excel File into R ?"
}
] |
How to validate if input in input field has integer number only using express-validator ?
|
08 Apr, 2022
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only integer numbers are allowed i.e. there not allowed any strings, special characters, or anything other than integer number. We can also validate these input fields to accept only integer numbers using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on the validation isInt() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate a input field to only allow integer numbers.
Filename – index.js
javascript
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateYearOfBirth } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validateYearOfBirth], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {name, qual, ybirth} = req.body // New record await repo.create({ 'Name':name, 'Last Qualification':qual, 'Year of birth':ybirth }) res.send('<strong>Information saved successfully!</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information// provided via signup form store in// this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show the form to submit the data.
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Vinit singh' for='name'> </div> <div> <div> <label class='label' id='qual'> Last Qulification </label> </div> <input class='input' type='text' name='qual' placeholder='Ex-B.Tech' for='qual'> </div> <div> <div> <label class='label' id='ybirthirate'> Year of Birth </label> </div> <input class='input' type='text' name='ybirth' placeholder='Ex-1997' for='ybirth'> <p class="help is-danger"> ${getError(errors, 'ybirth')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow the integer numbers).
javascript
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateYearOfBirth : check('ybirth') // To delete leading and trailing space .trim() // Validate interest rate to accept // only Integer number .isInt() // Custom message .withMessage('Must be a integer number') }
Filename – package.json
Package.json file
Database:
database
Output:
Attempt to submit form data when date of year input field is not a valid integer number
Attempt to submit form data when date of year input field is not a valid integer number
Response when attempt to submit form data where date of year input field is not a valid integer number
Attempt to submit form data when date of year input field is a valid integer number
Response when attempt to submit form data where date of year input field is a valid integer number
Database after successful form submission:
Database after successful submission of form
Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content.
rkbhola5
Node.js-Misc
Node.js
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": "\n08 Apr, 2022"
},
{
"code": null,
"e": 509,
"s": 28,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only integer numbers are allowed i.e. there not allowed any strings, special characters, or anything other than integer number. We can also validate these input fields to accept only integer numbers using express-validator middleware."
},
{
"code": null,
"e": 547,
"s": 509,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 577,
"s": 547,
"text": "npm install express-validator"
},
{
"code": null,
"e": 632,
"s": 577,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 670,
"s": 632,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 731,
"s": 670,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 840,
"s": 731,
"text": "Validate input by validateInputField: check(input field name) and chain on the validation isInt() with ‘ . ‘"
},
{
"code": null,
"e": 942,
"s": 840,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 1035,
"s": 942,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 1108,
"s": 1035,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 1184,
"s": 1108,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 1350,
"s": 1184,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 1445,
"s": 1350,
"text": "Example: This example illustrates how to validate a input field to only allow integer numbers."
},
{
"code": null,
"e": 1465,
"s": 1445,
"text": "Filename – index.js"
},
{
"code": null,
"e": 1476,
"s": 1465,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateYearOfBirth } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validateYearOfBirth], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {name, qual, ybirth} = req.body // New record await repo.create({ 'Name':name, 'Last Qualification':qual, 'Year of birth':ybirth }) res.send('<strong>Information saved successfully!</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 2534,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2642,
"s": 2534,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 2653,
"s": 2642,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information// provided via signup form store in// this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 3795,
"s": 2653,
"text": null
},
{
"code": null,
"e": 3877,
"s": 3795,
"text": "Filename – form.js: This file contains logic to show the form to submit the data."
},
{
"code": null,
"e": 3888,
"s": 3877,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Vinit singh' for='name'> </div> <div> <div> <label class='label' id='qual'> Last Qulification </label> </div> <input class='input' type='text' name='qual' placeholder='Ex-B.Tech' for='qual'> </div> <div> <div> <label class='label' id='ybirthirate'> Year of Birth </label> </div> <input class='input' type='text' name='ybirth' placeholder='Ex-1997' for='ybirth'> <p class=\"help is-danger\"> ${getError(errors, 'ybirth')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}",
"e": 5531,
"s": 3888,
"text": null
},
{
"code": null,
"e": 5667,
"s": 5531,
"text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to only allow the integer numbers)."
},
{
"code": null,
"e": 5678,
"s": 5667,
"text": "javascript"
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateYearOfBirth : check('ybirth') // To delete leading and trailing space .trim() // Validate interest rate to accept // only Integer number .isInt() // Custom message .withMessage('Must be a integer number') }",
"e": 6021,
"s": 5678,
"text": null
},
{
"code": null,
"e": 6045,
"s": 6021,
"text": "Filename – package.json"
},
{
"code": null,
"e": 6063,
"s": 6045,
"text": "Package.json file"
},
{
"code": null,
"e": 6073,
"s": 6063,
"text": "Database:"
},
{
"code": null,
"e": 6082,
"s": 6073,
"text": "database"
},
{
"code": null,
"e": 6090,
"s": 6082,
"text": "Output:"
},
{
"code": null,
"e": 6178,
"s": 6090,
"text": "Attempt to submit form data when date of year input field is not a valid integer number"
},
{
"code": null,
"e": 6266,
"s": 6178,
"text": "Attempt to submit form data when date of year input field is not a valid integer number"
},
{
"code": null,
"e": 6369,
"s": 6266,
"text": "Response when attempt to submit form data where date of year input field is not a valid integer number"
},
{
"code": null,
"e": 6453,
"s": 6369,
"text": "Attempt to submit form data when date of year input field is a valid integer number"
},
{
"code": null,
"e": 6552,
"s": 6453,
"text": "Response when attempt to submit form data where date of year input field is a valid integer number"
},
{
"code": null,
"e": 6595,
"s": 6552,
"text": "Database after successful form submission:"
},
{
"code": null,
"e": 6640,
"s": 6595,
"text": "Database after successful submission of form"
},
{
"code": null,
"e": 6736,
"s": 6640,
"text": "Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content."
},
{
"code": null,
"e": 6745,
"s": 6736,
"text": "rkbhola5"
},
{
"code": null,
"e": 6758,
"s": 6745,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 6766,
"s": 6758,
"text": "Node.js"
},
{
"code": null,
"e": 6783,
"s": 6766,
"text": "Web Technologies"
}
] |
Print system time in C++ (3 different ways)
|
10 Dec, 2018
First MethodPrinting current date and time using time()
Second Method
// CPP program to print current date and time// using time and ctime.#include <stdio.h>#include <stdlib.h>#include <time.h> int main(){ // declaring argument of time() time_t my_time = time(NULL); // ctime() used to give the present time printf("%s", ctime(&my_time)); return 0;}
Output:
It will show the current day, date and localtime,
in the format Day Month Date hh:mm:ss Year
Third MethodHere we have used chrono library to print current date and time . The chrono library is a flexible collection of types that tracks time with varying degrees of precision .The chrono library defines three main types as well as utility functions and common typedefs.-> clocks-> time points-> durations
Code to print current date, day and time .
// CPP program to print current date and time// using chronos.#include <chrono>#include <ctime>#include <iostream> using namespace std; int main(){ // Here system_clock is wall clock time from // the system-wide realtime clock auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); cout << ctime(&timenow) << endl;}
Output:
It will show the current day, date and localtime,
in the format Day Month Date hh:mm:ss Year
sanskar27jain
cpp-puzzle
date-time-program
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 108,
"s": 52,
"text": "First MethodPrinting current date and time using time()"
},
{
"code": null,
"e": 122,
"s": 108,
"text": "Second Method"
},
{
"code": "// CPP program to print current date and time// using time and ctime.#include <stdio.h>#include <stdlib.h>#include <time.h> int main(){ // declaring argument of time() time_t my_time = time(NULL); // ctime() used to give the present time printf(\"%s\", ctime(&my_time)); return 0;}",
"e": 420,
"s": 122,
"text": null
},
{
"code": null,
"e": 428,
"s": 420,
"text": "Output:"
},
{
"code": null,
"e": 523,
"s": 428,
"text": "It will show the current day, date and localtime, \nin the format Day Month Date hh:mm:ss Year\n"
},
{
"code": null,
"e": 835,
"s": 523,
"text": "Third MethodHere we have used chrono library to print current date and time . The chrono library is a flexible collection of types that tracks time with varying degrees of precision .The chrono library defines three main types as well as utility functions and common typedefs.-> clocks-> time points-> durations"
},
{
"code": null,
"e": 878,
"s": 835,
"text": "Code to print current date, day and time ."
},
{
"code": "// CPP program to print current date and time// using chronos.#include <chrono>#include <ctime>#include <iostream> using namespace std; int main(){ // Here system_clock is wall clock time from // the system-wide realtime clock auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); cout << ctime(&timenow) << endl;}",
"e": 1237,
"s": 878,
"text": null
},
{
"code": null,
"e": 1245,
"s": 1237,
"text": "Output:"
},
{
"code": null,
"e": 1340,
"s": 1245,
"text": "It will show the current day, date and localtime, \nin the format Day Month Date hh:mm:ss Year\n"
},
{
"code": null,
"e": 1354,
"s": 1340,
"text": "sanskar27jain"
},
{
"code": null,
"e": 1365,
"s": 1354,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 1383,
"s": 1365,
"text": "date-time-program"
},
{
"code": null,
"e": 1387,
"s": 1383,
"text": "C++"
},
{
"code": null,
"e": 1391,
"s": 1387,
"text": "CPP"
}
] |
Life Cycle of Java Applet
|
17 Dec, 2021
An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works on the client-side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server. The entire life cycle of an applet is managed by the Applet Container. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class. Applets are not stand-alone programs. They run either within a web browser or an applet viewer.
Applets generate Dynamic content
Applets work on the client-side
The response time is fast
We can view our Applet with the help of a standard applet viewer tool called Applet Viewer. Unlike the general executions and outputs of the java programs, applet execution does not begin at main() method, and the output of an applet window is not catered by System.out.println(). Rather it is handled with various Abstract Window Toolkit (AWT) methods, such as drawString().
Let us do see a hierarchy of Applet before landing up on stages in the lifecycle of the java applet that is as follows in the below media:
Stages in the Life Cycle of Java Applet
Initializing an Applet
Starting the Applet
Painting the Applet
Stopping the Applet
Destroying the Applet
Note: In order to implement the Applet we need to import awt package :
java.awt.applet.*;
Life Cycle of Applet
Step 1: Initialization
public void init()
There is no main method unlike our normal java programs. Every Applet will start it’s execution from init() method. It is executed only once
Step 2: Start
public void start()
After init() method start() method is invoked. Executed when the browser is maximized
Step 3: Paint
public void paint (Graphics g)
Paint method is used to display the content on the applet. We can create the objects or components to the applet or we can directly write a message on the applet. It will take Graphics class as a parameter.
Step 4: Stop
public void stop()
stop() method is used to stop the applet. It is executed when the browser is minimized.
Step 5: Destroy
public void destroy()
destroy() method is used to completely close the applet. It is executed when the applet is closed.
Implementation:
Implementation of java Applet can be done in two ways as follows:
Using HTML fileApplet viewer tool
Using HTML file
Applet viewer tool
Way 1: Using HTML file
HTML
<HTML><applet>code,width,height</applet></HTML>
Note: Drawbacks of using HTML file is you need a plugin (java plugin) to run it on your browser.
Way 2: Applet viewer tool
There are five methods of an Applet Life Cycle namely;
init()start()paint()stop()destroy()
init()
start()
paint()
stop()
destroy()
All these are available in AWT Package java.awt.applet.* and in order ton import paint (Graphics g) we do use java.awt.component package
Let’s understand each method in a detailed manner :
Method 1: init()
This is the first method to be called
Variables can be initialized here
This method can be called only once during the run time of the applet
It is invoked at the time of Initialization
Syntax:
public void init()
{
// To initialize objects
}
Method 2: start()
This method is called after init() method
start() method is used for starting the applet
It is also called to restart an applet after it has been stopped. i.e. to resume the applet
Syntax:
public void start()
{
// To start the applet code
}
Note: init() is called once i.e. when the first time an applet is loaded whereas start( ) is called each time an applet’s HTML document is displayed onscreen.
Method 3: paint()
void paint(Graphics g){ }
paint() method is used for painting any shapes like square, rectangle, trapeziums, etc.
paint() method has one parameter of type Graphics Class, this Graphics class enables the painting features in an applet.
This parameter will contain the graphics context, which is used whenever output for the applet is required.
Syntax:
public void paint(Graphics graphics)
{
// Any shape's code
}
Note: This is the only method among all the method mention above, which is parameterized.
Method 4: stop()
It is invoked every time the browser is stopped, minimized or when there is an abrupt failure in the application.
After stop()method called, we can also use start() method whenever we want.
This method mainly deals with clean up code.
The stop( ) method is called when a web browser leaves the HTML document containing the applet when it goes to another page, for example, when stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.
Syntax:
public void stop()
{
// To stop the applet code
}
Method 5: destroy()
destroy() method is used to destroy the application once we are done with our applet work. It can be invoked only once.
Once applet is destroyed we can’t start() the applet (we cannot restore the applet again)
The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory.
Syntax:
public void destroy()
{
// To destroy the applet
}
Note: The stop( ) method is always called before destroy( )
Syntax: Entire Applet Life Cycle
Java
Class AppletLifeCycle extends Applet{ public void init() { // Initializes objects } public void start() { // Starts the applet code } public void paint(Graphics graphics) { // Any shape's code } public void stop() { // Stops the applet code } public void destroy() { // Destroys the applet code }}
Implementation:
Example 1: In order to begin with Java Applet, let’s understand a simple code to make the Applet
Java
// Java Program to Make An Applet // Importing required classes from packagesimport java.awt.*;import java.awt.applet.*; // Class 1// Helper class extending Applet classpublic class AppletDemo extends Applet // Note: Every class used here is a derived class of applet,// Hence we use extends keyword Every applet is public{ public void init() { setBackground(Color.black); setForeground(Color.yellow); } public void paint(Graphics g) { g.drawString("Welcome", 100, 100); }} // Save file as AppletDemo.java in local machine
HTML
<html> <applet code = AppletDemo width = 400 height = 500> </applet> </html><!-- Save as Applet.html -->
Compilation methods:
Now in order to generate output, do follow below undersigned to compile and run the above file:
Method 1: Using command
Method 2: Include the applet code in our java program.
Methods are as follows:
Method 1: Using the command
Compilation:
c:> javac.AppletDemo.java
Execution:
Double click on Applet.html
This won't work on browser as we don't have the proper plugins.
Method 2: Include the applet code in our java program make sure to put this html applet code as comments as it is important evil as demonstrated below as follows:
Example
Java
// Java Program to Illustrate Insertion of HTML File in// Applet As Commands // Importing required classesimport java.applet.*;import java.awt.*; // Note: Insertion of HTM:L file as comments /* <applet code = AppletDemo width=400 height=500></applet>*/ // Java Program // Class extending Appletpublic class AppletDemo extends Applet { public void init() { setBackground(Color.black); setForeground(Color.yellow); } public void paint(Graphics g) { g.drawString("Welcome to Applets", 50, 50); }}
Compilation:
c:\> javac AppletDemo.java
Execution:
c:\> appletviewer AppletDemo.java
So this was all about the Life Cycle of Java Applet and methods used to run the applet ! Hope this helps.
germanshephered48
java-applet
Picked
TrueGeek-2021
Java
TrueGeek
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 533,
"s": 52,
"text": "An applet is a Java program that can be embedded into a web page. It runs inside the web browser and works on the client-side. An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server. The entire life cycle of an applet is managed by the Applet Container. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class. Applets are not stand-alone programs. They run either within a web browser or an applet viewer. "
},
{
"code": null,
"e": 566,
"s": 533,
"text": "Applets generate Dynamic content"
},
{
"code": null,
"e": 598,
"s": 566,
"text": "Applets work on the client-side"
},
{
"code": null,
"e": 624,
"s": 598,
"text": "The response time is fast"
},
{
"code": null,
"e": 1000,
"s": 624,
"text": "We can view our Applet with the help of a standard applet viewer tool called Applet Viewer. Unlike the general executions and outputs of the java programs, applet execution does not begin at main() method, and the output of an applet window is not catered by System.out.println(). Rather it is handled with various Abstract Window Toolkit (AWT) methods, such as drawString()."
},
{
"code": null,
"e": 1139,
"s": 1000,
"text": "Let us do see a hierarchy of Applet before landing up on stages in the lifecycle of the java applet that is as follows in the below media:"
},
{
"code": null,
"e": 1179,
"s": 1139,
"text": "Stages in the Life Cycle of Java Applet"
},
{
"code": null,
"e": 1202,
"s": 1179,
"text": "Initializing an Applet"
},
{
"code": null,
"e": 1222,
"s": 1202,
"text": "Starting the Applet"
},
{
"code": null,
"e": 1242,
"s": 1222,
"text": "Painting the Applet"
},
{
"code": null,
"e": 1262,
"s": 1242,
"text": "Stopping the Applet"
},
{
"code": null,
"e": 1284,
"s": 1262,
"text": "Destroying the Applet"
},
{
"code": null,
"e": 1355,
"s": 1284,
"text": "Note: In order to implement the Applet we need to import awt package :"
},
{
"code": null,
"e": 1374,
"s": 1355,
"text": "java.awt.applet.*;"
},
{
"code": null,
"e": 1395,
"s": 1374,
"text": "Life Cycle of Applet"
},
{
"code": null,
"e": 1418,
"s": 1395,
"text": "Step 1: Initialization"
},
{
"code": null,
"e": 1438,
"s": 1418,
"text": "public void init() "
},
{
"code": null,
"e": 1579,
"s": 1438,
"text": "There is no main method unlike our normal java programs. Every Applet will start it’s execution from init() method. It is executed only once"
},
{
"code": null,
"e": 1593,
"s": 1579,
"text": "Step 2: Start"
},
{
"code": null,
"e": 1613,
"s": 1593,
"text": "public void start()"
},
{
"code": null,
"e": 1699,
"s": 1613,
"text": "After init() method start() method is invoked. Executed when the browser is maximized"
},
{
"code": null,
"e": 1713,
"s": 1699,
"text": "Step 3: Paint"
},
{
"code": null,
"e": 1744,
"s": 1713,
"text": "public void paint (Graphics g)"
},
{
"code": null,
"e": 1951,
"s": 1744,
"text": "Paint method is used to display the content on the applet. We can create the objects or components to the applet or we can directly write a message on the applet. It will take Graphics class as a parameter."
},
{
"code": null,
"e": 1964,
"s": 1951,
"text": "Step 4: Stop"
},
{
"code": null,
"e": 1983,
"s": 1964,
"text": "public void stop()"
},
{
"code": null,
"e": 2071,
"s": 1983,
"text": "stop() method is used to stop the applet. It is executed when the browser is minimized."
},
{
"code": null,
"e": 2087,
"s": 2071,
"text": "Step 5: Destroy"
},
{
"code": null,
"e": 2109,
"s": 2087,
"text": "public void destroy()"
},
{
"code": null,
"e": 2208,
"s": 2109,
"text": "destroy() method is used to completely close the applet. It is executed when the applet is closed."
},
{
"code": null,
"e": 2224,
"s": 2208,
"text": "Implementation:"
},
{
"code": null,
"e": 2290,
"s": 2224,
"text": "Implementation of java Applet can be done in two ways as follows:"
},
{
"code": null,
"e": 2324,
"s": 2290,
"text": "Using HTML fileApplet viewer tool"
},
{
"code": null,
"e": 2340,
"s": 2324,
"text": "Using HTML file"
},
{
"code": null,
"e": 2359,
"s": 2340,
"text": "Applet viewer tool"
},
{
"code": null,
"e": 2382,
"s": 2359,
"text": "Way 1: Using HTML file"
},
{
"code": null,
"e": 2387,
"s": 2382,
"text": "HTML"
},
{
"code": "<HTML><applet>code,width,height</applet></HTML>",
"e": 2435,
"s": 2387,
"text": null
},
{
"code": null,
"e": 2532,
"s": 2435,
"text": "Note: Drawbacks of using HTML file is you need a plugin (java plugin) to run it on your browser."
},
{
"code": null,
"e": 2559,
"s": 2532,
"text": "Way 2: Applet viewer tool "
},
{
"code": null,
"e": 2615,
"s": 2559,
"text": "There are five methods of an Applet Life Cycle namely; "
},
{
"code": null,
"e": 2651,
"s": 2615,
"text": "init()start()paint()stop()destroy()"
},
{
"code": null,
"e": 2658,
"s": 2651,
"text": "init()"
},
{
"code": null,
"e": 2666,
"s": 2658,
"text": "start()"
},
{
"code": null,
"e": 2674,
"s": 2666,
"text": "paint()"
},
{
"code": null,
"e": 2681,
"s": 2674,
"text": "stop()"
},
{
"code": null,
"e": 2691,
"s": 2681,
"text": "destroy()"
},
{
"code": null,
"e": 2830,
"s": 2691,
"text": "All these are available in AWT Package java.awt.applet.* and in order ton import paint (Graphics g) we do use java.awt.component package "
},
{
"code": null,
"e": 2882,
"s": 2830,
"text": "Let’s understand each method in a detailed manner :"
},
{
"code": null,
"e": 2901,
"s": 2882,
"text": "Method 1: init() "
},
{
"code": null,
"e": 2939,
"s": 2901,
"text": "This is the first method to be called"
},
{
"code": null,
"e": 2973,
"s": 2939,
"text": "Variables can be initialized here"
},
{
"code": null,
"e": 3043,
"s": 2973,
"text": "This method can be called only once during the run time of the applet"
},
{
"code": null,
"e": 3087,
"s": 3043,
"text": "It is invoked at the time of Initialization"
},
{
"code": null,
"e": 3096,
"s": 3087,
"text": "Syntax: "
},
{
"code": null,
"e": 3148,
"s": 3096,
"text": "public void init()\n {\n // To initialize objects\n } "
},
{
"code": null,
"e": 3168,
"s": 3148,
"text": "Method 2: start() "
},
{
"code": null,
"e": 3210,
"s": 3168,
"text": "This method is called after init() method"
},
{
"code": null,
"e": 3257,
"s": 3210,
"text": "start() method is used for starting the applet"
},
{
"code": null,
"e": 3349,
"s": 3257,
"text": "It is also called to restart an applet after it has been stopped. i.e. to resume the applet"
},
{
"code": null,
"e": 3358,
"s": 3349,
"text": "Syntax: "
},
{
"code": null,
"e": 3413,
"s": 3358,
"text": "public void start()\n {\n // To start the applet code\n }"
},
{
"code": null,
"e": 3572,
"s": 3413,
"text": "Note: init() is called once i.e. when the first time an applet is loaded whereas start( ) is called each time an applet’s HTML document is displayed onscreen."
},
{
"code": null,
"e": 3591,
"s": 3572,
"text": "Method 3: paint() "
},
{
"code": null,
"e": 3617,
"s": 3591,
"text": "void paint(Graphics g){ }"
},
{
"code": null,
"e": 3705,
"s": 3617,
"text": "paint() method is used for painting any shapes like square, rectangle, trapeziums, etc."
},
{
"code": null,
"e": 3826,
"s": 3705,
"text": "paint() method has one parameter of type Graphics Class, this Graphics class enables the painting features in an applet."
},
{
"code": null,
"e": 3934,
"s": 3826,
"text": "This parameter will contain the graphics context, which is used whenever output for the applet is required."
},
{
"code": null,
"e": 3943,
"s": 3934,
"text": "Syntax: "
},
{
"code": null,
"e": 4007,
"s": 3943,
"text": "public void paint(Graphics graphics)\n {\n // Any shape's code\n }"
},
{
"code": null,
"e": 4098,
"s": 4007,
"text": "Note: This is the only method among all the method mention above, which is parameterized. "
},
{
"code": null,
"e": 4116,
"s": 4098,
"text": "Method 4: stop() "
},
{
"code": null,
"e": 4230,
"s": 4116,
"text": "It is invoked every time the browser is stopped, minimized or when there is an abrupt failure in the application."
},
{
"code": null,
"e": 4306,
"s": 4230,
"text": "After stop()method called, we can also use start() method whenever we want."
},
{
"code": null,
"e": 4351,
"s": 4306,
"text": "This method mainly deals with clean up code."
},
{
"code": null,
"e": 4720,
"s": 4351,
"text": "The stop( ) method is called when a web browser leaves the HTML document containing the applet when it goes to another page, for example, when stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page."
},
{
"code": null,
"e": 4729,
"s": 4720,
"text": "Syntax: "
},
{
"code": null,
"e": 4782,
"s": 4729,
"text": "public void stop()\n {\n // To stop the applet code\n }"
},
{
"code": null,
"e": 4803,
"s": 4782,
"text": "Method 5: destroy() "
},
{
"code": null,
"e": 4923,
"s": 4803,
"text": "destroy() method is used to destroy the application once we are done with our applet work. It can be invoked only once."
},
{
"code": null,
"e": 5013,
"s": 4923,
"text": "Once applet is destroyed we can’t start() the applet (we cannot restore the applet again)"
},
{
"code": null,
"e": 5138,
"s": 5013,
"text": "The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory."
},
{
"code": null,
"e": 5147,
"s": 5138,
"text": "Syntax: "
},
{
"code": null,
"e": 5201,
"s": 5147,
"text": "public void destroy()\n {\n // To destroy the applet\n }"
},
{
"code": null,
"e": 5261,
"s": 5201,
"text": "Note: The stop( ) method is always called before destroy( )"
},
{
"code": null,
"e": 5295,
"s": 5261,
"text": "Syntax: Entire Applet Life Cycle "
},
{
"code": null,
"e": 5300,
"s": 5295,
"text": "Java"
},
{
"code": "Class AppletLifeCycle extends Applet{ public void init() { // Initializes objects } public void start() { // Starts the applet code } public void paint(Graphics graphics) { // Any shape's code } public void stop() { // Stops the applet code } public void destroy() { // Destroys the applet code }}",
"e": 5678,
"s": 5300,
"text": null
},
{
"code": null,
"e": 5696,
"s": 5678,
"text": " Implementation: "
},
{
"code": null,
"e": 5795,
"s": 5696,
"text": "Example 1: In order to begin with Java Applet, let’s understand a simple code to make the Applet "
},
{
"code": null,
"e": 5800,
"s": 5795,
"text": "Java"
},
{
"code": "// Java Program to Make An Applet // Importing required classes from packagesimport java.awt.*;import java.awt.applet.*; // Class 1// Helper class extending Applet classpublic class AppletDemo extends Applet // Note: Every class used here is a derived class of applet,// Hence we use extends keyword Every applet is public{ public void init() { setBackground(Color.black); setForeground(Color.yellow); } public void paint(Graphics g) { g.drawString(\"Welcome\", 100, 100); }} // Save file as AppletDemo.java in local machine",
"e": 6362,
"s": 5800,
"text": null
},
{
"code": null,
"e": 6367,
"s": 6362,
"text": "HTML"
},
{
"code": "<html> <applet code = AppletDemo width = 400 height = 500> </applet> </html><!-- Save as Applet.html -->",
"e": 6495,
"s": 6367,
"text": null
},
{
"code": null,
"e": 6516,
"s": 6495,
"text": "Compilation methods:"
},
{
"code": null,
"e": 6612,
"s": 6516,
"text": "Now in order to generate output, do follow below undersigned to compile and run the above file:"
},
{
"code": null,
"e": 6636,
"s": 6612,
"text": "Method 1: Using command"
},
{
"code": null,
"e": 6691,
"s": 6636,
"text": "Method 2: Include the applet code in our java program."
},
{
"code": null,
"e": 6715,
"s": 6691,
"text": "Methods are as follows:"
},
{
"code": null,
"e": 6743,
"s": 6715,
"text": "Method 1: Using the command"
},
{
"code": null,
"e": 6756,
"s": 6743,
"text": "Compilation:"
},
{
"code": null,
"e": 6782,
"s": 6756,
"text": "c:> javac.AppletDemo.java"
},
{
"code": null,
"e": 6793,
"s": 6782,
"text": "Execution:"
},
{
"code": null,
"e": 6886,
"s": 6793,
"text": "Double click on Applet.html \nThis won't work on browser as we don't have the proper plugins."
},
{
"code": null,
"e": 7049,
"s": 6886,
"text": "Method 2: Include the applet code in our java program make sure to put this html applet code as comments as it is important evil as demonstrated below as follows:"
},
{
"code": null,
"e": 7057,
"s": 7049,
"text": "Example"
},
{
"code": null,
"e": 7062,
"s": 7057,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Insertion of HTML File in// Applet As Commands // Importing required classesimport java.applet.*;import java.awt.*; // Note: Insertion of HTM:L file as comments /* <applet code = AppletDemo width=400 height=500></applet>*/ // Java Program // Class extending Appletpublic class AppletDemo extends Applet { public void init() { setBackground(Color.black); setForeground(Color.yellow); } public void paint(Graphics g) { g.drawString(\"Welcome to Applets\", 50, 50); }}",
"e": 7595,
"s": 7062,
"text": null
},
{
"code": null,
"e": 7610,
"s": 7595,
"text": " Compilation: "
},
{
"code": null,
"e": 7637,
"s": 7610,
"text": "c:\\> javac AppletDemo.java"
},
{
"code": null,
"e": 7649,
"s": 7637,
"text": "Execution: "
},
{
"code": null,
"e": 7683,
"s": 7649,
"text": "c:\\> appletviewer AppletDemo.java"
},
{
"code": null,
"e": 7789,
"s": 7683,
"text": "So this was all about the Life Cycle of Java Applet and methods used to run the applet ! Hope this helps."
},
{
"code": null,
"e": 7809,
"s": 7791,
"text": "germanshephered48"
},
{
"code": null,
"e": 7821,
"s": 7809,
"text": "java-applet"
},
{
"code": null,
"e": 7828,
"s": 7821,
"text": "Picked"
},
{
"code": null,
"e": 7842,
"s": 7828,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 7847,
"s": 7842,
"text": "Java"
},
{
"code": null,
"e": 7856,
"s": 7847,
"text": "TrueGeek"
},
{
"code": null,
"e": 7861,
"s": 7856,
"text": "Java"
}
] |
Stream count() method in Java with examples
|
06 Dec, 2018
long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
long count()
Note : The return value of count operation is the count of elements in the stream.
Example 1 : Counting number of elements in array.
// Java code for Stream.count()// to count the elements in the stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10, 12); // Using count() to count the number // of elements in the stream and // storing the result in a variable. long total = list.stream().count(); // Displaying the number of elements System.out.println(total); }}
Output :
7
Example 2 : Count number of distinct elements in a list.
// Java code for Stream.count()// to count the number of distinct// elements in the stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Strings List<String> list = Arrays.asList("GFG", "Geeks", "for", "Geeks", "GeeksforGeeks", "GFG"); // Using count() to count the number // of distinct elements in the stream and // storing the result in a variable. long total = list.stream().distinct().count(); // Displaying the number of elements System.out.println(total); }}
Output :
4
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 519,
"s": 54,
"text": "long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used."
},
{
"code": null,
"e": 528,
"s": 519,
"text": "Syntax :"
},
{
"code": null,
"e": 542,
"s": 528,
"text": "long count()\n"
},
{
"code": null,
"e": 625,
"s": 542,
"text": "Note : The return value of count operation is the count of elements in the stream."
},
{
"code": null,
"e": 675,
"s": 625,
"text": "Example 1 : Counting number of elements in array."
},
{
"code": "// Java code for Stream.count()// to count the elements in the stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10, 12); // Using count() to count the number // of elements in the stream and // storing the result in a variable. long total = list.stream().count(); // Displaying the number of elements System.out.println(total); }}",
"e": 1252,
"s": 675,
"text": null
},
{
"code": null,
"e": 1261,
"s": 1252,
"text": "Output :"
},
{
"code": null,
"e": 1264,
"s": 1261,
"text": "7\n"
},
{
"code": null,
"e": 1321,
"s": 1264,
"text": "Example 2 : Count number of distinct elements in a list."
},
{
"code": "// Java code for Stream.count()// to count the number of distinct// elements in the stream.import java.util.*; class GFG { // Driver code public static void main(String[] args) { // creating a list of Strings List<String> list = Arrays.asList(\"GFG\", \"Geeks\", \"for\", \"Geeks\", \"GeeksforGeeks\", \"GFG\"); // Using count() to count the number // of distinct elements in the stream and // storing the result in a variable. long total = list.stream().distinct().count(); // Displaying the number of elements System.out.println(total); }}",
"e": 1969,
"s": 1321,
"text": null
},
{
"code": null,
"e": 1978,
"s": 1969,
"text": "Output :"
},
{
"code": null,
"e": 1981,
"s": 1978,
"text": "4\n"
},
{
"code": null,
"e": 2001,
"s": 1981,
"text": "Java - util package"
},
{
"code": null,
"e": 2016,
"s": 2001,
"text": "Java-Functions"
},
{
"code": null,
"e": 2028,
"s": 2016,
"text": "java-stream"
},
{
"code": null,
"e": 2050,
"s": 2028,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2055,
"s": 2050,
"text": "Java"
},
{
"code": null,
"e": 2060,
"s": 2055,
"text": "Java"
}
] |
numpy.mod() in Python
|
10 Feb, 2019
numpy.mod() is another function for doing mathematical operations in numpy.It returns element-wise remainder of division between two array arr1 and arr2 i.e. arr1 % arr2 .It returns 0 when arr2 is 0 and both arr1 and arr2 are (arrays of) integers.
Syntax : numpy.mod(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘remainder’)
Parameters :arr1 : [array_like] Dividend array.arr2 : [array_like] Divisor array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray] The element-wise remainder i.e arr1 % arr2 .
Code #1 :
# Python program explaining# numpy.mod() function import numpy as geekin_num1 = 6in_num2 = 4 print ("Dividend : ", in_num1)print ("Divisor : ", in_num2) out_num = geek.mod(in_num1, in_num2) print ("Remainder : ", out_num)
Dividend : 6
Divisor : 4
Remainder : 2
Code #2 :
# Python program explaining# numpy.mod() function import numpy as geek in_arr1 = geek.array([2, -4, 7])in_arr2 = geek.array([2, 3, 4]) print ("Dividend array : ", in_arr1)print ("Divisor array : ", in_arr2) out_arr = geek.mod(in_arr1, in_arr2) print ("Output remainder array: ", out_arr)
Dividend array : [ 2 -4 7]
Divisor array : [2 3 4]
Output remainder array: [0 2 3]
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Feb, 2019"
},
{
"code": null,
"e": 276,
"s": 28,
"text": "numpy.mod() is another function for doing mathematical operations in numpy.It returns element-wise remainder of division between two array arr1 and arr2 i.e. arr1 % arr2 .It returns 0 when arr2 is 0 and both arr1 and arr2 are (arrays of) integers."
},
{
"code": null,
"e": 431,
"s": 276,
"text": "Syntax : numpy.mod(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘remainder’)"
},
{
"code": null,
"e": 1089,
"s": 431,
"text": "Parameters :arr1 : [array_like] Dividend array.arr2 : [array_like] Divisor array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function."
},
{
"code": null,
"e": 1153,
"s": 1089,
"text": "Return : [ndarray] The element-wise remainder i.e arr1 % arr2 ."
},
{
"code": null,
"e": 1163,
"s": 1153,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.mod() function import numpy as geekin_num1 = 6in_num2 = 4 print (\"Dividend : \", in_num1)print (\"Divisor : \", in_num2) out_num = geek.mod(in_num1, in_num2) print (\"Remainder : \", out_num) ",
"e": 1391,
"s": 1163,
"text": null
},
{
"code": null,
"e": 1434,
"s": 1391,
"text": "Dividend : 6\nDivisor : 4\nRemainder : 2\n"
},
{
"code": null,
"e": 1446,
"s": 1436,
"text": "Code #2 :"
},
{
"code": "# Python program explaining# numpy.mod() function import numpy as geek in_arr1 = geek.array([2, -4, 7])in_arr2 = geek.array([2, 3, 4]) print (\"Dividend array : \", in_arr1)print (\"Divisor array : \", in_arr2) out_arr = geek.mod(in_arr1, in_arr2) print (\"Output remainder array: \", out_arr) ",
"e": 1745,
"s": 1446,
"text": null
},
{
"code": null,
"e": 1833,
"s": 1745,
"text": "Dividend array : [ 2 -4 7]\nDivisor array : [2 3 4]\nOutput remainder array: [0 2 3]\n"
},
{
"code": null,
"e": 1868,
"s": 1833,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 1881,
"s": 1868,
"text": "Python-numpy"
},
{
"code": null,
"e": 1888,
"s": 1881,
"text": "Python"
}
] |
TABBY Hack The Box Walkthrough for Root Flag
|
25 Aug, 2020
This is a root flag Walkthrough or Solution for the machine TABBY on Hack The Box. This machine is a Linux based machine in which we have to own root and user both. Its difficulty level is easy and has an IP 10.10.10.194 for me and it could depend on your account.
The link for the machine is https://www.hackthebox.eu/home/machines/profile/259. Please go through the steps to get the user flag before following the below-mentioned steps first.
1. When we entered the id command in the ash user, we found that ash user is a member of the group lxd. So I tried privilege escalation with LXD. To do so Enter the following set of commands on your local system.
git clone https://github.com/saghul/lxd-alpine-builder.git
cd lxd-alpine-builder/
sudo bash build-alpine
2. It will create a tar.gz file as shown below
3. Now, Copy this tar.gz file to /var/www/html folder using the command shown below
sudo cp alpine-v3.12-x86_64-20200806_0441.tar.gz /var/www/html
Replace the alipne tar.gz file with the respective file generated on the local system.
4. Run the Apache server to host the same using the following command.
sudo service apache2 restart
5. Go to the terminal with a machine shell and enter the following set of commands to change the user to ash.
su ash
This will ask for a password enter the password “admin@it” there. Now we have to write permission in the ash home directory, and we have to download the file in the same. So in order to do that switch to ash user’s home directory using the following command.
cd /home/ash
6. Now we are in the home directory of ash, and we could now download our alpine tar.gz file. Use the following command to download the same in the ash user home directory.
wget http://<hackthebox_ip>/alpine-v3.12-x86_64-20200806_0441.tar.gz
replace <hackthebox_ip> with your respective hackthebox ip address.
7. Import the new lxc image after downloading the tar.gz file with the alias liquid and enter the following command to do the same.
lxc image import ./alpine-v3.12-x86_64-20200806_0441.tar.gz --alias liquid
Replace the alipne tar.gz file with the respective file generated on the local system.
8. List the images to check the image created successfully or not and enter the following command for the same.
lxc image list
9. Now, all the setup is done, it’s time to initialize the lxd with the following command.
lxd init
10. Enter the following command now to change the security privileged to true for liquid and privesc.
lxc init liquid privesc -c security.privileged=true
11. Mount the source to root in order to get the terminal.
lxc config device add privesc mydevice disk source=/ path=/mnt/root recursive=true
12. Enter the following command sequence in order to get the terminal from the above setup.
lxc start privesc
lxc exec privesc /bin/sh
id
13. From the above snap, the id command confirms that we are now logged in as root.
14. Enter the following commands to get the hash of the root user flag.
cd /mnt/root
cd root
ls
cat root.txt
And there we go, we have the root flag for the user as well as root now.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 293,
"s": 28,
"text": "This is a root flag Walkthrough or Solution for the machine TABBY on Hack The Box. This machine is a Linux based machine in which we have to own root and user both. Its difficulty level is easy and has an IP 10.10.10.194 for me and it could depend on your account."
},
{
"code": null,
"e": 474,
"s": 293,
"text": "The link for the machine is https://www.hackthebox.eu/home/machines/profile/259. Please go through the steps to get the user flag before following the below-mentioned steps first. "
},
{
"code": null,
"e": 687,
"s": 474,
"text": "1. When we entered the id command in the ash user, we found that ash user is a member of the group lxd. So I tried privilege escalation with LXD. To do so Enter the following set of commands on your local system."
},
{
"code": null,
"e": 793,
"s": 687,
"text": "git clone https://github.com/saghul/lxd-alpine-builder.git\ncd lxd-alpine-builder/\nsudo bash build-alpine\n"
},
{
"code": null,
"e": 840,
"s": 793,
"text": "2. It will create a tar.gz file as shown below"
},
{
"code": null,
"e": 924,
"s": 840,
"text": "3. Now, Copy this tar.gz file to /var/www/html folder using the command shown below"
},
{
"code": null,
"e": 988,
"s": 924,
"text": "sudo cp alpine-v3.12-x86_64-20200806_0441.tar.gz /var/www/html\n"
},
{
"code": null,
"e": 1075,
"s": 988,
"text": "Replace the alipne tar.gz file with the respective file generated on the local system."
},
{
"code": null,
"e": 1146,
"s": 1075,
"text": "4. Run the Apache server to host the same using the following command."
},
{
"code": null,
"e": 1176,
"s": 1146,
"text": "sudo service apache2 restart\n"
},
{
"code": null,
"e": 1286,
"s": 1176,
"text": "5. Go to the terminal with a machine shell and enter the following set of commands to change the user to ash."
},
{
"code": null,
"e": 1294,
"s": 1286,
"text": "su ash\n"
},
{
"code": null,
"e": 1553,
"s": 1294,
"text": "This will ask for a password enter the password “admin@it” there. Now we have to write permission in the ash home directory, and we have to download the file in the same. So in order to do that switch to ash user’s home directory using the following command."
},
{
"code": null,
"e": 1567,
"s": 1553,
"text": "cd /home/ash\n"
},
{
"code": null,
"e": 1740,
"s": 1567,
"text": "6. Now we are in the home directory of ash, and we could now download our alpine tar.gz file. Use the following command to download the same in the ash user home directory."
},
{
"code": null,
"e": 1810,
"s": 1740,
"text": "wget http://<hackthebox_ip>/alpine-v3.12-x86_64-20200806_0441.tar.gz\n"
},
{
"code": null,
"e": 1878,
"s": 1810,
"text": "replace <hackthebox_ip> with your respective hackthebox ip address."
},
{
"code": null,
"e": 2010,
"s": 1878,
"text": "7. Import the new lxc image after downloading the tar.gz file with the alias liquid and enter the following command to do the same."
},
{
"code": null,
"e": 2086,
"s": 2010,
"text": "lxc image import ./alpine-v3.12-x86_64-20200806_0441.tar.gz --alias liquid\n"
},
{
"code": null,
"e": 2173,
"s": 2086,
"text": "Replace the alipne tar.gz file with the respective file generated on the local system."
},
{
"code": null,
"e": 2285,
"s": 2173,
"text": "8. List the images to check the image created successfully or not and enter the following command for the same."
},
{
"code": null,
"e": 2301,
"s": 2285,
"text": "lxc image list\n"
},
{
"code": null,
"e": 2392,
"s": 2301,
"text": "9. Now, all the setup is done, it’s time to initialize the lxd with the following command."
},
{
"code": null,
"e": 2402,
"s": 2392,
"text": "lxd init\n"
},
{
"code": null,
"e": 2504,
"s": 2402,
"text": "10. Enter the following command now to change the security privileged to true for liquid and privesc."
},
{
"code": null,
"e": 2557,
"s": 2504,
"text": "lxc init liquid privesc -c security.privileged=true\n"
},
{
"code": null,
"e": 2616,
"s": 2557,
"text": "11. Mount the source to root in order to get the terminal."
},
{
"code": null,
"e": 2700,
"s": 2616,
"text": "lxc config device add privesc mydevice disk source=/ path=/mnt/root recursive=true\n"
},
{
"code": null,
"e": 2792,
"s": 2700,
"text": "12. Enter the following command sequence in order to get the terminal from the above setup."
},
{
"code": null,
"e": 2839,
"s": 2792,
"text": "lxc start privesc\nlxc exec privesc /bin/sh\nid\n"
},
{
"code": null,
"e": 2923,
"s": 2839,
"text": "13. From the above snap, the id command confirms that we are now logged in as root."
},
{
"code": null,
"e": 2995,
"s": 2923,
"text": "14. Enter the following commands to get the hash of the root user flag."
},
{
"code": null,
"e": 3033,
"s": 2995,
"text": "cd /mnt/root\ncd root\nls\ncat root.txt\n"
},
{
"code": null,
"e": 3106,
"s": 3033,
"text": "And there we go, we have the root flag for the user as well as root now."
},
{
"code": null,
"e": 3117,
"s": 3106,
"text": "Linux-Unix"
}
] |
Convert a String to Character Array in Java
|
13 May, 2022
Here we are converting a string into a primitive datatype. It is recommended to have good knowledge of Wrapper classes and concepts like autoboxing and unboxing as in java they are frequently used in converting data types.
Illustrations:
Input : Hello World
Output : [H, e, l, l, o,, W, o, r, l, d]
Input : GeeksForGeeks
Output : [G, e, e, k, s, F, o, r, G, e, e, k, s]
Using a naive approach via loopsUsing toChar() method of String class
Using a naive approach via loops
Using toChar() method of String class
Get the string.Create a character array of the same length as of string.Traverse over the string to copy character at the i’th index of string to i’th index in the array.Return or perform the operation on the character array.
Get the string.
Create a character array of the same length as of string.
Traverse over the string to copy character at the i’th index of string to i’th index in the array.
Return or perform the operation on the character array.
Example:
Java
// Java Program to Convert a String to Character Array// Using Naive Approach // Importing required classesimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = "GeeksForGeeks"; // Creating array of string length // using length() method char[] ch = new char[str.length()]; // Copying character by character into array // using for each loop for (int i = 0; i < str.length(); i++) { ch[i] = str.charAt(i); } // Printing the elements of array // using for each loop for (char c : ch) { System.out.println(c); } }}
G
e
e
k
s
F
o
r
G
e
e
k
s
Tip: This method acts very important as in most interviews an approach is seen mostly laid through via this method.
Procedure:
Getting the string.Creating a character array of the same length as of string.Storing the array return by toCharArray() method.Returning or performing an operation on a character array.
Getting the string.
Creating a character array of the same length as of string.
Storing the array return by toCharArray() method.
Returning or performing an operation on a character array.
Example:
Java
// Java Program to Convert a String to Character Array// Using toCharArray() Method // Importing required classesimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = "GeeksForGeeks"; // Creating array and storing the array // returned by toCharArray() method char[] ch = str.toCharArray(); // Lastly printing the array elements for (char c : ch) { System.out.println(c); } }}
G
e
e
k
s
F
o
r
G
e
e
k
s
shubham_singh
solankimayank
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 275,
"s": 52,
"text": "Here we are converting a string into a primitive datatype. It is recommended to have good knowledge of Wrapper classes and concepts like autoboxing and unboxing as in java they are frequently used in converting data types."
},
{
"code": null,
"e": 290,
"s": 275,
"text": "Illustrations:"
},
{
"code": null,
"e": 354,
"s": 290,
"text": "Input : Hello World\nOutput : [H, e, l, l, o,, W, o, r, l, d]"
},
{
"code": null,
"e": 428,
"s": 354,
"text": "Input : GeeksForGeeks\nOutput : [G, e, e, k, s, F, o, r, G, e, e, k, s]"
},
{
"code": null,
"e": 498,
"s": 428,
"text": "Using a naive approach via loopsUsing toChar() method of String class"
},
{
"code": null,
"e": 531,
"s": 498,
"text": "Using a naive approach via loops"
},
{
"code": null,
"e": 569,
"s": 531,
"text": "Using toChar() method of String class"
},
{
"code": null,
"e": 795,
"s": 569,
"text": "Get the string.Create a character array of the same length as of string.Traverse over the string to copy character at the i’th index of string to i’th index in the array.Return or perform the operation on the character array."
},
{
"code": null,
"e": 811,
"s": 795,
"text": "Get the string."
},
{
"code": null,
"e": 869,
"s": 811,
"text": "Create a character array of the same length as of string."
},
{
"code": null,
"e": 968,
"s": 869,
"text": "Traverse over the string to copy character at the i’th index of string to i’th index in the array."
},
{
"code": null,
"e": 1024,
"s": 968,
"text": "Return or perform the operation on the character array."
},
{
"code": null,
"e": 1033,
"s": 1024,
"text": "Example:"
},
{
"code": null,
"e": 1038,
"s": 1033,
"text": "Java"
},
{
"code": "// Java Program to Convert a String to Character Array// Using Naive Approach // Importing required classesimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = \"GeeksForGeeks\"; // Creating array of string length // using length() method char[] ch = new char[str.length()]; // Copying character by character into array // using for each loop for (int i = 0; i < str.length(); i++) { ch[i] = str.charAt(i); } // Printing the elements of array // using for each loop for (char c : ch) { System.out.println(c); } }}",
"e": 1780,
"s": 1038,
"text": null
},
{
"code": null,
"e": 1806,
"s": 1780,
"text": "G\ne\ne\nk\ns\nF\no\nr\nG\ne\ne\nk\ns"
},
{
"code": null,
"e": 1922,
"s": 1806,
"text": "Tip: This method acts very important as in most interviews an approach is seen mostly laid through via this method."
},
{
"code": null,
"e": 1933,
"s": 1922,
"text": "Procedure:"
},
{
"code": null,
"e": 2120,
"s": 1933,
"text": "Getting the string.Creating a character array of the same length as of string.Storing the array return by toCharArray() method.Returning or performing an operation on a character array. "
},
{
"code": null,
"e": 2140,
"s": 2120,
"text": "Getting the string."
},
{
"code": null,
"e": 2200,
"s": 2140,
"text": "Creating a character array of the same length as of string."
},
{
"code": null,
"e": 2250,
"s": 2200,
"text": "Storing the array return by toCharArray() method."
},
{
"code": null,
"e": 2310,
"s": 2250,
"text": "Returning or performing an operation on a character array. "
},
{
"code": null,
"e": 2319,
"s": 2310,
"text": "Example:"
},
{
"code": null,
"e": 2324,
"s": 2319,
"text": "Java"
},
{
"code": "// Java Program to Convert a String to Character Array// Using toCharArray() Method // Importing required classesimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = \"GeeksForGeeks\"; // Creating array and storing the array // returned by toCharArray() method char[] ch = str.toCharArray(); // Lastly printing the array elements for (char c : ch) { System.out.println(c); } }}",
"e": 2882,
"s": 2324,
"text": null
},
{
"code": null,
"e": 2908,
"s": 2882,
"text": "G\ne\ne\nk\ns\nF\no\nr\nG\ne\ne\nk\ns"
},
{
"code": null,
"e": 2922,
"s": 2908,
"text": "shubham_singh"
},
{
"code": null,
"e": 2936,
"s": 2922,
"text": "solankimayank"
},
{
"code": null,
"e": 2957,
"s": 2936,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2964,
"s": 2957,
"text": "Picked"
},
{
"code": null,
"e": 2969,
"s": 2964,
"text": "Java"
},
{
"code": null,
"e": 2983,
"s": 2969,
"text": "Java Programs"
},
{
"code": null,
"e": 2988,
"s": 2983,
"text": "Java"
},
{
"code": null,
"e": 3086,
"s": 2988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3105,
"s": 3086,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3123,
"s": 3105,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3143,
"s": 3123,
"text": "Collections in Java"
},
{
"code": null,
"e": 3175,
"s": 3143,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3190,
"s": 3175,
"text": "Stream In Java"
},
{
"code": null,
"e": 3218,
"s": 3190,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 3244,
"s": 3218,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3278,
"s": 3244,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3325,
"s": 3278,
"text": "Implementing a Linked List in Java using Class"
}
] |
When do we use Initializer List in C++?
|
19 Apr, 2022
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
C++
#include<iostream>using namespace std; class Point {private: int x; int y;public: Point(int i = 0, int j = 0):x(i), y(j) {} /* The above use of Initializer list is optional as the constructor can also be written as: Point(int i = 0, int j = 0) { x = i; y = j; } */ int getX() const {return x;} int getY() const {return y;}}; int main() { Point t1(10, 15); cout<<"x = "<<t1.getX()<<", "; cout<<"y = "<<t1.getY(); return 0;} /* OUTPUT: x = 10, y = 15*/
The above code is just an example for syntax of the Initializer list. In the above code, x and y can also be easily initialed inside the constructor. But there are situations where initialization of data members inside constructor doesn’t work and Initializer List must be used. Following are such cases:
1) For initialization of non-static const data members: const data members must be initialized using Initializer List. In the following example, “t” is a const data member of Test class and is initialized using Initializer List. Reason for initializing the const data member in the initializer list is because no memory is allocated separately for const data member, it is folded in the symbol table due to which we need to initialize it in the initializer list. Also, it is a Parameterized constructor and we don’t need to call the assignment operator which means we are avoiding one extra operation.
C++
#include<iostream>using namespace std; class Test { const int t;public: Test(int t):t(t) {} //Initializer list must be used int getT() { return t; }}; int main() { Test t1(10); cout<<t1.getT(); return 0;} /* OUTPUT: 10*/
2) For initialization of reference members: Reference members must be initialized using Initializer List. In the following example, “t” is a reference member of Test class and is initialized using Initializer List.
C++
// Initialization of reference data members#include<iostream>using namespace std; class Test { int &t;public: Test(int &t):t(t) {} //Initializer list must be used int getT() { return t; }}; int main() { int x = 20; Test t1(x); cout<<t1.getT()<<endl; x = 30; cout<<t1.getT()<<endl; return 0;}/* OUTPUT: 20 30 */
3) For initialization of member objects which do not have default constructor: In the following example, an object “a” of class “A” is data member of class “B”, and “A” doesn’t have default constructor. Initializer List must be used to initialize “a”.
C++
#include <iostream>using namespace std; class A { int i;public: A(int );}; A::A(int arg) { i = arg; cout << "A's Constructor called: Value of i: " << i << endl;} // Class B contains object of Aclass B { A a;public: B(int );}; B::B(int x):a(x) { //Initializer list must be used cout << "B's Constructor called";} int main() { B obj(10); return 0;}/* OUTPUT: A's Constructor called: Value of i: 10 B's Constructor called*/
If class A had both default and parameterized constructors, then Initializer List is not must if we want to initialize “a” using default constructor, but it is must to initialize “a” using parameterized constructor.
4) For initialization of base class members : Like point 3, the parameterized constructor of the base class can only be called using Initializer List.
C++
#include <iostream>using namespace std; class A { int i;public: A(int );}; A::A(int arg) { i = arg; cout << "A's Constructor called: Value of i: " << i << endl;} // Class B is derived from Aclass B: A {public: B(int );}; B::B(int x):A(x) { //Initializer list must be used cout << "B's Constructor called";} int main() { B obj(10); return 0;}
5) When constructor’s parameter name is same as data member If constructor’s parameter name is same as data member name then the data member must be initialized either using this pointer or Initializer List. In the following example, both member name and parameter name for A() is “i”.
C++
#include <iostream>using namespace std; class A { int i;public: A(int ); int getI() const { return i; }}; A::A(int i):i(i) { } // Either Initializer list or this pointer must be used/* The above constructor can also be written asA::A(int i) { this->i = i;}*/ int main() { A a(10); cout<<a.getI(); return 0;}/* OUTPUT: 10*/
6) For Performance reasons: It is better to initialize all class variables in Initializer List instead of assigning values inside body. Consider the following example:
C++
// Without Initializer Listclass MyClass { Type variable;public: MyClass(Type a) { // Assume that Type is an already // declared class and it has appropriate // constructors and operators variable = a; }};
Here compiler follows following steps to create an object of type MyClass 1. Type’s constructor is called first for “a”.
2. Default construct “variable”3. The assignment operator of “Type” is called inside body of MyClass() constructor to assign
variable = a;
4. And then finally destructor of “Type” is called for “a” since it goes out of scope.
Now consider the same code with MyClass() constructor with Initializer List
C++
// With Initializer Listclass MyClass { Type variable;public: MyClass(Type a):variable(a) { // Assume that Type is an already // declared class and it has appropriate // constructors and operators }};
With the Initializer List, the following steps are followed by compiler: 1. 1. Type’s constructor is called first for “a”.
2. Parameterized constructor of “Type” class is called to initialize: variable(a). The arguments in the initializer list are used to copy construct “variable” directly. 3. The destructor of “Type” is called for “a” since it goes out of scope.As we can see from this example if we use assignment inside constructor body there are three function calls: constructor + destructor + one addition assignment operator call. And if we use Initializer List there are only two function calls: copy constructor + destructor call. See this post for a running example on this point.This assignment penalty will be much more in “real” applications where there will be many such variables. Thanks to ptr for adding this point. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
RajendraStalekar
sunnychaudharyvlsi
surabhi44
chhabradhanvi
ricoruotongjia
rkbhola5
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 332,
"s": 54,
"text": "Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class."
},
{
"code": null,
"e": 336,
"s": 332,
"text": "C++"
},
{
"code": "#include<iostream>using namespace std; class Point {private: int x; int y;public: Point(int i = 0, int j = 0):x(i), y(j) {} /* The above use of Initializer list is optional as the constructor can also be written as: Point(int i = 0, int j = 0) { x = i; y = j; } */ int getX() const {return x;} int getY() const {return y;}}; int main() { Point t1(10, 15); cout<<\"x = \"<<t1.getX()<<\", \"; cout<<\"y = \"<<t1.getY(); return 0;} /* OUTPUT: x = 10, y = 15*/",
"e": 866,
"s": 336,
"text": null
},
{
"code": null,
"e": 1171,
"s": 866,
"text": "The above code is just an example for syntax of the Initializer list. In the above code, x and y can also be easily initialed inside the constructor. But there are situations where initialization of data members inside constructor doesn’t work and Initializer List must be used. Following are such cases:"
},
{
"code": null,
"e": 1774,
"s": 1171,
"text": "1) For initialization of non-static const data members: const data members must be initialized using Initializer List. In the following example, “t” is a const data member of Test class and is initialized using Initializer List. Reason for initializing the const data member in the initializer list is because no memory is allocated separately for const data member, it is folded in the symbol table due to which we need to initialize it in the initializer list. Also, it is a Parameterized constructor and we don’t need to call the assignment operator which means we are avoiding one extra operation. "
},
{
"code": null,
"e": 1778,
"s": 1774,
"text": "C++"
},
{
"code": "#include<iostream>using namespace std; class Test { const int t;public: Test(int t):t(t) {} //Initializer list must be used int getT() { return t; }}; int main() { Test t1(10); cout<<t1.getT(); return 0;} /* OUTPUT: 10*/",
"e": 2020,
"s": 1778,
"text": null
},
{
"code": null,
"e": 2235,
"s": 2020,
"text": "2) For initialization of reference members: Reference members must be initialized using Initializer List. In the following example, “t” is a reference member of Test class and is initialized using Initializer List."
},
{
"code": null,
"e": 2239,
"s": 2235,
"text": "C++"
},
{
"code": "// Initialization of reference data members#include<iostream>using namespace std; class Test { int &t;public: Test(int &t):t(t) {} //Initializer list must be used int getT() { return t; }}; int main() { int x = 20; Test t1(x); cout<<t1.getT()<<endl; x = 30; cout<<t1.getT()<<endl; return 0;}/* OUTPUT: 20 30 */",
"e": 2584,
"s": 2239,
"text": null
},
{
"code": null,
"e": 2836,
"s": 2584,
"text": "3) For initialization of member objects which do not have default constructor: In the following example, an object “a” of class “A” is data member of class “B”, and “A” doesn’t have default constructor. Initializer List must be used to initialize “a”."
},
{
"code": null,
"e": 2840,
"s": 2836,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A { int i;public: A(int );}; A::A(int arg) { i = arg; cout << \"A's Constructor called: Value of i: \" << i << endl;} // Class B contains object of Aclass B { A a;public: B(int );}; B::B(int x):a(x) { //Initializer list must be used cout << \"B's Constructor called\";} int main() { B obj(10); return 0;}/* OUTPUT: A's Constructor called: Value of i: 10 B's Constructor called*/",
"e": 3295,
"s": 2840,
"text": null
},
{
"code": null,
"e": 3512,
"s": 3295,
"text": "If class A had both default and parameterized constructors, then Initializer List is not must if we want to initialize “a” using default constructor, but it is must to initialize “a” using parameterized constructor. "
},
{
"code": null,
"e": 3663,
"s": 3512,
"text": "4) For initialization of base class members : Like point 3, the parameterized constructor of the base class can only be called using Initializer List."
},
{
"code": null,
"e": 3667,
"s": 3663,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A { int i;public: A(int );}; A::A(int arg) { i = arg; cout << \"A's Constructor called: Value of i: \" << i << endl;} // Class B is derived from Aclass B: A {public: B(int );}; B::B(int x):A(x) { //Initializer list must be used cout << \"B's Constructor called\";} int main() { B obj(10); return 0;}",
"e": 4033,
"s": 3667,
"text": null
},
{
"code": null,
"e": 4319,
"s": 4033,
"text": "5) When constructor’s parameter name is same as data member If constructor’s parameter name is same as data member name then the data member must be initialized either using this pointer or Initializer List. In the following example, both member name and parameter name for A() is “i”."
},
{
"code": null,
"e": 4323,
"s": 4319,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; class A { int i;public: A(int ); int getI() const { return i; }}; A::A(int i):i(i) { } // Either Initializer list or this pointer must be used/* The above constructor can also be written asA::A(int i) { this->i = i;}*/ int main() { A a(10); cout<<a.getI(); return 0;}/* OUTPUT: 10*/",
"e": 4671,
"s": 4323,
"text": null
},
{
"code": null,
"e": 4840,
"s": 4671,
"text": "6) For Performance reasons: It is better to initialize all class variables in Initializer List instead of assigning values inside body. Consider the following example: "
},
{
"code": null,
"e": 4844,
"s": 4840,
"text": "C++"
},
{
"code": "// Without Initializer Listclass MyClass { Type variable;public: MyClass(Type a) { // Assume that Type is an already // declared class and it has appropriate // constructors and operators variable = a; }};",
"e": 5105,
"s": 4844,
"text": null
},
{
"code": null,
"e": 5227,
"s": 5105,
"text": "Here compiler follows following steps to create an object of type MyClass 1. Type’s constructor is called first for “a”. "
},
{
"code": null,
"e": 5353,
"s": 5227,
"text": "2. Default construct “variable”3. The assignment operator of “Type” is called inside body of MyClass() constructor to assign "
},
{
"code": null,
"e": 5371,
"s": 5353,
"text": " variable = a;"
},
{
"code": null,
"e": 5458,
"s": 5371,
"text": "4. And then finally destructor of “Type” is called for “a” since it goes out of scope."
},
{
"code": null,
"e": 5535,
"s": 5458,
"text": "Now consider the same code with MyClass() constructor with Initializer List "
},
{
"code": null,
"e": 5539,
"s": 5535,
"text": "C++"
},
{
"code": "// With Initializer Listclass MyClass { Type variable;public: MyClass(Type a):variable(a) { // Assume that Type is an already // declared class and it has appropriate // constructors and operators }};",
"e": 5791,
"s": 5539,
"text": null
},
{
"code": null,
"e": 5915,
"s": 5791,
"text": "With the Initializer List, the following steps are followed by compiler: 1. 1. Type’s constructor is called first for “a”. "
},
{
"code": null,
"e": 6753,
"s": 5915,
"text": "2. Parameterized constructor of “Type” class is called to initialize: variable(a). The arguments in the initializer list are used to copy construct “variable” directly. 3. The destructor of “Type” is called for “a” since it goes out of scope.As we can see from this example if we use assignment inside constructor body there are three function calls: constructor + destructor + one addition assignment operator call. And if we use Initializer List there are only two function calls: copy constructor + destructor call. See this post for a running example on this point.This assignment penalty will be much more in “real” applications where there will be many such variables. Thanks to ptr for adding this point. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6770,
"s": 6753,
"text": "RajendraStalekar"
},
{
"code": null,
"e": 6789,
"s": 6770,
"text": "sunnychaudharyvlsi"
},
{
"code": null,
"e": 6799,
"s": 6789,
"text": "surabhi44"
},
{
"code": null,
"e": 6813,
"s": 6799,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 6828,
"s": 6813,
"text": "ricoruotongjia"
},
{
"code": null,
"e": 6837,
"s": 6828,
"text": "rkbhola5"
},
{
"code": null,
"e": 6848,
"s": 6837,
"text": "C Language"
},
{
"code": null,
"e": 6852,
"s": 6848,
"text": "C++"
},
{
"code": null,
"e": 6856,
"s": 6852,
"text": "CPP"
},
{
"code": null,
"e": 6954,
"s": 6856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6971,
"s": 6954,
"text": "Substring in C++"
},
{
"code": null,
"e": 7006,
"s": 6971,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 7052,
"s": 7006,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 7074,
"s": 7052,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 7099,
"s": 7074,
"text": "std::string class in C++"
},
{
"code": null,
"e": 7117,
"s": 7099,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 7160,
"s": 7117,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7206,
"s": 7160,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 7249,
"s": 7206,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Speech Recognition in Real-Time using Python | by Behic Guven | Towards Data Science
|
In this post, I will show you how to convert your speech to text in real-time using Python. We will write a program that understands what we are saying and translates it into written words. This translation is known as speech recognition. Speech Recognition is a pretty exciting and fun field to get started with Machine Learning and Artificial Intelligence.
In my previous posts, I’ve covered similar topics like converting speech to text using Google’s Speech Recognition API and building a speech emotion recognizer using Python. In these projects, the recognition and the training was done over static audio files. Today, we will be doing something a little more advanced and more extraordinary in this project. We will learn how to convert our speech to text in real-time.
If you are ready, let’s get to work!
Getting Started
Step 1 — Libraries
Step 2 — Live Stream
Step 3 — Async Function
Final Step — Testing the Real-time Recognizer
In today’s tutorial, we will use AssemblyAI’s real-time transcription API. As a software engineer and tech enthusiast, it’s great to see that the speech recognition field is overgrowing. I believe that these kinds of developments are making our lives easier.
For example, one area where real-time transcription can be helpful is online lectures. While listening to the instructor, we can also read the instructor’s speech as a subtitle. This feature will make the learning process easier for people with hearing disabilities. This is just a basic example; I am sure there are many areas where real-time transcription can be implemented.
By the way, the AssemblyAI’s API is free to access. You will get a unique API key after creating an account. We will need that API key to use the services and features.
We are going to use three Python libraries in this project. They can list as follows: PortAudio, PyAudio, and Websockets. Here is a short definition for each of them.
PortAudio is a free, cross-platform, open-source audio input/output library. It is also a prerequisite library to get the subsequent library, PyAudio, to work.
Official documentaion.
PyAudio is a free, open-source library to play and record audio files on various platforms. This library works as an extension of PortAudio.
Official documentation.
Websockets is a dependency built on top of the asyncio, which is Python’s standard asynchronous I/O framework. It provides an elegant coroutine-based API.
Official documentation.
Let’s get to work by installing them.
We are going to run the following lines inside the terminal window. To install PortAudio we have to use a python library manager called brew.
brew install portaudio
After that, it’s time to install the other two libraries. This time we are using another python library manager called pip. Did you know that we can install one or more libraries in just one line?
pip install pyaudio websockets
Our libraries are installed. Time to get the streaming system ready!
Time to open our coding platform and start coding. Our code is static, so I will go with Atom text editor. The whole code will be in one python file. Easy to run.
import pyaudio FRAMES_PER_BUFFER = 3200FORMAT = pyaudio.paInt16CHANNELS = 1RATE = 16000p = pyaudio.PyAudio() stream = p.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=FRAMES_PER_BUFFER)
In the code above, we are defining the parameters of our stream system. Audio world is really complicated when it comes to details. I recommend searching online about each of the variables to understand them better.
In this step, we will write an async function to send and receive audio data with the API. Async functions are under the topic Coroutines and Tasks.
Coroutines declared with async syntax are the preferred way of writing asyncio applications. Since we want to stream the speech in real-time, this is a great way to display the recognized words into the terminal window with some wait times.
First thing first, let’s import the python libraries.
import websocketsimport asyncioimport base64import jsonfrom configure import auth_key
Now, we will write a function, which I named: send_receive_data(). Many things are going on within this function:
Connecting the program to AssemblyAI’s endpoint url.
The audio data is being transferred to the API to be recognized.
The API returns a json data with the recognized speech.
It is basically a two-way highway, where we send our voice data through the microphone of our laptop/ pc. Then, receive the recognized speech from the API. And everything happens so fast.
Isn’t that cool? And guess what, no rush hour :)
# the AssemblyAI endpoint we're going to hitURL = "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=16000" async def send_receive_data(): print(f'Connecting websocket to url ${URL}') async with websockets.connect( URL, extra_headers=(("Authorization", "our API key"),), ping_interval=5, ping_timeout=20 ) as _ws: await asyncio.sleep(0.1) print("Receiving SessionBegins ...") session_begins = await _ws.recv() print(session_begins) print("Sending messages ...") async def send(): while True: try: data = stream.read(FRAMES_PER_BUFFER) data = base64.b64encode(data).decode("utf-8") json_data = json.dumps({"audio_data":str(data)}) await _ws.send(json_data) except websockets.exceptions.ConnectionClosedError as e: print(e) assert e.code == 4008 break except Exception as e: assert False, "Not a websocket 4008 error" await asyncio.sleep(0.01) return True async def receive(): while True: try: result_str = await _ws.recv() print(json.loads(result_str)['text']) except websockets.exceptions.ConnectionClosedError as e: print(e) assert e.code == 4008 break except Exception as e: assert False, "Not a websocket 4008 error" send_result, receive_result = await asyncio.gather(send(), receive())
The send_receive_data() function is all set!
Now, let’s put it in a loop so that our program listens continuously to our voice. Since we don’t want it to run forever, there is a timeout, which is 1 minute. Asyncio will do this for us.
asyncio.run(send_receive_data())
After running main.py in the the terminal, the program starts to listen. And display the recognized speech right at that moment. I read the introduction part of this article, and here are results.
Congrats! In this hands-on tutorial, we learned how to build a program that detects our speech and converts it into text in real-time using Python. I enjoy creating and working on these projects because they are natural applications of machine learning and artificial intelligence in our daily lives. Hoping that you enjoyed reading this guide and learned something new today.
I am Behic Guven, and I love sharing stories on programming, education, and life. Subscribe to my content to stay inspired. Ty,
If you are wondering what kind of articles I write, here are some:
Building a Face Recognizer using Python
Step-by-Step Guide — Building a Prediction Model in Python
Building a Speech Emotion Recognizer using Python
|
[
{
"code": null,
"e": 406,
"s": 47,
"text": "In this post, I will show you how to convert your speech to text in real-time using Python. We will write a program that understands what we are saying and translates it into written words. This translation is known as speech recognition. Speech Recognition is a pretty exciting and fun field to get started with Machine Learning and Artificial Intelligence."
},
{
"code": null,
"e": 825,
"s": 406,
"text": "In my previous posts, I’ve covered similar topics like converting speech to text using Google’s Speech Recognition API and building a speech emotion recognizer using Python. In these projects, the recognition and the training was done over static audio files. Today, we will be doing something a little more advanced and more extraordinary in this project. We will learn how to convert our speech to text in real-time."
},
{
"code": null,
"e": 862,
"s": 825,
"text": "If you are ready, let’s get to work!"
},
{
"code": null,
"e": 878,
"s": 862,
"text": "Getting Started"
},
{
"code": null,
"e": 897,
"s": 878,
"text": "Step 1 — Libraries"
},
{
"code": null,
"e": 918,
"s": 897,
"text": "Step 2 — Live Stream"
},
{
"code": null,
"e": 942,
"s": 918,
"text": "Step 3 — Async Function"
},
{
"code": null,
"e": 988,
"s": 942,
"text": "Final Step — Testing the Real-time Recognizer"
},
{
"code": null,
"e": 1247,
"s": 988,
"text": "In today’s tutorial, we will use AssemblyAI’s real-time transcription API. As a software engineer and tech enthusiast, it’s great to see that the speech recognition field is overgrowing. I believe that these kinds of developments are making our lives easier."
},
{
"code": null,
"e": 1625,
"s": 1247,
"text": "For example, one area where real-time transcription can be helpful is online lectures. While listening to the instructor, we can also read the instructor’s speech as a subtitle. This feature will make the learning process easier for people with hearing disabilities. This is just a basic example; I am sure there are many areas where real-time transcription can be implemented."
},
{
"code": null,
"e": 1794,
"s": 1625,
"text": "By the way, the AssemblyAI’s API is free to access. You will get a unique API key after creating an account. We will need that API key to use the services and features."
},
{
"code": null,
"e": 1961,
"s": 1794,
"text": "We are going to use three Python libraries in this project. They can list as follows: PortAudio, PyAudio, and Websockets. Here is a short definition for each of them."
},
{
"code": null,
"e": 2121,
"s": 1961,
"text": "PortAudio is a free, cross-platform, open-source audio input/output library. It is also a prerequisite library to get the subsequent library, PyAudio, to work."
},
{
"code": null,
"e": 2144,
"s": 2121,
"text": "Official documentaion."
},
{
"code": null,
"e": 2285,
"s": 2144,
"text": "PyAudio is a free, open-source library to play and record audio files on various platforms. This library works as an extension of PortAudio."
},
{
"code": null,
"e": 2309,
"s": 2285,
"text": "Official documentation."
},
{
"code": null,
"e": 2464,
"s": 2309,
"text": "Websockets is a dependency built on top of the asyncio, which is Python’s standard asynchronous I/O framework. It provides an elegant coroutine-based API."
},
{
"code": null,
"e": 2488,
"s": 2464,
"text": "Official documentation."
},
{
"code": null,
"e": 2526,
"s": 2488,
"text": "Let’s get to work by installing them."
},
{
"code": null,
"e": 2668,
"s": 2526,
"text": "We are going to run the following lines inside the terminal window. To install PortAudio we have to use a python library manager called brew."
},
{
"code": null,
"e": 2691,
"s": 2668,
"text": "brew install portaudio"
},
{
"code": null,
"e": 2888,
"s": 2691,
"text": "After that, it’s time to install the other two libraries. This time we are using another python library manager called pip. Did you know that we can install one or more libraries in just one line?"
},
{
"code": null,
"e": 2919,
"s": 2888,
"text": "pip install pyaudio websockets"
},
{
"code": null,
"e": 2988,
"s": 2919,
"text": "Our libraries are installed. Time to get the streaming system ready!"
},
{
"code": null,
"e": 3151,
"s": 2988,
"text": "Time to open our coding platform and start coding. Our code is static, so I will go with Atom text editor. The whole code will be in one python file. Easy to run."
},
{
"code": null,
"e": 3381,
"s": 3151,
"text": "import pyaudio FRAMES_PER_BUFFER = 3200FORMAT = pyaudio.paInt16CHANNELS = 1RATE = 16000p = pyaudio.PyAudio() stream = p.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=FRAMES_PER_BUFFER)"
},
{
"code": null,
"e": 3597,
"s": 3381,
"text": "In the code above, we are defining the parameters of our stream system. Audio world is really complicated when it comes to details. I recommend searching online about each of the variables to understand them better."
},
{
"code": null,
"e": 3746,
"s": 3597,
"text": "In this step, we will write an async function to send and receive audio data with the API. Async functions are under the topic Coroutines and Tasks."
},
{
"code": null,
"e": 3987,
"s": 3746,
"text": "Coroutines declared with async syntax are the preferred way of writing asyncio applications. Since we want to stream the speech in real-time, this is a great way to display the recognized words into the terminal window with some wait times."
},
{
"code": null,
"e": 4041,
"s": 3987,
"text": "First thing first, let’s import the python libraries."
},
{
"code": null,
"e": 4127,
"s": 4041,
"text": "import websocketsimport asyncioimport base64import jsonfrom configure import auth_key"
},
{
"code": null,
"e": 4241,
"s": 4127,
"text": "Now, we will write a function, which I named: send_receive_data(). Many things are going on within this function:"
},
{
"code": null,
"e": 4294,
"s": 4241,
"text": "Connecting the program to AssemblyAI’s endpoint url."
},
{
"code": null,
"e": 4359,
"s": 4294,
"text": "The audio data is being transferred to the API to be recognized."
},
{
"code": null,
"e": 4415,
"s": 4359,
"text": "The API returns a json data with the recognized speech."
},
{
"code": null,
"e": 4603,
"s": 4415,
"text": "It is basically a two-way highway, where we send our voice data through the microphone of our laptop/ pc. Then, receive the recognized speech from the API. And everything happens so fast."
},
{
"code": null,
"e": 4652,
"s": 4603,
"text": "Isn’t that cool? And guess what, no rush hour :)"
},
{
"code": null,
"e": 6324,
"s": 4652,
"text": "# the AssemblyAI endpoint we're going to hitURL = \"wss://api.assemblyai.com/v2/realtime/ws?sample_rate=16000\" async def send_receive_data(): print(f'Connecting websocket to url ${URL}') async with websockets.connect( URL, extra_headers=((\"Authorization\", \"our API key\"),), ping_interval=5, ping_timeout=20 ) as _ws: await asyncio.sleep(0.1) print(\"Receiving SessionBegins ...\") session_begins = await _ws.recv() print(session_begins) print(\"Sending messages ...\") async def send(): while True: try: data = stream.read(FRAMES_PER_BUFFER) data = base64.b64encode(data).decode(\"utf-8\") json_data = json.dumps({\"audio_data\":str(data)}) await _ws.send(json_data) except websockets.exceptions.ConnectionClosedError as e: print(e) assert e.code == 4008 break except Exception as e: assert False, \"Not a websocket 4008 error\" await asyncio.sleep(0.01) return True async def receive(): while True: try: result_str = await _ws.recv() print(json.loads(result_str)['text']) except websockets.exceptions.ConnectionClosedError as e: print(e) assert e.code == 4008 break except Exception as e: assert False, \"Not a websocket 4008 error\" send_result, receive_result = await asyncio.gather(send(), receive())"
},
{
"code": null,
"e": 6369,
"s": 6324,
"text": "The send_receive_data() function is all set!"
},
{
"code": null,
"e": 6559,
"s": 6369,
"text": "Now, let’s put it in a loop so that our program listens continuously to our voice. Since we don’t want it to run forever, there is a timeout, which is 1 minute. Asyncio will do this for us."
},
{
"code": null,
"e": 6592,
"s": 6559,
"text": "asyncio.run(send_receive_data())"
},
{
"code": null,
"e": 6789,
"s": 6592,
"text": "After running main.py in the the terminal, the program starts to listen. And display the recognized speech right at that moment. I read the introduction part of this article, and here are results."
},
{
"code": null,
"e": 7166,
"s": 6789,
"text": "Congrats! In this hands-on tutorial, we learned how to build a program that detects our speech and converts it into text in real-time using Python. I enjoy creating and working on these projects because they are natural applications of machine learning and artificial intelligence in our daily lives. Hoping that you enjoyed reading this guide and learned something new today."
},
{
"code": null,
"e": 7294,
"s": 7166,
"text": "I am Behic Guven, and I love sharing stories on programming, education, and life. Subscribe to my content to stay inspired. Ty,"
},
{
"code": null,
"e": 7361,
"s": 7294,
"text": "If you are wondering what kind of articles I write, here are some:"
},
{
"code": null,
"e": 7401,
"s": 7361,
"text": "Building a Face Recognizer using Python"
},
{
"code": null,
"e": 7460,
"s": 7401,
"text": "Step-by-Step Guide — Building a Prediction Model in Python"
}
] |
Changed SAP password not working while resetting using BAPI
|
You are using the structure Password for resetting the password. It is of type “BAPIPWD” and comprises of a field which is again named as “BAPIPWD”
When you need to reset the password, you need to specify the correct field name instead of password.
JCO.Structure structPassword = userChangeInput.getStructure("PASSWORD");
sPassword.setValue(nPassword, "BAPIPWD");
|
[
{
"code": null,
"e": 1210,
"s": 1062,
"text": "You are using the structure Password for resetting the password. It is of type “BAPIPWD” and comprises of a field which is again named as “BAPIPWD”"
},
{
"code": null,
"e": 1311,
"s": 1210,
"text": "When you need to reset the password, you need to specify the correct field name instead of password."
},
{
"code": null,
"e": 1426,
"s": 1311,
"text": "JCO.Structure structPassword = userChangeInput.getStructure(\"PASSWORD\");\nsPassword.setValue(nPassword, \"BAPIPWD\");"
}
] |
Create n-child process from same parent process using fork() in C - GeeksforGeeks
|
03 Nov, 2017
fork() is a system call function which can generate child process from parent main process. Using some conditions we can generate as many child process as needed.
We have given n , we have to create n-child processes from same parent process (main process ).
Examples:
Input :3
Output :[son] pid 25332 from [parent] pid 25329
[son] pid 25331 from [parent] pid 25329
[son] pid 25330 from [parent] pid 25329
here 25332, 25331,25330 are child processes from same parent process
with process id 25329
Input :5
Output :[son] pid 28519 from [parent] pid 28518
[son] pid 28523 from [parent] pid 28518
[son] pid 28520 from [parent] pid 28518
[son] pid 28521 from [parent] pid 28518
[son] pid 28522 from [parent] pid 28518
here 28519, 28519,28520,28521,28522 are child processes from same parent process
with process id 28518
#include<stdio.h> int main(){ for(int i=0;i<5;i++) // loop will run n times (n=5) { if(fork() == 0) { printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid()); exit(0); } } for(int i=0;i<5;i++) // loop will run n times (n=5) wait(NULL); }
Output:
[son] pid 28519 from [parent] pid 28518
[son] pid 28523 from [parent] pid 28518
[son] pid 28520 from [parent] pid 28518
[son] pid 28521 from [parent] pid 28518
[son] pid 28522 from [parent] pid 28518
This article is contributed by Dibyendu Roy Chaudhuri. 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.
C Language
C Programs
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 24131,
"s": 24103,
"text": "\n03 Nov, 2017"
},
{
"code": null,
"e": 24294,
"s": 24131,
"text": "fork() is a system call function which can generate child process from parent main process. Using some conditions we can generate as many child process as needed."
},
{
"code": null,
"e": 24390,
"s": 24294,
"text": "We have given n , we have to create n-child processes from same parent process (main process )."
},
{
"code": null,
"e": 24400,
"s": 24390,
"text": "Examples:"
},
{
"code": null,
"e": 25003,
"s": 24400,
"text": "Input :3\nOutput :[son] pid 25332 from [parent] pid 25329\n [son] pid 25331 from [parent] pid 25329\n [son] pid 25330 from [parent] pid 25329\n\nhere 25332, 25331,25330 are child processes from same parent process\nwith process id 25329 \n\nInput :5\nOutput :[son] pid 28519 from [parent] pid 28518\n [son] pid 28523 from [parent] pid 28518\n [son] pid 28520 from [parent] pid 28518\n [son] pid 28521 from [parent] pid 28518\n [son] pid 28522 from [parent] pid 28518\n\nhere 28519, 28519,28520,28521,28522 are child processes from same parent process\nwith process id 28518 \n\n"
},
{
"code": "#include<stdio.h> int main(){ for(int i=0;i<5;i++) // loop will run n times (n=5) { if(fork() == 0) { printf(\"[son] pid %d from [parent] pid %d\\n\",getpid(),getppid()); exit(0); } } for(int i=0;i<5;i++) // loop will run n times (n=5) wait(NULL); }",
"e": 25316,
"s": 25003,
"text": null
},
{
"code": null,
"e": 25324,
"s": 25316,
"text": "Output:"
},
{
"code": null,
"e": 25525,
"s": 25324,
"text": "[son] pid 28519 from [parent] pid 28518\n[son] pid 28523 from [parent] pid 28518\n[son] pid 28520 from [parent] pid 28518\n[son] pid 28521 from [parent] pid 28518\n[son] pid 28522 from [parent] pid 28518\n"
},
{
"code": null,
"e": 25835,
"s": 25525,
"text": "This article is contributed by Dibyendu Roy Chaudhuri. 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": 25960,
"s": 25835,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25971,
"s": 25960,
"text": "C Language"
},
{
"code": null,
"e": 25982,
"s": 25971,
"text": "C Programs"
},
{
"code": null,
"e": 25987,
"s": 25982,
"text": "Misc"
},
{
"code": null,
"e": 25992,
"s": 25987,
"text": "Misc"
},
{
"code": null,
"e": 25997,
"s": 25992,
"text": "Misc"
},
{
"code": null,
"e": 26095,
"s": 25997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26104,
"s": 26095,
"text": "Comments"
},
{
"code": null,
"e": 26117,
"s": 26104,
"text": "Old Comments"
},
{
"code": null,
"e": 26145,
"s": 26117,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26191,
"s": 26145,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26223,
"s": 26191,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26240,
"s": 26223,
"text": "Substring in C++"
},
{
"code": null,
"e": 26262,
"s": 26240,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 26275,
"s": 26262,
"text": "Strings in C"
},
{
"code": null,
"e": 26316,
"s": 26275,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26357,
"s": 26316,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26395,
"s": 26357,
"text": "UDP Server-Client implementation in C"
}
] |
Haskell - Quick Guide
|
Haskell is a Functional Programming Language that has been specially designed to handle symbolic computation and list processing applications. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional Programming paradigm include: Lisp, Python, Erlang, Racket, F#, Clojure, etc.
In conventional programing, instructions are taken as a set of declarations in a specific syntax or format, but in the case of functional programing, all the computation is considered as a combination of separate mathematical functions.
Haskell is a widely used purely functional language. Here, we have listed down a few points that make this language so special over other conventional programing languages such as Java, C, C++, PHP, etc.
Functional Language − In conventional programing language, we instruct the compiler a series of tasks which is nothing but telling your computer "what to do" and "how to do?" But in Haskell we will tell our computer "what it is?"
Functional Language − In conventional programing language, we instruct the compiler a series of tasks which is nothing but telling your computer "what to do" and "how to do?" But in Haskell we will tell our computer "what it is?"
Laziness − Haskell is a lazy language. By lazy, we mean that Haskell won't evaluate any expression without any reason. When the evaluation engine finds that an expression needs to be evaluated, then it creates a thunk data structure to collect all the required information for that specific evaluation and a pointer to that thunk data structure. The evaluation engine will start working only when it is required to evaluate that specific expression.
Laziness − Haskell is a lazy language. By lazy, we mean that Haskell won't evaluate any expression without any reason. When the evaluation engine finds that an expression needs to be evaluated, then it creates a thunk data structure to collect all the required information for that specific evaluation and a pointer to that thunk data structure. The evaluation engine will start working only when it is required to evaluate that specific expression.
Modularity − A Haskell application is nothing but a series of functions. We can say that a Haskell application is a collection of numerous small Haskell applications.
Modularity − A Haskell application is nothing but a series of functions. We can say that a Haskell application is a collection of numerous small Haskell applications.
Statically Typed − In conventional programing language, we need to define a series of variables along with their type. In contrast, Haskell is a type interference language. By the term, type interference language, we mean the Haskell compiler is intelligent enough to figure out the type of the variable declared, hence we need not explicitly mention the type of the variable used.
Statically Typed − In conventional programing language, we need to define a series of variables along with their type. In contrast, Haskell is a type interference language. By the term, type interference language, we mean the Haskell compiler is intelligent enough to figure out the type of the variable declared, hence we need not explicitly mention the type of the variable used.
Maintainability − Haskell applications are modular and hence, it is very easy and cost-effective to maintain them.
Maintainability − Haskell applications are modular and hence, it is very easy and cost-effective to maintain them.
Functional programs are more concurrent and they follow parallelism in execution to provide more accurate and better performance. Haskell is no exception; it has been developed in a way to handle multithreading effectively.
It is a simple example to demonstrate the dynamism of Haskell. Take a look at the following code. All that we need is just one line to print "Hello Word" on the console.
main = putStrLn "Hello World"
Once the Haskell compiler encounters the above piece of code, it promptly yields the following output −
Hello World
We will provide plenty of examples throughout this tutorial to showcase the power and simplicity of Haskell.
We have set up the Haskell programing environment online at −
https://www.tutorialspoint.com/compile_haskell_online.php
This online editor has plenty of options to practice Haskell programing examples. Go to the terminal section of the page and type "ghci". This command automatically loads Haskell compiler and starts Haskell online. You will receive the following output after using the ghci command.
sh-4.3$ ghci
GHCi,version7.8.4:http://www.haskell.org/ghc/:?forhelp
Loading package ghc-prim...linking...done.
Loading packageinteger gmp...linking... done.
Loading package base...linking...done.
Prelude>
If you still want to use Haskell offline in your local system, then you need to download the available Haskell setup from its official webpage − https://www.haskell.org/downloads
There are three different types of installers available in the market −
Minimal Installer − It provides GHC (The Glasgow Haskell Compiler), CABAL (Common Architecture for Building Applications and Libraries), and Stack tools.
Minimal Installer − It provides GHC (The Glasgow Haskell Compiler), CABAL (Common Architecture for Building Applications and Libraries), and Stack tools.
Stack Installer − In this installer, the GHC can be downloaded in a cross-platform of managed toll chain. It will install your application globally such that it can update its API tools whenever required. It automatically resolves all the Haskell-oriented dependencies.
Stack Installer − In this installer, the GHC can be downloaded in a cross-platform of managed toll chain. It will install your application globally such that it can update its API tools whenever required. It automatically resolves all the Haskell-oriented dependencies.
Haskell Platform − This is the best way to install Haskell because it will install the entire platform in your machine and that to from one specific location. This installer is not distributive like the above two installers.
Haskell Platform − This is the best way to install Haskell because it will install the entire platform in your machine and that to from one specific location. This installer is not distributive like the above two installers.
We have seen different types of installer available in market now let us see how to use those installers in our machine. In this tutorial we are going to use Haskell platform installer to install Haskell compiler in our system.
To set up Haskell environment on your Windows computer, go to their official website https://www.haskell.org/platform/windows.html and download the Installer according to your customizable architecture.
Check out your system’s architecture and download the corresponding setup file and run it. It will install like any other Windows application. You may need to update the CABAL configuration of your system.
To set up Haskell environment on your MAC system, go to their official website https://www.haskell.org/platform/mac.html and download the Mac installer.
Installing Haskell on a Linux-based system requires to run some command which is not that much easy like MAC and Windows. Yes, it is tiresome but it is reliable.
You can follow the steps given below to install Haskell on your Linux system −
Step 1 − To set up Haskell environment on your Linux system, go to the official website https://www.haskell.org/platform/linux.html and choose your distribution. You will find the following screen on your browser.
Step 2 − Select your Distribution. In our case, we are using Ubuntu. After selecting this option, you will get the following page on your screen with the command to install the Haskell in our local system.
Step 3 − Open a terminal by pressing Ctrl + Alt + T. Run the command "$ sudo apt-get install haskell-platform" and press Enter. It will automatically start downloading Haskell on your system after authenticating you with the root password. After installing, you will receive a confirmation message.
Step 4 − Go to your terminal again and run the GHCI command. Once you get the Prelude prompt, you are ready to use Haskell on your local system.
To exit from the GHCI prolog, you can use the command ":quit exit".
Haskell is a purely functional programing language, hence it is much more interactive and intelligent than other programming languages. In this chapter, we will learn about basic data models of Haskell which are actually predefined or somehow intelligently decoded into the computer memory.
Throughout this tutorial, we will use the Haskell online platform available on our website (https://www.tutorialspoint.com/codingground.htm).
Haskell is intelligent enough to decode some number as a number. Therefore, you need not mention its type externally as we usually do in case of other programing languages. As per example go to your prelude command prompt and just run "2+2" and hit enter.
sh-4.3$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> 2+2
You will receive the following output as a result.
4
In the above code, we just passed two numbers as arguments to the GHCI compiler without predefining their type, but compiler could easily decode these two entries as numbers.
Now, let us try a little more complex mathematical calculation and see whether our intelligent compiler give us the correct output or not. Try with "15+(5*5)-40"
Prelude> 15+(5*5)-40
The above expression yields "0" as per the expected output.
0
Like numbers, Haskell can intelligently identify a character given in as an input to it. Go to your Haskell command prompt and type any character with double or single quotation.
Let us provide following line as input and check its output.
Prelude> :t "a"
It will produce the following output −
"a" :: [Char]
Remember you use (:t) while supplying the input. In the above example, (:t) is to include the specific type related to the inputs. We will learn more about this type in the upcoming chapters.
Take a look at the following example where we are passing some invalid input as a char which in turn leads to an error.
Prelude> :t a
<interactive>:1:1: Not in scope: 'a'
Prelude> a
<interactive>:4:1: Not in scope: 'a'
By the error message "<interactive>:4:1: Not in scope: `a'" the Haskell compiler is warning us that it is not able to recognize your input. Haskell is a type of language where everything is represented using a number.
Haskell follows conventional ASCII encoding style. Let us take a look at the following example to understand more −
Prelude> '\97'
'a'
Prelude> '\67'
'C'
Look how your input gets decoded into ASCII format.
A string is nothing but a collection of characters. There is no specific syntax for using string, but Haskell follows the conventional style of representing a string with double quotation.
Take a look at the following example where we are passing the string “Tutorialspoint.com”.
Prelude> :t "tutorialspoint.com"
It will produce the following output on screen −
"tutorialspoint.com" :: [Char]
See how the entire string has been decoded as an array of Char only. Let us move to the other data type and its syntax. Once we start our actual practice, we will be habituated with all the data type and its use.
Boolean data type is also pretty much straightforward like other data type. Look at the following example where we will use different Boolean operations using some Boolean inputs such as "True" or "False".
Prelude> True && True
True
Prelude> True && False
False
Prelude> True || True
True
Prelude> True || False
True
In the above example, we need not mention that "True" and "False" are the Boolean values. Haskell itself can decode it and do the respective operations. Let us modify our inputs with "true" or "false".
Prelude> true
It will produce the following output −
<interactive>:9:1: Not in scope: 'true'
In the above example, Haskell could not differentiate between "true" and a number value, hence our input "true" is not a number. Hence, the Haskell compiler throws an error stating that our input is not its scope.
Like other data types, List is also a very useful data type used in Haskell. As per example, [a,b,c] is a list of characters, hence, by definition, List is a collection of same data type separated by comma.
Like other data types, you need not declare a List as a List. Haskell is intelligent enough to decode your input by looking at the syntax used in the expression.
Take a look at the following example which shows how Haskell treats a List.
Prelude> [1,2,3,4,5]
It will produce the following output −
[1,2,3,4,5]
Lists in Haskell are homogeneous in nature, which means they won’t allow you to declare a list of different kind of data type. Any list like [1,2,3,4,5,a,b,c,d,e,f] will produce an error.
Prelude> [1,2,3,4,5,a,b,c,d,e,f]
This code will produce the following error −
<interactive>:17:12: Not in scope: 'a'
<interactive>:17:14: Not in scope: 'b'
<interactive>:17:16: Not in scope: 'c'
<interactive>:17:18: Not in scope: 'd'
<interactive>:17:20: Not in scope: 'e'
<interactive>:17:22: Not in scope: 'f'
List comprehension is the process of generating a list using mathematical expression. Look at the following example where we are generating a list using mathematical expression in the format of [output | range ,condition].
Prelude> [x*2| x<-[1..10]]
[2,4,6,8,10,12,14,16,18,20]
Prelude> [x*2| x<-[1..5]]
[2,4,6,8,10]
Prelude> [x| x<-[1..5]]
[1,2,3,4,5]
This method of creating one List using mathematical expression is called as List Comprehension.
Haskell provides another way to declare multiple values in a single data type. It is known as Tuple. A Tuple can be considered as a List, however there are some technical differences in between a Tuple and a List.
A Tuple is an immutable data type, as we cannot modify the number of elements at runtime, whereas a List is a mutable data type.
On the other hand, List is a homogeneous data type, but Tuple is heterogeneous in nature, because a Tuple may contain different type of data inside it.
Tuples are represented by single parenthesis. Take a look at the following example to see how Haskell treats a Tuple.
Prelude> (1,1,'a')
It will produce the following output −
(1,1,'a')
In the above example, we have used one Tuple with two number type variables, and a char type variable.
In this chapter, we will learn about different operators used in Haskell. Like other programming languages, Haskell intelligently handles some basic operations like addition, subtraction, multiplication, etc. In the upcoming chapters, we will learn more about different operators and their use.
In this chapter, we will use different operators in Haskell using our online platform (https://www.tutorialspoint.com/codingground.htm). Remember we are using only integer type numbers because we will learn more about decimal type numbers in the subsequent chapters.
As the name suggests, the addition (+) operator is used for addition function. The following sample code shows how you can add two integer numbers in Haskell −
main = do
let var1 = 2
let var2 = 3
putStrLn "The addition of the two numbers is:"
print(var1 + var2)
In the above file, we have created two separate variables var1 and var2. At the end, we are printing the result using the addition operator. Use the compile and execute button to run your code.
This code will produce the following output on screen −
The addition of the two numbers is:
5
As the name suggests, this operator is used for subtraction operation. The following sample code shows how you can subtract two integer numbers in Haskell −
main = do
let var1 = 10
let var2 = 6
putStrLn "The Subtraction of the two numbers is:"
print(var1 - var2)
In this example, we have created two variables var1 and var2. Thereafter, we use the subtraction (−) operator to subtract the two values.
This code will produce the following output on screen −
The Subtraction of the two numbers is:
4
This operator is used for multiplication operations. The following code shows how to multiply two numbers in Haskell using the Multiplication Operator −
main = do
let var1 = 2
let var2 = 3
putStrLn "The Multiplication of the Two Numbers is:"
print(var1 * var2)
This code will produce the following output, when you run it in our online platform −
The Multiplication of the Two Numbers is:
6
Take a look at the following code. It shows how you can divide two numbers in Haskell −
main = do
let var1 = 12
let var2 = 3
putStrLn "The Division of the Two Numbers is:"
print(var1/var2)
It will produce the following output −
The Division of the Two Numbers is:
4.0
Sequence or Range is a special operator in Haskell. It is denoted by "(..)". You can use this operator while declaring a list with a sequence of values.
If you want to print all the values from 1 to 10, then you can use something like "[1..10]". Similarly, if you want to generate all the alphabets from "a" to "z", then you can just type "[a..z]".
The following code shows how you can use the Sequence operator to print all the values from 1 to 10 −
main :: IO()
main = do
print [1..10]
It will generate the following output −
[1,2,3,4,5,6,7,8,9,10]
Decision Making is a feature that allows the programmers to apply a condition in the code flow. The programmer can execute a set of instructions depending on a predefined condition. The following flowchart shows the decision-making structure of Haskell −
Haskell provides the following types of decision-making statements −
One if statement with an else statement. The instruction in the else block will execute only when the given Boolean condition fails to satisfy.
Multiple if blocks followed by else blocks
Haskell is a functional language and it is strictly typed, which means the data type used in the entire application will be known to the compiler at compile time.
In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that "Type" is the data type of the expression used at compile time.
To learn more about the Type, we will use the ":t" command. In a generic way, Type can be considered as a value, whereas Type Class can be the considered as a set of similar kind of Types. In this chapter, we will learn about different Inbuilt Types.
Int is a type class representing the Integer types data. Every whole number within the range of 2147483647 to -2147483647 comes under the Int type class. In the following example, the function fType() will behave according to its type defined.
fType :: Int -> Int -> Int
fType x y = x*x + y*y
main = print (fType 2 4)
Here, we have set the type of the function fType() as int. The function takes two int values and returns one int value. If you compile and execute this piece of code, then it will produce the following output −
sh-4.3$ ghc -O2 --make *.hs -o main -threaded -rtsopts
sh-4.3$ main
20
Integer can be considered as a superset of Int. This value is not bounded by any number, hence an Integer can be of any length without any limitation. To see the basic difference between Int and Integer types, let us modify the above code as follows −
fType :: Int -> Int -> Int
fType x y = x*x + y*y
main = print (fType 212124454 44545454454554545445454544545)
If you compile the above piece of code, the following error message will be thrown −
main.hs:3:31: Warning:
Literal 44545454454554545445454544545 is out of the Int range -
9223372036854775808..9223372036854775807
Linking main ...
This error occurred because our function fType() expecting one Int type value, and we are passing some real big Int type value. To avoid this error, Let us modify the type "Int" with "Integer" and observe the difference.
fType :: Integer -> Integer -> Integer
fType x y = x*x + y*y
main = print (fType 212124454 4454545445455454545445445454544545)
Now, it will produce the following output −
sh-4.3$ main
1984297512562793395882644631364297686099210302577374055141
Take a look at the following piece of code. It shows how Float type works in Haskell −
fType :: Float -> Float -> Float
fType x y = x*x + y*y
main = print (fType 2.5 3.8)
The function takes two float values as the input and yields another float value as the output. When you compile and execute this code, it will produce the following output −
sh-4.3$ main
20.689999
Double is a floating point number with double precision at the end. Take a look at the following example −
fType :: Double -> Double -> Double
fType x y = x*x + y*y
main = print (fType 2.56 3.81)
When you execute the above piece of code, it will generate the following output −
sh-4.3$ main
21.0697
Bool is a Boolean Type. It can be either True or False. Execute the following code to understand how the Bool type works in Haskell −
main = do
let x = True
if x == False
then putStrLn "X matches with Bool Type"
else putStrLn "X is not a Bool Type"
Here, we are defining a variable "x" as a Bool and comparing it with another Boolean value to check its originality. It will produce the following output −
sh-4.3$ main
X is not a Bool Type
Char represent Characters. Anything within a single quote is considered as a Character. In the following code, we have modified our previous fType() function to accept Char value and return Char value as output.
fType :: Char-> Char
fType x = 'K'
main = do
let x = 'v'
print (fType x)
The above piece of code will call fType() function with a char value of 'v' but it returns another char value, that is, 'K'. Here is its output −
sh-4.3$ main
'K'
Note that we are not going to use these types explicitly because Haskell is intelligent enough to catch the type before it is declared. In the subsequent chapters of this tutorial, we will see how different types and Type classes make Haskell a strongly typed language.
EQ type class is an interface which provides the functionality to test the equality of an expression. Any Type class that wants to check the equality of an expression should be a part of this EQ Type Class.
All standard Type classes mentioned above is a part of this EQ class. Whenever we are checking any equality using any of the types mentioned above, we are actually making a call to EQ type class.
In the following example, we are using the EQ Type internally using the "==" or "/=" operation.
main = do
if 8 /= 8
then putStrLn "The values are Equal"
else putStrLn "The values are not Equal"
It will yield the following output −
sh-4.3$ main
The values are not Equal
Ord is another interface class which gives us the functionality of ordering. All the types that we have used so far are a part of this Ord interface. Like EQ interface, Ord interface can be called using ">", "<", "<=", ">=", "compare".
Please find below example where we used “compare ” functionality of this Type Class.
main = print (4 <= 2)
Here, the Haskell compiler will check if 4 is less than or equal to 2. Since it is not, the code will produce the following output −
sh-4.3$ main
False
Show has a functionality to print its argument as a String. Whatever may be its argument, it always prints the result as a String. In the following example, we will print the entire list using this interface. "show" can be used to call this interface.
main = print (show [1..10])
It will produce the following output on the console. Here, the double quotes indicate that it is a String type value.
sh-4.3$ main
"[1,2,3,4,5,6,7,8,9,10]"
Read interface does the same thing as Show, but it won’t print the result in String format. In the following code, we have used the read interface to read a string value and convert the same into an Int value.
main = print (readInt "12")
readInt :: String -> Int
readInt = read
Here, we are passing a String variable ("12") to the readInt method which in turn returns 12 (an Int value) after conversion. Here is its output −
sh-4.3$ main
12
Enum is another type of Type class which enables the sequential or ordered functionality in Haskell. This Type class can be accessed by commands such as Succ, Pred, Bool, Char, etc.
The following code shows how to find the successor value of 12.
main = print (succ 12)
It will produce the following output −
sh-4.3$ main
13
All the types having upper and lower bounds come under this Type Class. For example, Int type data has maximum bound of "9223372036854775807" and minimum bound of "-9223372036854775808".
The following code shows how Haskell determines the maximum and minimum bound of Int type.
main = do
print (maxBound :: Int)
print (minBound :: Int)
It will produce the following output −
sh-4.3$ main
9223372036854775807
-9223372036854775808
Now, try to find the maximum and minimum bound of Char, Float, and Bool types.
This type class is used for numeric operations. Types such as Int, Integer, Float, and Double come under this Type class. Take a look at the following code −
main = do
print(2 :: Int)
print(2 :: Float)
It will produce the following output −
sh-4.3$ main
2
2.0
Integral can be considered as a sub-class of the Num Type Class. Num Type class holds all types of numbers, whereas Integral type class is used only for integral numbers. Int and Integer are the types under this Type class.
Like Integral, Floating is also a part of the Num Type class, but it only holds floating point numbers. Hence, Float and Double come under this type class.
Like any other programming language, Haskell allows developers to define user-defined types. In the following example, we will create a user-defined type and use it.
data Area = Circle Float Float Float
surface :: Area -> Float
surface (Circle _ _ r) = pi * r ^ 2
main = print (surface $ Circle 10 20 10 )
Here, we have created a new type called Area. Next, we are using this type to calculate the area of a circle. In the above example, "surface" is a function that takes Area as an input and produces Float as the output.
Keep in mind that "data" is a keyword here and all user-defined types in Haskell always start with a capital letter.
It will produce the following output −
sh-4.3$ main
314.15927
Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration.
Function declaration consists of the function name and its argument list along with its output.
Function declaration consists of the function name and its argument list along with its output.
Function definition is where you actually define a function.
Function definition is where you actually define a function.
Let us take small example of add function to understand this concept in detail.
add :: Integer -> Integer -> Integer --function declaration
add x y = x + y --function definition
main = do
putStrLn "The addition of the two numbers is:"
print(add 2 5) --calling a function
Here, we have declared our function in the first line and in the second line, we have written our actual function that will take two arguments and produce one integer type output.
Like most other languages, Haskell starts compiling the code from the main method. Our code will generate the following output −
The addition of the two numbers is:
7
Pattern Matching is process of matching specific type of expressions. It is nothing but a technique to simplify your code. This technique can be implemented into any type of Type class. If-Else can be used as an alternate option of pattern matching.
Pattern Matching can be considered as a variant of dynamic polymorphism where at runtime, different methods can be executed depending on their argument list.
Take a look at the following code block. Here we have used the technique of Pattern Matching to calculate the factorial of a number.
fact :: Int -> Int
fact 0 = 1
fact n = n * fact ( n - 1 )
main = do
putStrLn "The factorial of 5 is:"
print (fact 5)
We all know how to calculate the factorial of a number. The compiler will start searching for a function called "fact" with an argument. If the argument is not equal to 0, then the number will keep on calling the same function with 1 less than that of the actual argument.
When the pattern of the argument exactly matches with 0, it will call our pattern which is "fact 0 = 1". Our code will produce the following output −
The factorial of 5 is:
120
Guards is a concept that is very similar to pattern matching. In pattern matching, we usually match one or more expressions, but we use guards to test some property of an expression.
Although it is advisable to use pattern matching over guards, but from a developer’s perspective, guards is more readable and simple. For first-time users, guards can look very similar to If-Else statements, but they are functionally different.
In the following code, we have modified our factorial program by using the concept of guards.
fact :: Integer -> Integer
fact n | n == 0 = 1
| n /= 0 = n * fact (n-1)
main = do
putStrLn "The factorial of 5 is:"
print (fact 5)
Here, we have declared two guards, separated by "|" and calling the fact function from main. Internally, the compiler will work in the same manner as in the case of pattern matching to yield the following output −
The factorial of 5 is:
120
Where is a keyword or inbuilt function that can be used at runtime to generate a desired output. It can be very helpful when function calculation becomes complex.
Consider a scenario where your input is a complex expression with multiple parameters. In such cases, you can break the entire expression into small parts using the "where" clause.
In the following example, we are taking a complex mathematical expression. We will show how you can find the roots of a polynomial equation [x^2 - 8x + 6] using Haskell.
roots :: (Float, Float, Float) -> (Float, Float)
roots (a,b,c) = (x1, x2) where
x1 = e + sqrt d / (2 * a)
x2 = e - sqrt d / (2 * a)
d = b * b - 4 * a * c
e = - b / (2 * a)
main = do
putStrLn "The roots of our Polynomial equation are:"
print (roots(1,-8,6))
Notice the complexity of our expression to calculate the roots of the given polynomial function. It is quite complex. Hence, we are breaking the expression using the where clause. The above piece of code will generate the following output −
The roots of our Polynomial equation are:
(7.1622777,0.8377223)
Recursion is a situation where a function calls itself repeatedly. Haskell does not provide any facility of looping any expression for more than once. Instead, Haskell wants you to break your entire functionality into a collection of different functions and use recursion technique to implement your functionality.
Let us consider our pattern matching example again, where we have calculated the factorial of a number. Finding the factorial of a number is a classic case of using Recursion. Here, you might, "How is pattern matching any different from recursion?” The difference between these two lie in the way they are used. Pattern matching works on setting up the terminal constrain, whereas recursion is a function call.
In the following example, we have used both pattern matching and recursion to calculate the factorial of 5.
fact :: Int -> Int
fact 0 = 1
fact n = n * fact ( n - 1 )
main = do
putStrLn "The factorial of 5 is:"
print (fact 5)
It will produce the following output −
The factorial of 5 is:
120
Till now, what we have seen is that Haskell functions take one type as input and produce another type as output, which is pretty much similar in other imperative languages. Higher Order Functions are a unique feature of Haskell where you can use a function as an input or output argument.
Although it is a virtual concept, but in real-world programs, every function that we define in Haskell use higher-order mechanism to provide output. If you get a chance to look into the library function of Haskell, then you will find that most of the library functions have been written in higher order manner.
Let us take an example where we will import an inbuilt higher order function map and use the same to implement another higher order function according to our choice.
import Data.Char
import Prelude hiding (map)
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map func (x : abc) = func x : map func abc
main = print $ map toUpper "tutorialspoint.com"
In the above example, we have used the toUpper function of the Type Class Char to convert our input into uppercase. Here, the method "map" is taking a function as an argument and returning the required output. Here is its output −
sh-4.3$ ghc -O2 --make *.hs -o main -threaded -rtsopts
sh-4.3$ main
"TUTORIALSPOINT.COM"
We sometimes have to write a function that is going to be used only once, throughout the entire lifespan of an application. To deal with this kind of situations, Haskell developers use another anonymous block known as lambda expression or lambda function.
A function without having a definition is called a lambda function. A lambda function is denoted by "\" character. Let us take the following example where we will increase the input value by 1 without creating any function.
main = do
putStrLn "The successor of 4 is:"
print ((\x -> x + 1) 4)
Here, we have created an anonymous function which does not have a name. It takes the integer 4 as an argument and prints the output value. We are basically operating one function without even declaring it properly. That's the beauty of lambda expressions.
Our lambda expression will produce the following output −
sh-4.3$ main
The successor of 4 is:
5
Till now, we have discussed many types of Haskell functions and used different ways to call those functions. In this chapter, we will learn about some basic functions that can be easily used in Haskell without importing any special Type class. Most of these functions are a part of other higher order functions.
Head function works on a List. It returns the first of the input argument which is basically a list. In the following example, we are passing a list with 10 values and we are generating the first element of that list using the head function.
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "The first element of the list is:"
print (head x)
It will produce the following output −
Our list is:
[1,2,3,4,5,6,7,8,9,10]
The first element of the list is:
1
Tail is the function that complements the head function. It takes a list as the input and yields the entire list without the head part. That means, the tail function returns the entire list without the first element. Take a look at the following example −
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "The tail of our list is:"
print (tail x)
It will produce the following output −
Our list is:
[1,2,3,4,5,6,7,8,9,10]
The tail of our list is:
[2,3,4,5,6,7,8,9,10]
As the name suggests, it yields the last element of the list that is provided as the input. Check the following example.
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "The last element of our list is:"
print (last x)
It will produce the following output −
Our list is:
[1,2,3,4,5,6,7,8,9,10]
The last element of our list is:
10
Init works exactly as the opposite of tail function. It takes a list as an argument and returns the entire list without the last entry.
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "Our list without the last entry:"
print (init x)
Now, observe its output −
Our list is:
[1,2,3,4,5,6,7,8,9,10]
Our list without the last entry:
[1,2,3,4,5,6,7,8,9]
Null is a Boolean check function which works on a String and returns True only when the given list is empty, otherwise it returns False. The following code checks whether the supplied list is empty or not.
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "Is our list empty?"
print (null x)
It will produce the following output −
Our list is:
[1,2,3,4,5,6,7,8,9,10]
Is our list empty?
False
It works on a String input and converts the entire input into reverse order and give one output as a result. Below is the code base for this function.
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "The list in Reverse Order is:"
print (reverse x)
It will produce the following output −
Our list is:
[1,2,3,4,5,6,7,8,9,10]
The list in Reverse Order is:
[10,9,8,7,6,5,4,3,2,1]
This function is used to calculate the length of the list given as an argument. Take a look at the following example −
main = do
let x = [1..10]
putStrLn "Our list is:"
print (x)
putStrLn "The length of this list is:"
print (length x)
We have 10 elements in our list, hence our code will yield 10 as the output.
Our list is:
[1,2,3,4,5,6,7,8,9,10]
The length of this list is:
10
Take function is used to create a sub-string from another String. The following code shows how you can use the take function in Haskell −
main = print(take 5 ([1 .. 10]))
The code generates a sub-string containing 5 elements from the supplied list −
[1,2,3,4,5]
This function is also used to generate a sub-string. It functions as the opposite of the take function. Look at the following piece of code −
main = print(drop 5 ([1 .. 10]))
The code drops the first 5 elements from the supplied list and prints the remaining 5 elements. It will produce the following output −
[6,7,8,9,10]
This function is used to find the element with the maximum value from the supplied list. Let us see how to use it in practice −
main = do
let x = [1,45,565,1245,02,2]
putStrLn "The maximum value element of the list is:"
print (maximum x)
The above piece of code will generate following output −
The maximum value element of the list is:
1245
This function is used to find the element with the minimum value from the supplied list. It’s just the opposite of the maximum function.
main = do
let x = [1,45,565,1245,02,2]
putStrLn "The minimum value element of the list is:"
print (minimum x)
The output of the above code is −
The minimum value element of the list is:
1
As the name suggests, this function returns the summation of all the elements present in the supplied list. The following code takes a list of 5 elements and returns their summation as the output.
main = do
let x = [1..5]
putStrLn "Our list is:"
print (x)
putStrLn "The summation of the list elements is:"
print (sum x)
It will produce the following output −
Our list is:
[1,2,3,4,5]
The summation of the list elements is:
15
You can use this function to multiply all the elements in a list and print its value.
main = do
let x = [1..5]
putStrLn "Our list is:"
print (x)
putStrLn "The multiplication of the list elements is:"
print (product x)
Our code will produce the following output −
Our list is:
[1,2,3,4,5]
The multiplication of the list elements is:
120
This function is used to check whether the supplied list contains a specific element or not. Accordingly, it either returns a true or a false.
The following code checks whether the supplied list of elements contains the value 786.
main = do
let x = [1,45,155,1785]
putStrLn "Our list is:"
print (x)
putStrLn "Does it contain 786?"
print (elem 786 (x))
It will produce the following output −
Our list is:
[1,45,155,1785]
Does it contain 786?
False
Use the same code to check if the supplied list contains the value 1785 or not.
Function Composition is the process of using the output of one function as an input of another function. It will be better if we learn the mathematics behind composition. In mathematics, composition is denoted by f{g(x)} where g() is a function and its output in used as an input of another function, that is, f().
Function composition can be implemented using any two functions, provided the output type of one function matches with the input type of the second function. We use the dot operator (.) to implement function composition in Haskell.
Take a look at the following example code. Here, we have used function composition to calculate whether an input number is even or odd.
eveno :: Int -> Bool
noto :: Bool -> String
eveno x = if x `rem` 2 == 0
then True
else False
noto x = if x == True
then "This is an even Number"
else "This is an ODD number"
main = do
putStrLn "Example of Haskell Function composition"
print ((noto.eveno)(16))
Here, in the main function, we are calling two functions, noto and eveno, simultaneously. The compiler will first call the function "eveno()" with 16 as an argument. Thereafter, the compiler will use the output of the eveno method as an input of noto() method.
Its output would be as follows −
Example of Haskell Function composition
"This is an even Number"
Since we are supplying the number 16 as the input (which is an even number), the eveno() function returns true, which becomes the input for the noto() function and returns the output: "This is an even Number".
If you have worked on Java, then you would know how all the classes are bound into a folder called package. Similarly, Haskell can be considered as a collection of modules.
Haskell is a functional language and everything is denoted as an expression, hence a Module can be called as a collection of similar or related types of functions.
You can import a function from one module into another module. All the "import" statements should come first before you start defining other functions. In this chapter, we will learn the different features of Haskell modules.
List provides some wonderful functions to work with list type data. Once you import the List module, you have a wide range of functions at your disposal.
In the following example, we have used some important functions available under the List module.
import Data.List
main = do
putStrLn("Different methods of List Module")
print(intersperse '.' "Tutorialspoint.com")
print(intercalate " " ["Lets","Start","with","Haskell"])
print(splitAt 7 "HaskellTutorial")
print (sort [8,5,3,2,1,6,4,2])
Here, we have many functions without even defining them. That is because these functions are available in the List module. After importing the List module, the Haskell compiler made all these functions available in the global namespace. Hence, we could use these functions.
Our code will yield the following output −
Different methods of List Module
"T.u.t.o.r.i.a.l.s.p.o.i.n.t...c.o.m"
"Lets Start with Haskell"
("Haskell","Tutorial")
[1,2,2,3,4,5,6,8]
The Char module has plenty of predefined functions to work with the Character type. Take a look at the following code block −
import Data.Char
main = do
putStrLn("Different methods of Char Module")
print(toUpper 'a')
print(words "Let us study tonight")
print(toLower 'A')
Here, the functions toUpper and toLower are already defined inside the Char module. It will produce the following output −
Different methods of Char Module
'A'
["Let","us","study","tonight"]
'a'
Map is an unsorted value-added pair type data type. It is a widely used module with many useful functions. The following example shows how you can use a predefined function available in the Map module.
import Data.Map (Map)
import qualified Data.Map as Map --required for GHCI
myMap :: Integer -> Map Integer [Integer]
myMap n = Map.fromList (map makePair [1..n])
where makePair x = (x, [x])
main = print(myMap 3)
It will produce the following output −
fromList [(1,[1]),(2,[2]),(3,[3])]
The Set module has some very useful predefined functions to manipulate mathematical data. A set is implemented as a binary tree, so all the elements in a set must be unique.
Take a look at the following example code
import qualified Data.Set as Set
text1 = "Hey buddy"
text2 = "This tutorial is for Haskell"
main = do
let set1 = Set.fromList text1
set2 = Set.fromList text2
print(set1)
print(set2)
Here, we are modifying a String into a Set. It will produce the following output. Observe that the output set has no repetition of characters.
fromList " Hbdeuy"
fromList " HTaefhiklorstu"
Let’s see how we can create a custom module that can be called at other programs. To implement this custom module, we will create a separate file called "custom.hs" along with our "main.hs".
Let us create the custom module and define a few functions in it.
module Custom (
showEven,
showBoolean
) where
showEven:: Int-> Bool
showEven x = do
if x 'rem' 2 == 0
then True
else False
showBoolean :: Bool->Int
showBoolean c = do
if c == True
then 1
else 0
Our Custom module is ready. Now, let us import it into a program.
import Custom
main = do
print(showEven 4)
print(showBoolean True)
Our code will generate the following output −
True
1
The showEven function returns True, as "4" is an even number. The showBoolean function returns "1" as the Boolean function that we passed into the function is "True".
All the examples that we have discussed so far are static in nature. In this chapter, we will learn to communicate dynamically with the users. We will learn different input and output techniques used in Haskell.
We have so far hard-coded all the inputs in the program itself. We have been taking inputs from static variables. Now, let us learn how to read and write from an external file.
Let us create a file and name it "abc.txt". Next, enter the following lines in this text file: "Welcome to Tutorialspoint. Here, you will get the best resource to learn Haskell."
Next, we will write the following code which will display the contents of this file on the console. Here, we are using the function readFile() which reads a file until it finds an EOF character.
main = do
let file = "abc.txt"
contents <- readFile file
putStrLn contents
The above piece of code will read the file "abc.txt" as a String until it encounters any End of File character. This piece of code will generate the following output.
Welcome to Tutorialspoint
Here, you will get the best resource to learn Haskell.
Observe that whatever it is printing on the terminal is written in that file.
Haskell also provides the facility to operate a file through the command prompt. Let us get back to our terminal and type "ghci". Then, type the following set of commands −
let file = "abc.txt"
writeFile file "I am just experimenting here."
readFile file
Here, we have created a text file called "abc.txt". Next, we have inserted a statement in the file using the command writeFile. Finally, we have used the command readFile to print the contents of the file on the console. Our code will produce the following output −
I am just experimenting here.
An exception can be considered as a bug in the code. It is a situation where the compiler does not get the expected output at runtime. Like any other good programming language, Haskell provides a way to implement exception handling.
If you are familiar with Java, then you might know the Try-Catch block where we usually throw an error and catch the same in the catch block. In Haskell, we also have the same function to catch runtime errors.
The function definition of try looks like "try :: Exception e => IO a -> IO (Either e a)". Take a look at the following example code. It shows how you can catch the "Divide by Zero" exception.
import Control.Exception
main = do
result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int)
case result of
Left ex -> putStrLn $ "Caught exception: " ++ show ex
Right val -> putStrLn $ "The answer was: " ++ show val
In the above example, we have used the inbuilt try function of the Control.Exception module, hence we are catching the exception beforehand. Above piece of code will yield below output in the screen.
Caught exception: divide by zero
Functor in Haskell is a kind of functional representation of different Types which can be mapped over. It is a high level concept of implementing polymorphism. According to Haskell developers, all the Types such as List, Map, Tree, etc. are the instance of the Haskell Functor.
A Functor is an inbuilt class with a function definition like −
class Functor f where
fmap :: (a -> b) -> f a -> f b
By this definition, we can conclude that the Functor is a function which takes a function, say, fmap() and returns another function. In the above example, fmap() is a generalized representation of the function map().
In the following example, we will see how Haskell Functor works.
main = do
print(map (subtract 1) [2,4,8,16])
print(fmap (subtract 1) [2,4,8,16])
Here, we have used both map() and fmap() over a list for a subtraction operation. You can observe that both the statements will yield the same result of a list containing the elements [1,3,7,15].
Both the functions called another function called subtract() to yield the result.
[1,3,7,15]
[1,3,7,15]
Then, what is the difference between map and fmap? The difference lies in their usage. Functor enables us to implement some more functionalists in different data types, like "just" and "Nothing".
main = do
print (fmap (+7)(Just 10))
print (fmap (+7) Nothing)
The above piece of code will yield the following output on the terminal −
Just 17
Nothing
An Applicative Functor is a normal Functor with some extra features provided by the Applicative Type Class.
Using Functor, we usually map an existing function with another function defined inside it. But there is no any way to map a function which is defined inside a Functor with another Functor. That is why we have another facility called Applicative Functor. This facility of mapping is implemented by Applicative Type class defined under the Control module. This class gives us only two methods to work with: one is pure and the other one is <*>.
Following is the class definition of the Applicative Functor.
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
According to the implementation, we can map another Functor using two methods: "Pure" and "<*>". The "Pure" method should take a value of any type and it will always return an Applicative Functor of that value.
The following example shows how an Applicative Functor works −
import Control.Applicative
f1:: Int -> Int -> Int
f1 x y = 2*x+y
main = do
print(show $ f1 <$> (Just 1) <*> (Just 2) )
Here, we have implemented applicative functors in the function call of the function f1. Our program will yield the following output.
"Just 4"
We all know Haskell defines everything in the form of functions. In functions, we have options to get our input as an output of the function. This is what a Monoid is.
A Monoid is a set of functions and operators where the output is independent of its input. Let’s take a function (*) and an integer (1). Now, whatever may be the input, its output will remain the same number only. That is, if you multiply a number by 1, you will get the same number.
Here is a Type Class definition of monoid.
class Monoid m where
mempty :: m
mappend :: m -> m -> m
mconcat :: [m] -> m
mconcat = foldr mappend mempty
Take a look at the following example to understand the use of Monoid in Haskell.
multi:: Int->Int
multi x = x * 1
add :: Int->Int
add x = x + 0
main = do
print(multi 9)
print (add 7)
Our code will produce the following output −
9
7
Here, the function "multi" multiplies the input with "1". Similarly, the function "add" adds the input with "0". In the both the cases, the output will be same as the input. Hence, the functions {(*),1} and {(+),0} are the perfect examples of monoids.
Monads are nothing but a type of Applicative Functor with some extra features. It is a Type class which governs three basic rules known as monadic rules.
All the three rules are strictly applicable over a Monad declaration which is as follows −
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
x >> y = x >>= \_ -> y
fail :: String -> m a
fail msg = error msg
The three basic laws that are applicable over a Monad declaration are −
Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "return >=> mf = mf".
Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "return >=> mf = mf".
Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "mf >=> return = mf".
Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as "mf >=> return = mf".
Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as "( f >==>g) >=> h =f >= >(g >=h)".
Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as "( f >==>g) >=> h =f >= >(g >=h)".
The first two laws iterate the same point, i.e., a return should have identity behavior on both sides of the bind operator.
We have already used lots of Monads in our previous examples without realizing that they are Monad. Consider the following example where we are using a List Monad to generate a specific list.
main = do
print([1..10] >>= (\x -> if odd x then [x*2] else []))
This code will produce the following output −
[2,6,10,14,18]
Zippers in Haskell are basically pointers that point to some specific location of a data structure such as a tree.
Let us consider a tree having 5 elements [45,7,55,120,56] which can be represented as a perfect binary tree. If I want to update the last element of this list, then I need to traverse through all the elements to reach at the last element before updating it. Right?
But, what if we could construct our tree in such a manner that a tree of having N elements is a collection of [(N-1),N]. Then, we need not traverse through all the unwanted (N-1) elements. We can directly update the Nth element. This is exactly the concept of Zipper. It focuses or points to a specific location of a tree where we can update that value without traversing the entire tree.
In the following example, we have implemented the concept of Zipper in a List. In the same way, one can implement Zipper in a tree or a file data structure.
data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord)
type Zipper_List a = ([a],[a])
go_Forward :: Zipper_List a -> Zipper_List a
go_Forward (x:xs, bs) = (xs, x:bs)
go_Back :: Zipper_List a -> Zipper_List a
go_Back (xs, b:bs) = (b:xs, bs)
main = do
let list_Ex = [1,2,3,4]
print(go_Forward (list_Ex,[]))
print(go_Back([4],[3,2,1]))
When you compile and execute the above program, it will produce the following output −
([2,3,4],[1])
([3,4],[2,1])
Here we are focusing on an element of the entire string while going forward or while coming backward.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2271,
"s": 1915,
"text": "Haskell is a Functional Programming Language that has been specially designed to handle symbolic computation and list processing applications. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional Programming paradigm include: Lisp, Python, Erlang, Racket, F#, Clojure, etc."
},
{
"code": null,
"e": 2508,
"s": 2271,
"text": "In conventional programing, instructions are taken as a set of declarations in a specific syntax or format, but in the case of functional programing, all the computation is considered as a combination of separate mathematical functions."
},
{
"code": null,
"e": 2712,
"s": 2508,
"text": "Haskell is a widely used purely functional language. Here, we have listed down a few points that make this language so special over other conventional programing languages such as Java, C, C++, PHP, etc."
},
{
"code": null,
"e": 2942,
"s": 2712,
"text": "Functional Language − In conventional programing language, we instruct the compiler a series of tasks which is nothing but telling your computer \"what to do\" and \"how to do?\" But in Haskell we will tell our computer \"what it is?\""
},
{
"code": null,
"e": 3172,
"s": 2942,
"text": "Functional Language − In conventional programing language, we instruct the compiler a series of tasks which is nothing but telling your computer \"what to do\" and \"how to do?\" But in Haskell we will tell our computer \"what it is?\""
},
{
"code": null,
"e": 3622,
"s": 3172,
"text": "Laziness − Haskell is a lazy language. By lazy, we mean that Haskell won't evaluate any expression without any reason. When the evaluation engine finds that an expression needs to be evaluated, then it creates a thunk data structure to collect all the required information for that specific evaluation and a pointer to that thunk data structure. The evaluation engine will start working only when it is required to evaluate that specific expression."
},
{
"code": null,
"e": 4072,
"s": 3622,
"text": "Laziness − Haskell is a lazy language. By lazy, we mean that Haskell won't evaluate any expression without any reason. When the evaluation engine finds that an expression needs to be evaluated, then it creates a thunk data structure to collect all the required information for that specific evaluation and a pointer to that thunk data structure. The evaluation engine will start working only when it is required to evaluate that specific expression."
},
{
"code": null,
"e": 4239,
"s": 4072,
"text": "Modularity − A Haskell application is nothing but a series of functions. We can say that a Haskell application is a collection of numerous small Haskell applications."
},
{
"code": null,
"e": 4406,
"s": 4239,
"text": "Modularity − A Haskell application is nothing but a series of functions. We can say that a Haskell application is a collection of numerous small Haskell applications."
},
{
"code": null,
"e": 4788,
"s": 4406,
"text": "Statically Typed − In conventional programing language, we need to define a series of variables along with their type. In contrast, Haskell is a type interference language. By the term, type interference language, we mean the Haskell compiler is intelligent enough to figure out the type of the variable declared, hence we need not explicitly mention the type of the variable used."
},
{
"code": null,
"e": 5170,
"s": 4788,
"text": "Statically Typed − In conventional programing language, we need to define a series of variables along with their type. In contrast, Haskell is a type interference language. By the term, type interference language, we mean the Haskell compiler is intelligent enough to figure out the type of the variable declared, hence we need not explicitly mention the type of the variable used."
},
{
"code": null,
"e": 5285,
"s": 5170,
"text": "Maintainability − Haskell applications are modular and hence, it is very easy and cost-effective to maintain them."
},
{
"code": null,
"e": 5400,
"s": 5285,
"text": "Maintainability − Haskell applications are modular and hence, it is very easy and cost-effective to maintain them."
},
{
"code": null,
"e": 5624,
"s": 5400,
"text": "Functional programs are more concurrent and they follow parallelism in execution to provide more accurate and better performance. Haskell is no exception; it has been developed in a way to handle multithreading effectively."
},
{
"code": null,
"e": 5794,
"s": 5624,
"text": "It is a simple example to demonstrate the dynamism of Haskell. Take a look at the following code. All that we need is just one line to print \"Hello Word\" on the console."
},
{
"code": null,
"e": 5824,
"s": 5794,
"text": "main = putStrLn \"Hello World\""
},
{
"code": null,
"e": 5928,
"s": 5824,
"text": "Once the Haskell compiler encounters the above piece of code, it promptly yields the following output −"
},
{
"code": null,
"e": 5942,
"s": 5928,
"text": "Hello World \n"
},
{
"code": null,
"e": 6051,
"s": 5942,
"text": "We will provide plenty of examples throughout this tutorial to showcase the power and simplicity of Haskell."
},
{
"code": null,
"e": 6171,
"s": 6051,
"text": "We have set up the Haskell programing environment online at −\nhttps://www.tutorialspoint.com/compile_haskell_online.php"
},
{
"code": null,
"e": 6454,
"s": 6171,
"text": "This online editor has plenty of options to practice Haskell programing examples. Go to the terminal section of the page and type \"ghci\". This command automatically loads Haskell compiler and starts Haskell online. You will receive the following output after using the ghci command."
},
{
"code": null,
"e": 6659,
"s": 6454,
"text": "sh-4.3$ ghci\nGHCi,version7.8.4:http://www.haskell.org/ghc/:?forhelp\nLoading package ghc-prim...linking...done.\nLoading packageinteger gmp...linking... done.\nLoading package base...linking...done.\nPrelude>"
},
{
"code": null,
"e": 6839,
"s": 6659,
"text": "If you still want to use Haskell offline in your local system, then you need to download the available Haskell setup from its official webpage − https://www.haskell.org/downloads"
},
{
"code": null,
"e": 6911,
"s": 6839,
"text": "There are three different types of installers available in the market −"
},
{
"code": null,
"e": 7065,
"s": 6911,
"text": "Minimal Installer − It provides GHC (The Glasgow Haskell Compiler), CABAL (Common Architecture for Building Applications and Libraries), and Stack tools."
},
{
"code": null,
"e": 7219,
"s": 7065,
"text": "Minimal Installer − It provides GHC (The Glasgow Haskell Compiler), CABAL (Common Architecture for Building Applications and Libraries), and Stack tools."
},
{
"code": null,
"e": 7489,
"s": 7219,
"text": "Stack Installer − In this installer, the GHC can be downloaded in a cross-platform of managed toll chain. It will install your application globally such that it can update its API tools whenever required. It automatically resolves all the Haskell-oriented dependencies."
},
{
"code": null,
"e": 7759,
"s": 7489,
"text": "Stack Installer − In this installer, the GHC can be downloaded in a cross-platform of managed toll chain. It will install your application globally such that it can update its API tools whenever required. It automatically resolves all the Haskell-oriented dependencies."
},
{
"code": null,
"e": 7984,
"s": 7759,
"text": "Haskell Platform − This is the best way to install Haskell because it will install the entire platform in your machine and that to from one specific location. This installer is not distributive like the above two installers."
},
{
"code": null,
"e": 8209,
"s": 7984,
"text": "Haskell Platform − This is the best way to install Haskell because it will install the entire platform in your machine and that to from one specific location. This installer is not distributive like the above two installers."
},
{
"code": null,
"e": 8437,
"s": 8209,
"text": "We have seen different types of installer available in market now let us see how to use those installers in our machine. In this tutorial we are going to use Haskell platform installer to install Haskell compiler in our system."
},
{
"code": null,
"e": 8640,
"s": 8437,
"text": "To set up Haskell environment on your Windows computer, go to their official website https://www.haskell.org/platform/windows.html and download the Installer according to your customizable architecture."
},
{
"code": null,
"e": 8846,
"s": 8640,
"text": "Check out your system’s architecture and download the corresponding setup file and run it. It will install like any other Windows application. You may need to update the CABAL configuration of your system."
},
{
"code": null,
"e": 8999,
"s": 8846,
"text": "To set up Haskell environment on your MAC system, go to their official website https://www.haskell.org/platform/mac.html and download the Mac installer."
},
{
"code": null,
"e": 9161,
"s": 8999,
"text": "Installing Haskell on a Linux-based system requires to run some command which is not that much easy like MAC and Windows. Yes, it is tiresome but it is reliable."
},
{
"code": null,
"e": 9240,
"s": 9161,
"text": "You can follow the steps given below to install Haskell on your Linux system −"
},
{
"code": null,
"e": 9454,
"s": 9240,
"text": "Step 1 − To set up Haskell environment on your Linux system, go to the official website https://www.haskell.org/platform/linux.html and choose your distribution. You will find the following screen on your browser."
},
{
"code": null,
"e": 9660,
"s": 9454,
"text": "Step 2 − Select your Distribution. In our case, we are using Ubuntu. After selecting this option, you will get the following page on your screen with the command to install the Haskell in our local system."
},
{
"code": null,
"e": 9959,
"s": 9660,
"text": "Step 3 − Open a terminal by pressing Ctrl + Alt + T. Run the command \"$ sudo apt-get install haskell-platform\" and press Enter. It will automatically start downloading Haskell on your system after authenticating you with the root password. After installing, you will receive a confirmation message."
},
{
"code": null,
"e": 10104,
"s": 9959,
"text": "Step 4 − Go to your terminal again and run the GHCI command. Once you get the Prelude prompt, you are ready to use Haskell on your local system."
},
{
"code": null,
"e": 10172,
"s": 10104,
"text": "To exit from the GHCI prolog, you can use the command \":quit exit\"."
},
{
"code": null,
"e": 10463,
"s": 10172,
"text": "Haskell is a purely functional programing language, hence it is much more interactive and intelligent than other programming languages. In this chapter, we will learn about basic data models of Haskell which are actually predefined or somehow intelligently decoded into the computer memory."
},
{
"code": null,
"e": 10605,
"s": 10463,
"text": "Throughout this tutorial, we will use the Haskell online platform available on our website (https://www.tutorialspoint.com/codingground.htm)."
},
{
"code": null,
"e": 10861,
"s": 10605,
"text": "Haskell is intelligent enough to decode some number as a number. Therefore, you need not mention its type externally as we usually do in case of other programing languages. As per example go to your prelude command prompt and just run \"2+2\" and hit enter."
},
{
"code": null,
"e": 11095,
"s": 10861,
"text": "sh-4.3$ ghci \nGHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help \nLoading package ghc-prim ... linking ... done. \nLoading package integer-gmp ... linking ... done. \nLoading package base ... linking ... done. \nPrelude> 2+2\n"
},
{
"code": null,
"e": 11146,
"s": 11095,
"text": "You will receive the following output as a result."
},
{
"code": null,
"e": 11149,
"s": 11146,
"text": "4\n"
},
{
"code": null,
"e": 11324,
"s": 11149,
"text": "In the above code, we just passed two numbers as arguments to the GHCI compiler without predefining their type, but compiler could easily decode these two entries as numbers."
},
{
"code": null,
"e": 11486,
"s": 11324,
"text": "Now, let us try a little more complex mathematical calculation and see whether our intelligent compiler give us the correct output or not. Try with \"15+(5*5)-40\""
},
{
"code": null,
"e": 11509,
"s": 11486,
"text": "Prelude> 15+(5*5)-40 \n"
},
{
"code": null,
"e": 11569,
"s": 11509,
"text": "The above expression yields \"0\" as per the expected output."
},
{
"code": null,
"e": 11572,
"s": 11569,
"text": "0\n"
},
{
"code": null,
"e": 11751,
"s": 11572,
"text": "Like numbers, Haskell can intelligently identify a character given in as an input to it. Go to your Haskell command prompt and type any character with double or single quotation."
},
{
"code": null,
"e": 11812,
"s": 11751,
"text": "Let us provide following line as input and check its output."
},
{
"code": null,
"e": 11830,
"s": 11812,
"text": "Prelude> :t \"a\" \n"
},
{
"code": null,
"e": 11869,
"s": 11830,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 11885,
"s": 11869,
"text": "\"a\" :: [Char] \n"
},
{
"code": null,
"e": 12077,
"s": 11885,
"text": "Remember you use (:t) while supplying the input. In the above example, (:t) is to include the specific type related to the inputs. We will learn more about this type in the upcoming chapters."
},
{
"code": null,
"e": 12197,
"s": 12077,
"text": "Take a look at the following example where we are passing some invalid input as a char which in turn leads to an error."
},
{
"code": null,
"e": 12302,
"s": 12197,
"text": "Prelude> :t a \n<interactive>:1:1: Not in scope: 'a' \n\nPrelude> a \n<interactive>:4:1: Not in scope: 'a' "
},
{
"code": null,
"e": 12520,
"s": 12302,
"text": "By the error message \"<interactive>:4:1: Not in scope: `a'\" the Haskell compiler is warning us that it is not able to recognize your input. Haskell is a type of language where everything is represented using a number."
},
{
"code": null,
"e": 12636,
"s": 12520,
"text": "Haskell follows conventional ASCII encoding style. Let us take a look at the following example to understand more −"
},
{
"code": null,
"e": 12679,
"s": 12636,
"text": "Prelude> '\\97' \n'a' \nPrelude> '\\67' \n'C' "
},
{
"code": null,
"e": 12731,
"s": 12679,
"text": "Look how your input gets decoded into ASCII format."
},
{
"code": null,
"e": 12920,
"s": 12731,
"text": "A string is nothing but a collection of characters. There is no specific syntax for using string, but Haskell follows the conventional style of representing a string with double quotation."
},
{
"code": null,
"e": 13011,
"s": 12920,
"text": "Take a look at the following example where we are passing the string “Tutorialspoint.com”."
},
{
"code": null,
"e": 13045,
"s": 13011,
"text": "Prelude> :t \"tutorialspoint.com\" "
},
{
"code": null,
"e": 13094,
"s": 13045,
"text": "It will produce the following output on screen −"
},
{
"code": null,
"e": 13127,
"s": 13094,
"text": "\"tutorialspoint.com\" :: [Char] \n"
},
{
"code": null,
"e": 13340,
"s": 13127,
"text": "See how the entire string has been decoded as an array of Char only. Let us move to the other data type and its syntax. Once we start our actual practice, we will be habituated with all the data type and its use."
},
{
"code": null,
"e": 13546,
"s": 13340,
"text": "Boolean data type is also pretty much straightforward like other data type. Look at the following example where we will use different Boolean operations using some Boolean inputs such as \"True\" or \"False\"."
},
{
"code": null,
"e": 13668,
"s": 13546,
"text": "Prelude> True && True \nTrue \nPrelude> True && False \nFalse \nPrelude> True || True \nTrue \nPrelude> True || False \nTrue"
},
{
"code": null,
"e": 13870,
"s": 13668,
"text": "In the above example, we need not mention that \"True\" and \"False\" are the Boolean values. Haskell itself can decode it and do the respective operations. Let us modify our inputs with \"true\" or \"false\"."
},
{
"code": null,
"e": 13885,
"s": 13870,
"text": "Prelude> true "
},
{
"code": null,
"e": 13924,
"s": 13885,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 13966,
"s": 13924,
"text": "<interactive>:9:1: Not in scope: 'true' \n"
},
{
"code": null,
"e": 14180,
"s": 13966,
"text": "In the above example, Haskell could not differentiate between \"true\" and a number value, hence our input \"true\" is not a number. Hence, the Haskell compiler throws an error stating that our input is not its scope."
},
{
"code": null,
"e": 14387,
"s": 14180,
"text": "Like other data types, List is also a very useful data type used in Haskell. As per example, [a,b,c] is a list of characters, hence, by definition, List is a collection of same data type separated by comma."
},
{
"code": null,
"e": 14549,
"s": 14387,
"text": "Like other data types, you need not declare a List as a List. Haskell is intelligent enough to decode your input by looking at the syntax used in the expression."
},
{
"code": null,
"e": 14625,
"s": 14549,
"text": "Take a look at the following example which shows how Haskell treats a List."
},
{
"code": null,
"e": 14647,
"s": 14625,
"text": "Prelude> [1,2,3,4,5] "
},
{
"code": null,
"e": 14686,
"s": 14647,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 14700,
"s": 14686,
"text": "[1,2,3,4,5] \n"
},
{
"code": null,
"e": 14888,
"s": 14700,
"text": "Lists in Haskell are homogeneous in nature, which means they won’t allow you to declare a list of different kind of data type. Any list like [1,2,3,4,5,a,b,c,d,e,f] will produce an error."
},
{
"code": null,
"e": 14922,
"s": 14888,
"text": "Prelude> [1,2,3,4,5,a,b,c,d,e,f] "
},
{
"code": null,
"e": 14967,
"s": 14922,
"text": "This code will produce the following error −"
},
{
"code": null,
"e": 15207,
"s": 14967,
"text": "<interactive>:17:12: Not in scope: 'a' \n<interactive>:17:14: Not in scope: 'b' \n<interactive>:17:16: Not in scope: 'c' \n<interactive>:17:18: Not in scope: 'd' \n<interactive>:17:20: Not in scope: 'e' \n<interactive>:17:22: Not in scope: 'f'\n"
},
{
"code": null,
"e": 15430,
"s": 15207,
"text": "List comprehension is the process of generating a list using mathematical expression. Look at the following example where we are generating a list using mathematical expression in the format of [output | range ,condition]."
},
{
"code": null,
"e": 15567,
"s": 15430,
"text": "Prelude> [x*2| x<-[1..10]] \n[2,4,6,8,10,12,14,16,18,20] \nPrelude> [x*2| x<-[1..5]] \n[2,4,6,8,10] \nPrelude> [x| x<-[1..5]] \n[1,2,3,4,5]"
},
{
"code": null,
"e": 15663,
"s": 15567,
"text": "This method of creating one List using mathematical expression is called as List Comprehension."
},
{
"code": null,
"e": 15877,
"s": 15663,
"text": "Haskell provides another way to declare multiple values in a single data type. It is known as Tuple. A Tuple can be considered as a List, however there are some technical differences in between a Tuple and a List."
},
{
"code": null,
"e": 16006,
"s": 15877,
"text": "A Tuple is an immutable data type, as we cannot modify the number of elements at runtime, whereas a List is a mutable data type."
},
{
"code": null,
"e": 16158,
"s": 16006,
"text": "On the other hand, List is a homogeneous data type, but Tuple is heterogeneous in nature, because a Tuple may contain different type of data inside it."
},
{
"code": null,
"e": 16276,
"s": 16158,
"text": "Tuples are represented by single parenthesis. Take a look at the following example to see how Haskell treats a Tuple."
},
{
"code": null,
"e": 16296,
"s": 16276,
"text": "Prelude> (1,1,'a') "
},
{
"code": null,
"e": 16335,
"s": 16296,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 16347,
"s": 16335,
"text": "(1,1,'a') \n"
},
{
"code": null,
"e": 16450,
"s": 16347,
"text": "In the above example, we have used one Tuple with two number type variables, and a char type variable."
},
{
"code": null,
"e": 16745,
"s": 16450,
"text": "In this chapter, we will learn about different operators used in Haskell. Like other programming languages, Haskell intelligently handles some basic operations like addition, subtraction, multiplication, etc. In the upcoming chapters, we will learn more about different operators and their use."
},
{
"code": null,
"e": 17012,
"s": 16745,
"text": "In this chapter, we will use different operators in Haskell using our online platform (https://www.tutorialspoint.com/codingground.htm). Remember we are using only integer type numbers because we will learn more about decimal type numbers in the subsequent chapters."
},
{
"code": null,
"e": 17173,
"s": 17012,
"text": "As the name suggests, the addition (+) operator is used for addition function. The following sample code shows how you can add two integer numbers in Haskell −"
},
{
"code": null,
"e": 17292,
"s": 17173,
"text": "main = do \n let var1 = 2 \n let var2 = 3 \n putStrLn \"The addition of the two numbers is:\" \n print(var1 + var2) "
},
{
"code": null,
"e": 17486,
"s": 17292,
"text": "In the above file, we have created two separate variables var1 and var2. At the end, we are printing the result using the addition operator. Use the compile and execute button to run your code."
},
{
"code": null,
"e": 17542,
"s": 17486,
"text": "This code will produce the following output on screen −"
},
{
"code": null,
"e": 17581,
"s": 17542,
"text": "The addition of the two numbers is:\n5\n"
},
{
"code": null,
"e": 17738,
"s": 17581,
"text": "As the name suggests, this operator is used for subtraction operation. The following sample code shows how you can subtract two integer numbers in Haskell −"
},
{
"code": null,
"e": 17860,
"s": 17738,
"text": "main = do \n let var1 = 10 \n let var2 = 6 \n putStrLn \"The Subtraction of the two numbers is:\" \n print(var1 - var2)"
},
{
"code": null,
"e": 17998,
"s": 17860,
"text": "In this example, we have created two variables var1 and var2. Thereafter, we use the subtraction (−) operator to subtract the two values."
},
{
"code": null,
"e": 18054,
"s": 17998,
"text": "This code will produce the following output on screen −"
},
{
"code": null,
"e": 18096,
"s": 18054,
"text": "The Subtraction of the two numbers is:\n4\n"
},
{
"code": null,
"e": 18249,
"s": 18096,
"text": "This operator is used for multiplication operations. The following code shows how to multiply two numbers in Haskell using the Multiplication Operator −"
},
{
"code": null,
"e": 18374,
"s": 18249,
"text": "main = do \n let var1 = 2 \n let var2 = 3 \n putStrLn \"The Multiplication of the Two Numbers is:\" \n print(var1 * var2) "
},
{
"code": null,
"e": 18460,
"s": 18374,
"text": "This code will produce the following output, when you run it in our online platform −"
},
{
"code": null,
"e": 18506,
"s": 18460,
"text": "The Multiplication of the Two Numbers is:\n6 \n"
},
{
"code": null,
"e": 18594,
"s": 18506,
"text": "Take a look at the following code. It shows how you can divide two numbers in Haskell −"
},
{
"code": null,
"e": 18711,
"s": 18594,
"text": "main = do \n let var1 = 12 \n let var2 = 3 \n putStrLn \"The Division of the Two Numbers is:\" \n print(var1/var2)"
},
{
"code": null,
"e": 18750,
"s": 18711,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 18793,
"s": 18750,
"text": "The Division of the Two Numbers is: \n4.0 \n"
},
{
"code": null,
"e": 18946,
"s": 18793,
"text": "Sequence or Range is a special operator in Haskell. It is denoted by \"(..)\". You can use this operator while declaring a list with a sequence of values."
},
{
"code": null,
"e": 19142,
"s": 18946,
"text": "If you want to print all the values from 1 to 10, then you can use something like \"[1..10]\". Similarly, if you want to generate all the alphabets from \"a\" to \"z\", then you can just type \"[a..z]\"."
},
{
"code": null,
"e": 19244,
"s": 19142,
"text": "The following code shows how you can use the Sequence operator to print all the values from 1 to 10 −"
},
{
"code": null,
"e": 19286,
"s": 19244,
"text": "main :: IO() \nmain = do \n print [1..10]"
},
{
"code": null,
"e": 19326,
"s": 19286,
"text": "It will generate the following output −"
},
{
"code": null,
"e": 19351,
"s": 19326,
"text": "[1,2,3,4,5,6,7,8,9,10] \n"
},
{
"code": null,
"e": 19606,
"s": 19351,
"text": "Decision Making is a feature that allows the programmers to apply a condition in the code flow. The programmer can execute a set of instructions depending on a predefined condition. The following flowchart shows the decision-making structure of Haskell −"
},
{
"code": null,
"e": 19675,
"s": 19606,
"text": "Haskell provides the following types of decision-making statements −"
},
{
"code": null,
"e": 19819,
"s": 19675,
"text": "One if statement with an else statement. The instruction in the else block will execute only when the given Boolean condition fails to satisfy."
},
{
"code": null,
"e": 19862,
"s": 19819,
"text": "Multiple if blocks followed by else blocks"
},
{
"code": null,
"e": 20025,
"s": 19862,
"text": "Haskell is a functional language and it is strictly typed, which means the data type used in the entire application will be known to the compiler at compile time."
},
{
"code": null,
"e": 20234,
"s": 20025,
"text": "In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that \"Type\" is the data type of the expression used at compile time."
},
{
"code": null,
"e": 20485,
"s": 20234,
"text": "To learn more about the Type, we will use the \":t\" command. In a generic way, Type can be considered as a value, whereas Type Class can be the considered as a set of similar kind of Types. In this chapter, we will learn about different Inbuilt Types."
},
{
"code": null,
"e": 20729,
"s": 20485,
"text": "Int is a type class representing the Integer types data. Every whole number within the range of 2147483647 to -2147483647 comes under the Int type class. In the following example, the function fType() will behave according to its type defined."
},
{
"code": null,
"e": 20805,
"s": 20729,
"text": "fType :: Int -> Int -> Int \nfType x y = x*x + y*y\nmain = print (fType 2 4) "
},
{
"code": null,
"e": 21016,
"s": 20805,
"text": "Here, we have set the type of the function fType() as int. The function takes two int values and returns one int value. If you compile and execute this piece of code, then it will produce the following output −"
},
{
"code": null,
"e": 21089,
"s": 21016,
"text": "sh-4.3$ ghc -O2 --make *.hs -o main -threaded -rtsopts \nsh-4.3$ main\n20\n"
},
{
"code": null,
"e": 21341,
"s": 21089,
"text": "Integer can be considered as a superset of Int. This value is not bounded by any number, hence an Integer can be of any length without any limitation. To see the basic difference between Int and Integer types, let us modify the above code as follows −"
},
{
"code": null,
"e": 21453,
"s": 21341,
"text": "fType :: Int -> Int -> Int \nfType x y = x*x + y*y \nmain = print (fType 212124454 44545454454554545445454544545)"
},
{
"code": null,
"e": 21538,
"s": 21453,
"text": "If you compile the above piece of code, the following error message will be thrown −"
},
{
"code": null,
"e": 21703,
"s": 21538,
"text": "main.hs:3:31: Warning: \n Literal 44545454454554545445454544545 is out of the Int range -\n 9223372036854775808..9223372036854775807 \nLinking main ...\n"
},
{
"code": null,
"e": 21924,
"s": 21703,
"text": "This error occurred because our function fType() expecting one Int type value, and we are passing some real big Int type value. To avoid this error, Let us modify the type \"Int\" with \"Integer\" and observe the difference."
},
{
"code": null,
"e": 22054,
"s": 21924,
"text": "fType :: Integer -> Integer -> Integer \nfType x y = x*x + y*y \nmain = print (fType 212124454 4454545445455454545445445454544545) "
},
{
"code": null,
"e": 22098,
"s": 22054,
"text": "Now, it will produce the following output −"
},
{
"code": null,
"e": 22171,
"s": 22098,
"text": "sh-4.3$ main\n1984297512562793395882644631364297686099210302577374055141\n"
},
{
"code": null,
"e": 22258,
"s": 22171,
"text": "Take a look at the following piece of code. It shows how Float type works in Haskell −"
},
{
"code": null,
"e": 22344,
"s": 22258,
"text": "fType :: Float -> Float -> Float \nfType x y = x*x + y*y \nmain = print (fType 2.5 3.8)"
},
{
"code": null,
"e": 22518,
"s": 22344,
"text": "The function takes two float values as the input and yields another float value as the output. When you compile and execute this code, it will produce the following output −"
},
{
"code": null,
"e": 22543,
"s": 22518,
"text": "sh-4.3$ main\n20.689999 \n"
},
{
"code": null,
"e": 22650,
"s": 22543,
"text": "Double is a floating point number with double precision at the end. Take a look at the following example −"
},
{
"code": null,
"e": 22741,
"s": 22650,
"text": "fType :: Double -> Double -> Double \nfType x y = x*x + y*y \nmain = print (fType 2.56 3.81)"
},
{
"code": null,
"e": 22823,
"s": 22741,
"text": "When you execute the above piece of code, it will generate the following output −"
},
{
"code": null,
"e": 22846,
"s": 22823,
"text": "sh-4.3$ main \n21.0697\n"
},
{
"code": null,
"e": 22980,
"s": 22846,
"text": "Bool is a Boolean Type. It can be either True or False. Execute the following code to understand how the Bool type works in Haskell −"
},
{
"code": null,
"e": 23120,
"s": 22980,
"text": "main = do \n let x = True \n \n if x == False \n then putStrLn \"X matches with Bool Type\" \n else putStrLn \"X is not a Bool Type\" "
},
{
"code": null,
"e": 23276,
"s": 23120,
"text": "Here, we are defining a variable \"x\" as a Bool and comparing it with another Boolean value to check its originality. It will produce the following output −"
},
{
"code": null,
"e": 23312,
"s": 23276,
"text": "sh-4.3$ main\nX is not a Bool Type \n"
},
{
"code": null,
"e": 23524,
"s": 23312,
"text": "Char represent Characters. Anything within a single quote is considered as a Character. In the following code, we have modified our previous fType() function to accept Char value and return Char value as output."
},
{
"code": null,
"e": 23609,
"s": 23524,
"text": "fType :: Char-> Char \nfType x = 'K' \nmain = do \n let x = 'v' \n print (fType x) "
},
{
"code": null,
"e": 23755,
"s": 23609,
"text": "The above piece of code will call fType() function with a char value of 'v' but it returns another char value, that is, 'K'. Here is its output −"
},
{
"code": null,
"e": 23774,
"s": 23755,
"text": "sh-4.3$ main \n'K'\n"
},
{
"code": null,
"e": 24044,
"s": 23774,
"text": "Note that we are not going to use these types explicitly because Haskell is intelligent enough to catch the type before it is declared. In the subsequent chapters of this tutorial, we will see how different types and Type classes make Haskell a strongly typed language."
},
{
"code": null,
"e": 24251,
"s": 24044,
"text": "EQ type class is an interface which provides the functionality to test the equality of an expression. Any Type class that wants to check the equality of an expression should be a part of this EQ Type Class."
},
{
"code": null,
"e": 24447,
"s": 24251,
"text": "All standard Type classes mentioned above is a part of this EQ class. Whenever we are checking any equality using any of the types mentioned above, we are actually making a call to EQ type class."
},
{
"code": null,
"e": 24543,
"s": 24447,
"text": "In the following example, we are using the EQ Type internally using the \"==\" or \"/=\" operation."
},
{
"code": null,
"e": 24656,
"s": 24543,
"text": "main = do \n if 8 /= 8 \n then putStrLn \"The values are Equal\" \n else putStrLn \"The values are not Equal\""
},
{
"code": null,
"e": 24693,
"s": 24656,
"text": "It will yield the following output −"
},
{
"code": null,
"e": 24734,
"s": 24693,
"text": "sh-4.3$ main \nThe values are not Equal \n"
},
{
"code": null,
"e": 24971,
"s": 24734,
"text": "Ord is another interface class which gives us the functionality of ordering. All the types that we have used so far are a part of this Ord interface. Like EQ interface, Ord interface can be called using \">\", \"<\", \"<=\", \">=\", \"compare\"."
},
{
"code": null,
"e": 25056,
"s": 24971,
"text": "Please find below example where we used “compare ” functionality of this Type Class."
},
{
"code": null,
"e": 25079,
"s": 25056,
"text": "main = print (4 <= 2) "
},
{
"code": null,
"e": 25212,
"s": 25079,
"text": "Here, the Haskell compiler will check if 4 is less than or equal to 2. Since it is not, the code will produce the following output −"
},
{
"code": null,
"e": 25233,
"s": 25212,
"text": "sh-4.3$ main \nFalse\n"
},
{
"code": null,
"e": 25485,
"s": 25233,
"text": "Show has a functionality to print its argument as a String. Whatever may be its argument, it always prints the result as a String. In the following example, we will print the entire list using this interface. \"show\" can be used to call this interface."
},
{
"code": null,
"e": 25514,
"s": 25485,
"text": "main = print (show [1..10]) "
},
{
"code": null,
"e": 25632,
"s": 25514,
"text": "It will produce the following output on the console. Here, the double quotes indicate that it is a String type value."
},
{
"code": null,
"e": 25673,
"s": 25632,
"text": "sh-4.3$ main \n\"[1,2,3,4,5,6,7,8,9,10]\" \n"
},
{
"code": null,
"e": 25883,
"s": 25673,
"text": "Read interface does the same thing as Show, but it won’t print the result in String format. In the following code, we have used the read interface to read a string value and convert the same into an Int value."
},
{
"code": null,
"e": 25954,
"s": 25883,
"text": "main = print (readInt \"12\") \nreadInt :: String -> Int \nreadInt = read "
},
{
"code": null,
"e": 26101,
"s": 25954,
"text": "Here, we are passing a String variable (\"12\") to the readInt method which in turn returns 12 (an Int value) after conversion. Here is its output −"
},
{
"code": null,
"e": 26119,
"s": 26101,
"text": "sh-4.3$ main \n12\n"
},
{
"code": null,
"e": 26301,
"s": 26119,
"text": "Enum is another type of Type class which enables the sequential or ordered functionality in Haskell. This Type class can be accessed by commands such as Succ, Pred, Bool, Char, etc."
},
{
"code": null,
"e": 26365,
"s": 26301,
"text": "The following code shows how to find the successor value of 12."
},
{
"code": null,
"e": 26389,
"s": 26365,
"text": "main = print (succ 12) "
},
{
"code": null,
"e": 26428,
"s": 26389,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 26445,
"s": 26428,
"text": "sh-4.3$ main\n13\n"
},
{
"code": null,
"e": 26632,
"s": 26445,
"text": "All the types having upper and lower bounds come under this Type Class. For example, Int type data has maximum bound of \"9223372036854775807\" and minimum bound of \"-9223372036854775808\"."
},
{
"code": null,
"e": 26723,
"s": 26632,
"text": "The following code shows how Haskell determines the maximum and minimum bound of Int type."
},
{
"code": null,
"e": 26790,
"s": 26723,
"text": "main = do \n print (maxBound :: Int) \n print (minBound :: Int) "
},
{
"code": null,
"e": 26829,
"s": 26790,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 26884,
"s": 26829,
"text": "sh-4.3$ main\n9223372036854775807\n-9223372036854775808\n"
},
{
"code": null,
"e": 26963,
"s": 26884,
"text": "Now, try to find the maximum and minimum bound of Char, Float, and Bool types."
},
{
"code": null,
"e": 27121,
"s": 26963,
"text": "This type class is used for numeric operations. Types such as Int, Integer, Float, and Double come under this Type class. Take a look at the following code −"
},
{
"code": null,
"e": 27175,
"s": 27121,
"text": "main = do \n print(2 :: Int) \n print(2 :: Float) "
},
{
"code": null,
"e": 27214,
"s": 27175,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 27234,
"s": 27214,
"text": "sh-4.3$ main\n2\n2.0\n"
},
{
"code": null,
"e": 27460,
"s": 27234,
"text": "Integral can be considered as a sub-class of the Num Type Class. Num Type class holds all types of numbers, whereas Integral type class is used only for integral numbers. Int and Integer are the types under this Type class."
},
{
"code": null,
"e": 27616,
"s": 27460,
"text": "Like Integral, Floating is also a part of the Num Type class, but it only holds floating point numbers. Hence, Float and Double come under this type class."
},
{
"code": null,
"e": 27782,
"s": 27616,
"text": "Like any other programming language, Haskell allows developers to define user-defined types. In the following example, we will create a user-defined type and use it."
},
{
"code": null,
"e": 27931,
"s": 27782,
"text": "data Area = Circle Float Float Float \nsurface :: Area -> Float \nsurface (Circle _ _ r) = pi * r ^ 2 \nmain = print (surface $ Circle 10 20 10 ) "
},
{
"code": null,
"e": 28149,
"s": 27931,
"text": "Here, we have created a new type called Area. Next, we are using this type to calculate the area of a circle. In the above example, \"surface\" is a function that takes Area as an input and produces Float as the output."
},
{
"code": null,
"e": 28266,
"s": 28149,
"text": "Keep in mind that \"data\" is a keyword here and all user-defined types in Haskell always start with a capital letter."
},
{
"code": null,
"e": 28305,
"s": 28266,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 28329,
"s": 28305,
"text": "sh-4.3$ main\n314.15927\n"
},
{
"code": null,
"e": 28500,
"s": 28329,
"text": "Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration."
},
{
"code": null,
"e": 28596,
"s": 28500,
"text": "Function declaration consists of the function name and its argument list along with its output."
},
{
"code": null,
"e": 28692,
"s": 28596,
"text": "Function declaration consists of the function name and its argument list along with its output."
},
{
"code": null,
"e": 28753,
"s": 28692,
"text": "Function definition is where you actually define a function."
},
{
"code": null,
"e": 28814,
"s": 28753,
"text": "Function definition is where you actually define a function."
},
{
"code": null,
"e": 28894,
"s": 28814,
"text": "Let us take small example of add function to understand this concept in detail."
},
{
"code": null,
"e": 29126,
"s": 28894,
"text": "add :: Integer -> Integer -> Integer --function declaration \nadd x y = x + y --function definition \n\nmain = do \n putStrLn \"The addition of the two numbers is:\" \n print(add 2 5) --calling a function "
},
{
"code": null,
"e": 29306,
"s": 29126,
"text": "Here, we have declared our function in the first line and in the second line, we have written our actual function that will take two arguments and produce one integer type output."
},
{
"code": null,
"e": 29435,
"s": 29306,
"text": "Like most other languages, Haskell starts compiling the code from the main method. Our code will generate the following output −"
},
{
"code": null,
"e": 29474,
"s": 29435,
"text": "The addition of the two numbers is:\n7\n"
},
{
"code": null,
"e": 29724,
"s": 29474,
"text": "Pattern Matching is process of matching specific type of expressions. It is nothing but a technique to simplify your code. This technique can be implemented into any type of Type class. If-Else can be used as an alternate option of pattern matching."
},
{
"code": null,
"e": 29882,
"s": 29724,
"text": "Pattern Matching can be considered as a variant of dynamic polymorphism where at runtime, different methods can be executed depending on their argument list."
},
{
"code": null,
"e": 30015,
"s": 29882,
"text": "Take a look at the following code block. Here we have used the technique of Pattern Matching to calculate the factorial of a number."
},
{
"code": null,
"e": 30144,
"s": 30015,
"text": "fact :: Int -> Int \nfact 0 = 1 \nfact n = n * fact ( n - 1 ) \n\nmain = do \n putStrLn \"The factorial of 5 is:\" \n print (fact 5)"
},
{
"code": null,
"e": 30417,
"s": 30144,
"text": "We all know how to calculate the factorial of a number. The compiler will start searching for a function called \"fact\" with an argument. If the argument is not equal to 0, then the number will keep on calling the same function with 1 less than that of the actual argument."
},
{
"code": null,
"e": 30567,
"s": 30417,
"text": "When the pattern of the argument exactly matches with 0, it will call our pattern which is \"fact 0 = 1\". Our code will produce the following output −"
},
{
"code": null,
"e": 30595,
"s": 30567,
"text": "The factorial of 5 is:\n120\n"
},
{
"code": null,
"e": 30778,
"s": 30595,
"text": "Guards is a concept that is very similar to pattern matching. In pattern matching, we usually match one or more expressions, but we use guards to test some property of an expression."
},
{
"code": null,
"e": 31023,
"s": 30778,
"text": "Although it is advisable to use pattern matching over guards, but from a developer’s perspective, guards is more readable and simple. For first-time users, guards can look very similar to If-Else statements, but they are functionally different."
},
{
"code": null,
"e": 31117,
"s": 31023,
"text": "In the following code, we have modified our factorial program by using the concept of guards."
},
{
"code": null,
"e": 31269,
"s": 31117,
"text": "fact :: Integer -> Integer \nfact n | n == 0 = 1 \n | n /= 0 = n * fact (n-1) \nmain = do \n putStrLn \"The factorial of 5 is:\" \n print (fact 5) "
},
{
"code": null,
"e": 31483,
"s": 31269,
"text": "Here, we have declared two guards, separated by \"|\" and calling the fact function from main. Internally, the compiler will work in the same manner as in the case of pattern matching to yield the following output −"
},
{
"code": null,
"e": 31511,
"s": 31483,
"text": "The factorial of 5 is:\n120\n"
},
{
"code": null,
"e": 31674,
"s": 31511,
"text": "Where is a keyword or inbuilt function that can be used at runtime to generate a desired output. It can be very helpful when function calculation becomes complex."
},
{
"code": null,
"e": 31855,
"s": 31674,
"text": "Consider a scenario where your input is a complex expression with multiple parameters. In such cases, you can break the entire expression into small parts using the \"where\" clause."
},
{
"code": null,
"e": 32025,
"s": 31855,
"text": "In the following example, we are taking a complex mathematical expression. We will show how you can find the roots of a polynomial equation [x^2 - 8x + 6] using Haskell."
},
{
"code": null,
"e": 32311,
"s": 32025,
"text": "roots :: (Float, Float, Float) -> (Float, Float) \nroots (a,b,c) = (x1, x2) where \n x1 = e + sqrt d / (2 * a) \n x2 = e - sqrt d / (2 * a) \n d = b * b - 4 * a * c \n e = - b / (2 * a) \nmain = do \n putStrLn \"The roots of our Polynomial equation are:\" \n print (roots(1,-8,6))"
},
{
"code": null,
"e": 32552,
"s": 32311,
"text": "Notice the complexity of our expression to calculate the roots of the given polynomial function. It is quite complex. Hence, we are breaking the expression using the where clause. The above piece of code will generate the following output −"
},
{
"code": null,
"e": 32617,
"s": 32552,
"text": "The roots of our Polynomial equation are:\n(7.1622777,0.8377223)\n"
},
{
"code": null,
"e": 32932,
"s": 32617,
"text": "Recursion is a situation where a function calls itself repeatedly. Haskell does not provide any facility of looping any expression for more than once. Instead, Haskell wants you to break your entire functionality into a collection of different functions and use recursion technique to implement your functionality."
},
{
"code": null,
"e": 33343,
"s": 32932,
"text": "Let us consider our pattern matching example again, where we have calculated the factorial of a number. Finding the factorial of a number is a classic case of using Recursion. Here, you might, \"How is pattern matching any different from recursion?” The difference between these two lie in the way they are used. Pattern matching works on setting up the terminal constrain, whereas recursion is a function call."
},
{
"code": null,
"e": 33451,
"s": 33343,
"text": "In the following example, we have used both pattern matching and recursion to calculate the factorial of 5."
},
{
"code": null,
"e": 33581,
"s": 33451,
"text": "fact :: Int -> Int \nfact 0 = 1 \nfact n = n * fact ( n - 1 ) \n\nmain = do \n putStrLn \"The factorial of 5 is:\" \n print (fact 5) "
},
{
"code": null,
"e": 33620,
"s": 33581,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 33648,
"s": 33620,
"text": "The factorial of 5 is:\n120\n"
},
{
"code": null,
"e": 33937,
"s": 33648,
"text": "Till now, what we have seen is that Haskell functions take one type as input and produce another type as output, which is pretty much similar in other imperative languages. Higher Order Functions are a unique feature of Haskell where you can use a function as an input or output argument."
},
{
"code": null,
"e": 34248,
"s": 33937,
"text": "Although it is a virtual concept, but in real-world programs, every function that we define in Haskell use higher-order mechanism to provide output. If you get a chance to look into the library function of Haskell, then you will find that most of the library functions have been written in higher order manner."
},
{
"code": null,
"e": 34414,
"s": 34248,
"text": "Let us take an example where we will import an inbuilt higher order function map and use the same to implement another higher order function according to our choice."
},
{
"code": null,
"e": 34603,
"s": 34414,
"text": "import Data.Char \nimport Prelude hiding (map) \n\nmap :: (a -> b) -> [a] -> [b] \nmap _ [] = [] \nmap func (x : abc) = func x : map func abc \nmain = print $ map toUpper \"tutorialspoint.com\" "
},
{
"code": null,
"e": 34834,
"s": 34603,
"text": "In the above example, we have used the toUpper function of the Type Class Char to convert our input into uppercase. Here, the method \"map\" is taking a function as an argument and returning the required output. Here is its output −"
},
{
"code": null,
"e": 34925,
"s": 34834,
"text": "sh-4.3$ ghc -O2 --make *.hs -o main -threaded -rtsopts\nsh-4.3$ main\n\"TUTORIALSPOINT.COM\" \n"
},
{
"code": null,
"e": 35181,
"s": 34925,
"text": "We sometimes have to write a function that is going to be used only once, throughout the entire lifespan of an application. To deal with this kind of situations, Haskell developers use another anonymous block known as lambda expression or lambda function."
},
{
"code": null,
"e": 35405,
"s": 35181,
"text": "A function without having a definition is called a lambda function. A lambda function is denoted by \"\\\" character. Let us take the following example where we will increase the input value by 1 without creating any function."
},
{
"code": null,
"e": 35482,
"s": 35405,
"text": "main = do \n putStrLn \"The successor of 4 is:\" \n print ((\\x -> x + 1) 4)"
},
{
"code": null,
"e": 35738,
"s": 35482,
"text": "Here, we have created an anonymous function which does not have a name. It takes the integer 4 as an argument and prints the output value. We are basically operating one function without even declaring it properly. That's the beauty of lambda expressions."
},
{
"code": null,
"e": 35796,
"s": 35738,
"text": "Our lambda expression will produce the following output −"
},
{
"code": null,
"e": 35835,
"s": 35796,
"text": "sh-4.3$ main\nThe successor of 4 is:\n5\n"
},
{
"code": null,
"e": 36147,
"s": 35835,
"text": "Till now, we have discussed many types of Haskell functions and used different ways to call those functions. In this chapter, we will learn about some basic functions that can be easily used in Haskell without importing any special Type class. Most of these functions are a part of other higher order functions."
},
{
"code": null,
"e": 36389,
"s": 36147,
"text": "Head function works on a List. It returns the first of the input argument which is basically a list. In the following example, we are passing a list with 10 values and we are generating the first element of that list using the head function."
},
{
"code": null,
"e": 36532,
"s": 36389,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The first element of the list is:\" \n print (head x)"
},
{
"code": null,
"e": 36571,
"s": 36532,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 36645,
"s": 36571,
"text": "Our list is: \n[1,2,3,4,5,6,7,8,9,10]\nThe first element of the list is:\n1\n"
},
{
"code": null,
"e": 36901,
"s": 36645,
"text": "Tail is the function that complements the head function. It takes a list as the input and yields the entire list without the head part. That means, the tail function returns the entire list without the first element. Take a look at the following example −"
},
{
"code": null,
"e": 37036,
"s": 36901,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The tail of our list is:\" \n print (tail x) "
},
{
"code": null,
"e": 37075,
"s": 37036,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 37158,
"s": 37075,
"text": "Our list is:\n[1,2,3,4,5,6,7,8,9,10]\nThe tail of our list is:\n[2,3,4,5,6,7,8,9,10]\n"
},
{
"code": null,
"e": 37279,
"s": 37158,
"text": "As the name suggests, it yields the last element of the list that is provided as the input. Check the following example."
},
{
"code": null,
"e": 37421,
"s": 37279,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The last element of our list is:\" \n print (last x)"
},
{
"code": null,
"e": 37460,
"s": 37421,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 37533,
"s": 37460,
"text": "Our list is:\n[1,2,3,4,5,6,7,8,9,10]\nThe last element of our list is:\n10\n"
},
{
"code": null,
"e": 37669,
"s": 37533,
"text": "Init works exactly as the opposite of tail function. It takes a list as an argument and returns the entire list without the last entry."
},
{
"code": null,
"e": 37813,
"s": 37669,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"Our list without the last entry:\" \n print (init x) "
},
{
"code": null,
"e": 37839,
"s": 37813,
"text": "Now, observe its output −"
},
{
"code": null,
"e": 37929,
"s": 37839,
"text": "Our list is:\n[1,2,3,4,5,6,7,8,9,10]\nOur list without the last entry:\n[1,2,3,4,5,6,7,8,9]\n"
},
{
"code": null,
"e": 38135,
"s": 37929,
"text": "Null is a Boolean check function which works on a String and returns True only when the given list is empty, otherwise it returns False. The following code checks whether the supplied list is empty or not."
},
{
"code": null,
"e": 38264,
"s": 38135,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"Is our list empty?\" \n print (null x)"
},
{
"code": null,
"e": 38303,
"s": 38264,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 38365,
"s": 38303,
"text": "Our list is:\n[1,2,3,4,5,6,7,8,9,10]\nIs our list empty?\nFalse\n"
},
{
"code": null,
"e": 38516,
"s": 38365,
"text": "It works on a String input and converts the entire input into reverse order and give one output as a result. Below is the code base for this function."
},
{
"code": null,
"e": 38656,
"s": 38516,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The list in Reverse Order is:\" \n print (reverse x)"
},
{
"code": null,
"e": 38695,
"s": 38656,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 38785,
"s": 38695,
"text": "Our list is:\n[1,2,3,4,5,6,7,8,9,10]\nThe list in Reverse Order is:\n[10,9,8,7,6,5,4,3,2,1]\n"
},
{
"code": null,
"e": 38904,
"s": 38785,
"text": "This function is used to calculate the length of the list given as an argument. Take a look at the following example −"
},
{
"code": null,
"e": 39042,
"s": 38904,
"text": "main = do \n let x = [1..10] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The length of this list is:\" \n print (length x)"
},
{
"code": null,
"e": 39119,
"s": 39042,
"text": "We have 10 elements in our list, hence our code will yield 10 as the output."
},
{
"code": null,
"e": 39187,
"s": 39119,
"text": "Our list is:\n[1,2,3,4,5,6,7,8,9,10]\nThe length of this list is:\n10\n"
},
{
"code": null,
"e": 39325,
"s": 39187,
"text": "Take function is used to create a sub-string from another String. The following code shows how you can use the take function in Haskell −"
},
{
"code": null,
"e": 39359,
"s": 39325,
"text": "main = print(take 5 ([1 .. 10])) "
},
{
"code": null,
"e": 39438,
"s": 39359,
"text": "The code generates a sub-string containing 5 elements from the supplied list −"
},
{
"code": null,
"e": 39451,
"s": 39438,
"text": "[1,2,3,4,5]\n"
},
{
"code": null,
"e": 39593,
"s": 39451,
"text": "This function is also used to generate a sub-string. It functions as the opposite of the take function. Look at the following piece of code −"
},
{
"code": null,
"e": 39627,
"s": 39593,
"text": "main = print(drop 5 ([1 .. 10])) "
},
{
"code": null,
"e": 39762,
"s": 39627,
"text": "The code drops the first 5 elements from the supplied list and prints the remaining 5 elements. It will produce the following output −"
},
{
"code": null,
"e": 39776,
"s": 39762,
"text": "[6,7,8,9,10]\n"
},
{
"code": null,
"e": 39904,
"s": 39776,
"text": "This function is used to find the element with the maximum value from the supplied list. Let us see how to use it in practice −"
},
{
"code": null,
"e": 40029,
"s": 39904,
"text": "main = do \n let x = [1,45,565,1245,02,2] \n putStrLn \"The maximum value element of the list is:\" \n print (maximum x)"
},
{
"code": null,
"e": 40086,
"s": 40029,
"text": "The above piece of code will generate following output −"
},
{
"code": null,
"e": 40134,
"s": 40086,
"text": "The maximum value element of the list is:\n1245\n"
},
{
"code": null,
"e": 40271,
"s": 40134,
"text": "This function is used to find the element with the minimum value from the supplied list. It’s just the opposite of the maximum function."
},
{
"code": null,
"e": 40396,
"s": 40271,
"text": "main = do \n let x = [1,45,565,1245,02,2] \n putStrLn \"The minimum value element of the list is:\" \n print (minimum x)"
},
{
"code": null,
"e": 40430,
"s": 40396,
"text": "The output of the above code is −"
},
{
"code": null,
"e": 40475,
"s": 40430,
"text": "The minimum value element of the list is:\n1\n"
},
{
"code": null,
"e": 40672,
"s": 40475,
"text": "As the name suggests, this function returns the summation of all the elements present in the supplied list. The following code takes a list of 5 elements and returns their summation as the output."
},
{
"code": null,
"e": 40815,
"s": 40672,
"text": "main = do \n let x = [1..5] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The summation of the list elements is:\" \n print (sum x)"
},
{
"code": null,
"e": 40854,
"s": 40815,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 40922,
"s": 40854,
"text": "Our list is:\n[1,2,3,4,5]\nThe summation of the list elements is:\n15\n"
},
{
"code": null,
"e": 41008,
"s": 40922,
"text": "You can use this function to multiply all the elements in a list and print its value."
},
{
"code": null,
"e": 41161,
"s": 41008,
"text": "main = do \n let x = [1..5] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"The multiplication of the list elements is:\" \n print (product x) "
},
{
"code": null,
"e": 41206,
"s": 41161,
"text": "Our code will produce the following output −"
},
{
"code": null,
"e": 41281,
"s": 41206,
"text": "Our list is:\n[1,2,3,4,5]\nThe multiplication of the list elements is: \n120\n"
},
{
"code": null,
"e": 41424,
"s": 41281,
"text": "This function is used to check whether the supplied list contains a specific element or not. Accordingly, it either returns a true or a false."
},
{
"code": null,
"e": 41512,
"s": 41424,
"text": "The following code checks whether the supplied list of elements contains the value 786."
},
{
"code": null,
"e": 41653,
"s": 41512,
"text": "main = do \n let x = [1,45,155,1785] \n putStrLn \"Our list is:\" \n print (x) \n putStrLn \"Does it contain 786?\" \n print (elem 786 (x))"
},
{
"code": null,
"e": 41692,
"s": 41653,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 41749,
"s": 41692,
"text": "Our list is:\n[1,45,155,1785]\nDoes it contain 786?\nFalse\n"
},
{
"code": null,
"e": 41829,
"s": 41749,
"text": "Use the same code to check if the supplied list contains the value 1785 or not."
},
{
"code": null,
"e": 42144,
"s": 41829,
"text": "Function Composition is the process of using the output of one function as an input of another function. It will be better if we learn the mathematics behind composition. In mathematics, composition is denoted by f{g(x)} where g() is a function and its output in used as an input of another function, that is, f()."
},
{
"code": null,
"e": 42376,
"s": 42144,
"text": "Function composition can be implemented using any two functions, provided the output type of one function matches with the input type of the second function. We use the dot operator (.) to implement function composition in Haskell."
},
{
"code": null,
"e": 42512,
"s": 42376,
"text": "Take a look at the following example code. Here, we have used function composition to calculate whether an input number is even or odd."
},
{
"code": null,
"e": 42797,
"s": 42512,
"text": "eveno :: Int -> Bool \nnoto :: Bool -> String \n\neveno x = if x `rem` 2 == 0 \n then True \nelse False \nnoto x = if x == True \n then \"This is an even Number\" \nelse \"This is an ODD number\" \n\nmain = do \n putStrLn \"Example of Haskell Function composition\" \n print ((noto.eveno)(16))"
},
{
"code": null,
"e": 43058,
"s": 42797,
"text": "Here, in the main function, we are calling two functions, noto and eveno, simultaneously. The compiler will first call the function \"eveno()\" with 16 as an argument. Thereafter, the compiler will use the output of the eveno method as an input of noto() method."
},
{
"code": null,
"e": 43091,
"s": 43058,
"text": "Its output would be as follows −"
},
{
"code": null,
"e": 43173,
"s": 43091,
"text": "Example of Haskell Function composition \n\"This is an even Number\"\n"
},
{
"code": null,
"e": 43383,
"s": 43173,
"text": "Since we are supplying the number 16 as the input (which is an even number), the eveno() function returns true, which becomes the input for the noto() function and returns the output: \"This is an even Number\"."
},
{
"code": null,
"e": 43556,
"s": 43383,
"text": "If you have worked on Java, then you would know how all the classes are bound into a folder called package. Similarly, Haskell can be considered as a collection of modules."
},
{
"code": null,
"e": 43720,
"s": 43556,
"text": "Haskell is a functional language and everything is denoted as an expression, hence a Module can be called as a collection of similar or related types of functions."
},
{
"code": null,
"e": 43946,
"s": 43720,
"text": "You can import a function from one module into another module. All the \"import\" statements should come first before you start defining other functions. In this chapter, we will learn the different features of Haskell modules."
},
{
"code": null,
"e": 44100,
"s": 43946,
"text": "List provides some wonderful functions to work with list type data. Once you import the List module, you have a wide range of functions at your disposal."
},
{
"code": null,
"e": 44197,
"s": 44100,
"text": "In the following example, we have used some important functions available under the List module."
},
{
"code": null,
"e": 44460,
"s": 44197,
"text": "import Data.List \n\nmain = do \n putStrLn(\"Different methods of List Module\") \n print(intersperse '.' \"Tutorialspoint.com\") \n print(intercalate \" \" [\"Lets\",\"Start\",\"with\",\"Haskell\"]) \n print(splitAt 7 \"HaskellTutorial\") \n print (sort [8,5,3,2,1,6,4,2])"
},
{
"code": null,
"e": 44734,
"s": 44460,
"text": "Here, we have many functions without even defining them. That is because these functions are available in the List module. After importing the List module, the Haskell compiler made all these functions available in the global namespace. Hence, we could use these functions."
},
{
"code": null,
"e": 44777,
"s": 44734,
"text": "Our code will yield the following output −"
},
{
"code": null,
"e": 44916,
"s": 44777,
"text": "Different methods of List Module\n\"T.u.t.o.r.i.a.l.s.p.o.i.n.t...c.o.m\"\n\"Lets Start with Haskell\"\n(\"Haskell\",\"Tutorial\")\n[1,2,2,3,4,5,6,8]\n"
},
{
"code": null,
"e": 45042,
"s": 44916,
"text": "The Char module has plenty of predefined functions to work with the Character type. Take a look at the following code block −"
},
{
"code": null,
"e": 45207,
"s": 45042,
"text": "import Data.Char \n\nmain = do \n putStrLn(\"Different methods of Char Module\") \n print(toUpper 'a') \n print(words \"Let us study tonight\") \n print(toLower 'A')"
},
{
"code": null,
"e": 45330,
"s": 45207,
"text": "Here, the functions toUpper and toLower are already defined inside the Char module. It will produce the following output −"
},
{
"code": null,
"e": 45403,
"s": 45330,
"text": "Different methods of Char Module\n'A'\n[\"Let\",\"us\",\"study\",\"tonight\"]\n'a'\n"
},
{
"code": null,
"e": 45605,
"s": 45403,
"text": "Map is an unsorted value-added pair type data type. It is a widely used module with many useful functions. The following example shows how you can use a predefined function available in the Map module."
},
{
"code": null,
"e": 45830,
"s": 45605,
"text": "import Data.Map (Map) \nimport qualified Data.Map as Map --required for GHCI \n\nmyMap :: Integer -> Map Integer [Integer] \nmyMap n = Map.fromList (map makePair [1..n]) \n where makePair x = (x, [x]) \n\nmain = print(myMap 3)"
},
{
"code": null,
"e": 45869,
"s": 45830,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 45906,
"s": 45869,
"text": "fromList [(1,[1]),(2,[2]),(3,[3])] \n"
},
{
"code": null,
"e": 46080,
"s": 45906,
"text": "The Set module has some very useful predefined functions to manipulate mathematical data. A set is implemented as a binary tree, so all the elements in a set must be unique."
},
{
"code": null,
"e": 46122,
"s": 46080,
"text": "Take a look at the following example code"
},
{
"code": null,
"e": 46342,
"s": 46122,
"text": "import qualified Data.Set as Set \n\ntext1 = \"Hey buddy\" \ntext2 = \"This tutorial is for Haskell\" \n\nmain = do \n let set1 = Set.fromList text1 \n set2 = Set.fromList text2 \n print(set1) \n print(set2) "
},
{
"code": null,
"e": 46485,
"s": 46342,
"text": "Here, we are modifying a String into a Set. It will produce the following output. Observe that the output set has no repetition of characters."
},
{
"code": null,
"e": 46532,
"s": 46485,
"text": "fromList \" Hbdeuy\"\nfromList \" HTaefhiklorstu\"\n"
},
{
"code": null,
"e": 46723,
"s": 46532,
"text": "Let’s see how we can create a custom module that can be called at other programs. To implement this custom module, we will create a separate file called \"custom.hs\" along with our \"main.hs\"."
},
{
"code": null,
"e": 46789,
"s": 46723,
"text": "Let us create the custom module and define a few functions in it."
},
{
"code": null,
"e": 47012,
"s": 46789,
"text": "module Custom ( \n showEven, \n showBoolean \n) where \n\nshowEven:: Int-> Bool \nshowEven x = do \n\nif x 'rem' 2 == 0 \n then True \nelse False \nshowBoolean :: Bool->Int \nshowBoolean c = do \n\nif c == True \n then 1 \nelse 0 "
},
{
"code": null,
"e": 47078,
"s": 47012,
"text": "Our Custom module is ready. Now, let us import it into a program."
},
{
"code": null,
"e": 47155,
"s": 47078,
"text": "import Custom \n\nmain = do \n print(showEven 4) \n print(showBoolean True) "
},
{
"code": null,
"e": 47201,
"s": 47155,
"text": "Our code will generate the following output −"
},
{
"code": null,
"e": 47209,
"s": 47201,
"text": "True\n1\n"
},
{
"code": null,
"e": 47376,
"s": 47209,
"text": "The showEven function returns True, as \"4\" is an even number. The showBoolean function returns \"1\" as the Boolean function that we passed into the function is \"True\"."
},
{
"code": null,
"e": 47588,
"s": 47376,
"text": "All the examples that we have discussed so far are static in nature. In this chapter, we will learn to communicate dynamically with the users. We will learn different input and output techniques used in Haskell."
},
{
"code": null,
"e": 47765,
"s": 47588,
"text": "We have so far hard-coded all the inputs in the program itself. We have been taking inputs from static variables. Now, let us learn how to read and write from an external file."
},
{
"code": null,
"e": 47944,
"s": 47765,
"text": "Let us create a file and name it \"abc.txt\". Next, enter the following lines in this text file: \"Welcome to Tutorialspoint. Here, you will get the best resource to learn Haskell.\""
},
{
"code": null,
"e": 48139,
"s": 47944,
"text": "Next, we will write the following code which will display the contents of this file on the console. Here, we are using the function readFile() which reads a file until it finds an EOF character."
},
{
"code": null,
"e": 48230,
"s": 48139,
"text": "main = do \n let file = \"abc.txt\" \n contents <- readFile file \n putStrLn contents "
},
{
"code": null,
"e": 48398,
"s": 48230,
"text": "The above piece of code will read the file \"abc.txt\" as a String until it encounters any End of File character. This piece of code will generate the following output."
},
{
"code": null,
"e": 48480,
"s": 48398,
"text": "Welcome to Tutorialspoint\nHere, you will get the best resource to learn Haskell.\n"
},
{
"code": null,
"e": 48558,
"s": 48480,
"text": "Observe that whatever it is printing on the terminal is written in that file."
},
{
"code": null,
"e": 48731,
"s": 48558,
"text": "Haskell also provides the facility to operate a file through the command prompt. Let us get back to our terminal and type \"ghci\". Then, type the following set of commands −"
},
{
"code": null,
"e": 48817,
"s": 48731,
"text": "let file = \"abc.txt\" \nwriteFile file \"I am just experimenting here.\" \nreadFile file \n"
},
{
"code": null,
"e": 49083,
"s": 48817,
"text": "Here, we have created a text file called \"abc.txt\". Next, we have inserted a statement in the file using the command writeFile. Finally, we have used the command readFile to print the contents of the file on the console. Our code will produce the following output −"
},
{
"code": null,
"e": 49114,
"s": 49083,
"text": "I am just experimenting here.\n"
},
{
"code": null,
"e": 49347,
"s": 49114,
"text": "An exception can be considered as a bug in the code. It is a situation where the compiler does not get the expected output at runtime. Like any other good programming language, Haskell provides a way to implement exception handling."
},
{
"code": null,
"e": 49557,
"s": 49347,
"text": "If you are familiar with Java, then you might know the Try-Catch block where we usually throw an error and catch the same in the catch block. In Haskell, we also have the same function to catch runtime errors."
},
{
"code": null,
"e": 49750,
"s": 49557,
"text": "The function definition of try looks like \"try :: Exception e => IO a -> IO (Either e a)\". Take a look at the following example code. It shows how you can catch the \"Divide by Zero\" exception."
},
{
"code": null,
"e": 50006,
"s": 49750,
"text": "import Control.Exception \n\nmain = do \n result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int) \n case result of \n Left ex -> putStrLn $ \"Caught exception: \" ++ show ex \n Right val -> putStrLn $ \"The answer was: \" ++ show val "
},
{
"code": null,
"e": 50206,
"s": 50006,
"text": "In the above example, we have used the inbuilt try function of the Control.Exception module, hence we are catching the exception beforehand. Above piece of code will yield below output in the screen."
},
{
"code": null,
"e": 50241,
"s": 50206,
"text": "Caught exception: divide by zero \n"
},
{
"code": null,
"e": 50519,
"s": 50241,
"text": "Functor in Haskell is a kind of functional representation of different Types which can be mapped over. It is a high level concept of implementing polymorphism. According to Haskell developers, all the Types such as List, Map, Tree, etc. are the instance of the Haskell Functor."
},
{
"code": null,
"e": 50583,
"s": 50519,
"text": "A Functor is an inbuilt class with a function definition like −"
},
{
"code": null,
"e": 50641,
"s": 50583,
"text": "class Functor f where \n fmap :: (a -> b) -> f a -> f b "
},
{
"code": null,
"e": 50858,
"s": 50641,
"text": "By this definition, we can conclude that the Functor is a function which takes a function, say, fmap() and returns another function. In the above example, fmap() is a generalized representation of the function map()."
},
{
"code": null,
"e": 50923,
"s": 50858,
"text": "In the following example, we will see how Haskell Functor works."
},
{
"code": null,
"e": 51021,
"s": 50923,
"text": "main = do \n print(map (subtract 1) [2,4,8,16]) \n print(fmap (subtract 1) [2,4,8,16]) "
},
{
"code": null,
"e": 51217,
"s": 51021,
"text": "Here, we have used both map() and fmap() over a list for a subtraction operation. You can observe that both the statements will yield the same result of a list containing the elements [1,3,7,15]."
},
{
"code": null,
"e": 51299,
"s": 51217,
"text": "Both the functions called another function called subtract() to yield the result."
},
{
"code": null,
"e": 51322,
"s": 51299,
"text": "[1,3,7,15]\n[1,3,7,15]\n"
},
{
"code": null,
"e": 51518,
"s": 51322,
"text": "Then, what is the difference between map and fmap? The difference lies in their usage. Functor enables us to implement some more functionalists in different data types, like \"just\" and \"Nothing\"."
},
{
"code": null,
"e": 51591,
"s": 51518,
"text": "main = do \n print (fmap (+7)(Just 10)) \n print (fmap (+7) Nothing)"
},
{
"code": null,
"e": 51665,
"s": 51591,
"text": "The above piece of code will yield the following output on the terminal −"
},
{
"code": null,
"e": 51682,
"s": 51665,
"text": "Just 17\nNothing\n"
},
{
"code": null,
"e": 51790,
"s": 51682,
"text": "An Applicative Functor is a normal Functor with some extra features provided by the Applicative Type Class."
},
{
"code": null,
"e": 52234,
"s": 51790,
"text": "Using Functor, we usually map an existing function with another function defined inside it. But there is no any way to map a function which is defined inside a Functor with another Functor. That is why we have another facility called Applicative Functor. This facility of mapping is implemented by Applicative Type class defined under the Control module. This class gives us only two methods to work with: one is pure and the other one is <*>."
},
{
"code": null,
"e": 52296,
"s": 52234,
"text": "Following is the class definition of the Applicative Functor."
},
{
"code": null,
"e": 52403,
"s": 52296,
"text": "class (Functor f) => Applicative f where \n pure :: a -> f a \n (<*>) :: f (a -> b) -> f a -> f b "
},
{
"code": null,
"e": 52614,
"s": 52403,
"text": "According to the implementation, we can map another Functor using two methods: \"Pure\" and \"<*>\". The \"Pure\" method should take a value of any type and it will always return an Applicative Functor of that value."
},
{
"code": null,
"e": 52677,
"s": 52614,
"text": "The following example shows how an Applicative Functor works −"
},
{
"code": null,
"e": 52807,
"s": 52677,
"text": "import Control.Applicative \n\nf1:: Int -> Int -> Int \nf1 x y = 2*x+y \nmain = do \n print(show $ f1 <$> (Just 1) <*> (Just 2) ) "
},
{
"code": null,
"e": 52940,
"s": 52807,
"text": "Here, we have implemented applicative functors in the function call of the function f1. Our program will yield the following output."
},
{
"code": null,
"e": 52950,
"s": 52940,
"text": "\"Just 4\"\n"
},
{
"code": null,
"e": 53118,
"s": 52950,
"text": "We all know Haskell defines everything in the form of functions. In functions, we have options to get our input as an output of the function. This is what a Monoid is."
},
{
"code": null,
"e": 53402,
"s": 53118,
"text": "A Monoid is a set of functions and operators where the output is independent of its input. Let’s take a function (*) and an integer (1). Now, whatever may be the input, its output will remain the same number only. That is, if you multiply a number by 1, you will get the same number."
},
{
"code": null,
"e": 53445,
"s": 53402,
"text": "Here is a Type Class definition of monoid."
},
{
"code": null,
"e": 53571,
"s": 53445,
"text": "class Monoid m where \n mempty :: m \n mappend :: m -> m -> m \n mconcat :: [m] -> m \n mconcat = foldr mappend mempty "
},
{
"code": null,
"e": 53652,
"s": 53571,
"text": "Take a look at the following example to understand the use of Monoid in Haskell."
},
{
"code": null,
"e": 53769,
"s": 53652,
"text": "multi:: Int->Int \nmulti x = x * 1 \nadd :: Int->Int \nadd x = x + 0 \n\nmain = do \n print(multi 9) \n print (add 7)"
},
{
"code": null,
"e": 53814,
"s": 53769,
"text": "Our code will produce the following output −"
},
{
"code": null,
"e": 53819,
"s": 53814,
"text": "9\n7\n"
},
{
"code": null,
"e": 54071,
"s": 53819,
"text": "Here, the function \"multi\" multiplies the input with \"1\". Similarly, the function \"add\" adds the input with \"0\". In the both the cases, the output will be same as the input. Hence, the functions {(*),1} and {(+),0} are the perfect examples of monoids."
},
{
"code": null,
"e": 54225,
"s": 54071,
"text": "Monads are nothing but a type of Applicative Functor with some extra features. It is a Type class which governs three basic rules known as monadic rules."
},
{
"code": null,
"e": 54316,
"s": 54225,
"text": "All the three rules are strictly applicable over a Monad declaration which is as follows −"
},
{
"code": null,
"e": 54508,
"s": 54316,
"text": "class Monad m where \n return :: a -> m a \n (>>=) :: m a -> (a -> m b) -> m b \n (>>) :: m a -> m b -> m b \n x >> y = x >>= \\_ -> y \n fail :: String -> m a \n fail msg = error msg "
},
{
"code": null,
"e": 54580,
"s": 54508,
"text": "The three basic laws that are applicable over a Monad declaration are −"
},
{
"code": null,
"e": 54739,
"s": 54580,
"text": "Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"return >=> mf = mf\"."
},
{
"code": null,
"e": 54898,
"s": 54739,
"text": "Left Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"return >=> mf = mf\"."
},
{
"code": null,
"e": 55058,
"s": 54898,
"text": "Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"mf >=> return = mf\"."
},
{
"code": null,
"e": 55218,
"s": 55058,
"text": "Right Identity Law − The return function does not change the value and it should not change anything in the Monad. It can be expressed as \"mf >=> return = mf\"."
},
{
"code": null,
"e": 55395,
"s": 55218,
"text": "Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as \"( f >==>g) >=> h =f >= >(g >=h)\"."
},
{
"code": null,
"e": 55572,
"s": 55395,
"text": "Associativity − According to this law, both Functors and Monad instance should work in the same manner. It can be mathematically expressed as \"( f >==>g) >=> h =f >= >(g >=h)\"."
},
{
"code": null,
"e": 55696,
"s": 55572,
"text": "The first two laws iterate the same point, i.e., a return should have identity behavior on both sides of the bind operator."
},
{
"code": null,
"e": 55888,
"s": 55696,
"text": "We have already used lots of Monads in our previous examples without realizing that they are Monad. Consider the following example where we are using a List Monad to generate a specific list."
},
{
"code": null,
"e": 55956,
"s": 55888,
"text": "main = do\n print([1..10] >>= (\\x -> if odd x then [x*2] else []))"
},
{
"code": null,
"e": 56002,
"s": 55956,
"text": "This code will produce the following output −"
},
{
"code": null,
"e": 56018,
"s": 56002,
"text": "[2,6,10,14,18]\n"
},
{
"code": null,
"e": 56133,
"s": 56018,
"text": "Zippers in Haskell are basically pointers that point to some specific location of a data structure such as a tree."
},
{
"code": null,
"e": 56398,
"s": 56133,
"text": "Let us consider a tree having 5 elements [45,7,55,120,56] which can be represented as a perfect binary tree. If I want to update the last element of this list, then I need to traverse through all the elements to reach at the last element before updating it. Right?"
},
{
"code": null,
"e": 56787,
"s": 56398,
"text": "But, what if we could construct our tree in such a manner that a tree of having N elements is a collection of [(N-1),N]. Then, we need not traverse through all the unwanted (N-1) elements. We can directly update the Nth element. This is exactly the concept of Zipper. It focuses or points to a specific location of a tree where we can update that value without traversing the entire tree."
},
{
"code": null,
"e": 56944,
"s": 56787,
"text": "In the following example, we have implemented the concept of Zipper in a List. In the same way, one can implement Zipper in a tree or a file data structure."
},
{
"code": null,
"e": 57333,
"s": 56944,
"text": "data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord)\ntype Zipper_List a = ([a],[a]) \n\ngo_Forward :: Zipper_List a -> Zipper_List a \ngo_Forward (x:xs, bs) = (xs, x:bs) \n \ngo_Back :: Zipper_List a -> Zipper_List a \ngo_Back (xs, b:bs) = (b:xs, bs) \n\nmain = do \n let list_Ex = [1,2,3,4] \n print(go_Forward (list_Ex,[])) \n print(go_Back([4],[3,2,1])) "
},
{
"code": null,
"e": 57420,
"s": 57333,
"text": "When you compile and execute the above program, it will produce the following output −"
},
{
"code": null,
"e": 57450,
"s": 57420,
"text": "([2,3,4],[1]) \n([3,4],[2,1])\n"
},
{
"code": null,
"e": 57552,
"s": 57450,
"text": "Here we are focusing on an element of the entire string while going forward or while coming backward."
},
{
"code": null,
"e": 57559,
"s": 57552,
"text": " Print"
},
{
"code": null,
"e": 57570,
"s": 57559,
"text": " Add Notes"
}
] |
numpy.matmul()
|
The numpy.matmul() function returns the matrix product of two arrays. While it returns a normal product for 2-D arrays, if dimensions of either argument is >2, it is treated as a stack of matrices residing in the last two indexes and is broadcast accordingly.
On the other hand, if either argument is 1-D array, it is promoted to a matrix by appending a 1 to its dimension, which is removed after multiplication.
# For 2-D array, it is matrix multiplication
import numpy.matlib
import numpy as np
a = [[1,0],[0,1]]
b = [[4,1],[2,2]]
print np.matmul(a,b)
It will produce the following output −
[[4 1]
[2 2]]
# 2-D mixed with 1-D
import numpy.matlib
import numpy as np
a = [[1,0],[0,1]]
b = [1,2]
print np.matmul(a,b)
print np.matmul(b,a)
It will produce the following output −
[1 2]
[1 2]
# one array having dimensions > 2
import numpy.matlib
import numpy as np
a = np.arange(8).reshape(2,2,2)
b = np.arange(4).reshape(2,2)
print np.matmul(a,b)
It will produce the following output −
[[[2 3]
[6 11]]
[[10 19]
[14 27]]]
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2503,
"s": 2243,
"text": "The numpy.matmul() function returns the matrix product of two arrays. While it returns a normal product for 2-D arrays, if dimensions of either argument is >2, it is treated as a stack of matrices residing in the last two indexes and is broadcast accordingly."
},
{
"code": null,
"e": 2656,
"s": 2503,
"text": "On the other hand, if either argument is 1-D array, it is promoted to a matrix by appending a 1 to its dimension, which is removed after multiplication."
},
{
"code": null,
"e": 2803,
"s": 2656,
"text": "# For 2-D array, it is matrix multiplication \nimport numpy.matlib \nimport numpy as np \n\na = [[1,0],[0,1]] \nb = [[4,1],[2,2]] \nprint np.matmul(a,b)"
},
{
"code": null,
"e": 2842,
"s": 2803,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 2862,
"s": 2842,
"text": "[[4 1] \n [2 2]] \n"
},
{
"code": null,
"e": 2999,
"s": 2862,
"text": "# 2-D mixed with 1-D \nimport numpy.matlib \nimport numpy as np \n\na = [[1,0],[0,1]] \nb = [1,2] \nprint np.matmul(a,b) \nprint np.matmul(b,a)"
},
{
"code": null,
"e": 3038,
"s": 2999,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3055,
"s": 3038,
"text": "[1 2] \n[1 2] \n"
},
{
"code": null,
"e": 3217,
"s": 3055,
"text": "# one array having dimensions > 2 \nimport numpy.matlib \nimport numpy as np \n\na = np.arange(8).reshape(2,2,2) \nb = np.arange(4).reshape(2,2) \nprint np.matmul(a,b)"
},
{
"code": null,
"e": 3256,
"s": 3217,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3309,
"s": 3256,
"text": "[[[2 3] \n [6 11]] \n [[10 19] \n [14 27]]]\n"
},
{
"code": null,
"e": 3342,
"s": 3309,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3359,
"s": 3342,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3392,
"s": 3359,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3427,
"s": 3392,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3460,
"s": 3427,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3495,
"s": 3460,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3530,
"s": 3495,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3542,
"s": 3530,
"text": " Akbar Khan"
},
{
"code": null,
"e": 3575,
"s": 3542,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3590,
"s": 3575,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 3623,
"s": 3590,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3630,
"s": 3623,
"text": " Anmol"
},
{
"code": null,
"e": 3637,
"s": 3630,
"text": " Print"
},
{
"code": null,
"e": 3648,
"s": 3637,
"text": " Add Notes"
}
] |
How to add a Time picker in Form using HTML5 ? - GeeksforGeeks
|
25 Oct, 2021
As we know that a Time picker is used to provide tp select single value from a pre-determined set. Basically, it creates an input field that accepts a time. We can open a time picker by clicking on a clock icon. The UI Design of the Time picker is different from browser to browsers.
Follow the below approach to complete the task:
Firstly, we create an HTML document that contains a Form element.
Add an <input> tag under the form.
Use the type attribute with the input element.
Set the type attribute to value “time”.
Syntax:
<input type="time">
Example:
HTML
<!DOCTYPE html><html> <head> <title> How to add a Time picker in Form using HTML5? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> How to add a Time picker in Form using HTML5? </h2> <form action="#"> <legend> Select Time: <input type="time" name="time"> </legend> <br><br> <input type="submit" value="Submit"> </form></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Questions
HTML-Tags
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24503,
"s": 24475,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 24787,
"s": 24503,
"text": "As we know that a Time picker is used to provide tp select single value from a pre-determined set. Basically, it creates an input field that accepts a time. We can open a time picker by clicking on a clock icon. The UI Design of the Time picker is different from browser to browsers."
},
{
"code": null,
"e": 24835,
"s": 24787,
"text": "Follow the below approach to complete the task:"
},
{
"code": null,
"e": 24901,
"s": 24835,
"text": "Firstly, we create an HTML document that contains a Form element."
},
{
"code": null,
"e": 24936,
"s": 24901,
"text": "Add an <input> tag under the form."
},
{
"code": null,
"e": 24983,
"s": 24936,
"text": "Use the type attribute with the input element."
},
{
"code": null,
"e": 25023,
"s": 24983,
"text": "Set the type attribute to value “time”."
},
{
"code": null,
"e": 25031,
"s": 25023,
"text": "Syntax:"
},
{
"code": null,
"e": 25052,
"s": 25031,
"text": "<input type=\"time\"> "
},
{
"code": null,
"e": 25061,
"s": 25052,
"text": "Example:"
},
{
"code": null,
"e": 25066,
"s": 25061,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to add a Time picker in Form using HTML5? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> How to add a Time picker in Form using HTML5? </h2> <form action=\"#\"> <legend> Select Time: <input type=\"time\" name=\"time\"> </legend> <br><br> <input type=\"submit\" value=\"Submit\"> </form></body> </html>",
"e": 25574,
"s": 25066,
"text": null
},
{
"code": null,
"e": 25582,
"s": 25574,
"text": "Output:"
},
{
"code": null,
"e": 25719,
"s": 25582,
"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": 25734,
"s": 25719,
"text": "HTML-Questions"
},
{
"code": null,
"e": 25744,
"s": 25734,
"text": "HTML-Tags"
},
{
"code": null,
"e": 25750,
"s": 25744,
"text": "HTML5"
},
{
"code": null,
"e": 25755,
"s": 25750,
"text": "HTML"
},
{
"code": null,
"e": 25772,
"s": 25755,
"text": "Web Technologies"
},
{
"code": null,
"e": 25777,
"s": 25772,
"text": "HTML"
},
{
"code": null,
"e": 25875,
"s": 25777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25884,
"s": 25875,
"text": "Comments"
},
{
"code": null,
"e": 25897,
"s": 25884,
"text": "Old Comments"
},
{
"code": null,
"e": 25921,
"s": 25897,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25958,
"s": 25921,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 25987,
"s": 25958,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26034,
"s": 25987,
"text": "How to place text on image using HTML and CSS?"
},
{
"code": null,
"e": 26096,
"s": 26034,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 26152,
"s": 26096,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26185,
"s": 26152,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26228,
"s": 26185,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26289,
"s": 26228,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Can constructors be marked final, abstract or static in Java?
|
Except public, protected and, private constructor does not allow any other modifier.
When you use a final keyword with a method or constructor it cannot be overridden. But, a constructor in Java cannot be overridden therefore, there is no need of using the final keyword with the constructor.
When you use a final keyword with a method or constructor it cannot be overridden. But, a constructor in Java cannot be overridden therefore, there is no need of using the final keyword with the constructor.
Since you cannot override a constructor you cannot provide body to it if it is made abstract. Therefore, you cannot use abstract keyword with the constructor.
Since you cannot override a constructor you cannot provide body to it if it is made abstract. Therefore, you cannot use abstract keyword with the constructor.
If you want to invoke a member of a class before instantiating the class you need to use static before it. But, contractors are called implicitly at the time of instantiation. Therefore, there is no point in using static with constructors.
If you want to invoke a member of a class before instantiating the class you need to use static before it. But, contractors are called implicitly at the time of instantiation. Therefore, there is no point in using static with constructors.
public class Sample {
public final static Sample(){
System.out.println("Hello");
}
public static void main(String args[]) throws Exception{
Sample obj = new Sample();
}
}
C:\Sample>javac Sample.java
Sample.java:2: error: modifier static, final not allowed here
public final static Sample(){
^
1 error
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Except public, protected and, private constructor does not allow any other modifier."
},
{
"code": null,
"e": 1355,
"s": 1147,
"text": "When you use a final keyword with a method or constructor it cannot be overridden. But, a constructor in Java cannot be overridden therefore, there is no need of using the final keyword with the constructor."
},
{
"code": null,
"e": 1563,
"s": 1355,
"text": "When you use a final keyword with a method or constructor it cannot be overridden. But, a constructor in Java cannot be overridden therefore, there is no need of using the final keyword with the constructor."
},
{
"code": null,
"e": 1722,
"s": 1563,
"text": "Since you cannot override a constructor you cannot provide body to it if it is made abstract. Therefore, you cannot use abstract keyword with the constructor."
},
{
"code": null,
"e": 1881,
"s": 1722,
"text": "Since you cannot override a constructor you cannot provide body to it if it is made abstract. Therefore, you cannot use abstract keyword with the constructor."
},
{
"code": null,
"e": 2121,
"s": 1881,
"text": "If you want to invoke a member of a class before instantiating the class you need to use static before it. But, contractors are called implicitly at the time of instantiation. Therefore, there is no point in using static with constructors."
},
{
"code": null,
"e": 2361,
"s": 2121,
"text": "If you want to invoke a member of a class before instantiating the class you need to use static before it. But, contractors are called implicitly at the time of instantiation. Therefore, there is no point in using static with constructors."
},
{
"code": null,
"e": 2556,
"s": 2361,
"text": "public class Sample {\n public final static Sample(){\n System.out.println(\"Hello\");\n }\n public static void main(String args[]) throws Exception{\n Sample obj = new Sample();\n }\n}"
},
{
"code": null,
"e": 2707,
"s": 2556,
"text": "C:\\Sample>javac Sample.java\nSample.java:2: error: modifier static, final not allowed here\npublic final static Sample(){\n ^\n1 error\n"
}
] |
Tryit Editor v3.7
|
RWD Media Queries
Tryit: Using media queries
|
[
{
"code": null,
"e": 27,
"s": 9,
"text": "RWD Media Queries"
}
] |
C# Program to remove whitespaces in a string
|
Let’s say the following is the string −
StringBuilder str = new StringBuilder("Patience is key!");
To remove whitespace, you can use the replace method.
str.Replace(" ", "");
Let us see the complete code.
Live Demo
using System;
using System.Text;
class Demo {
static void Main() {
// Initial String
StringBuilder str = new StringBuilder("Patience is key!");
Console.WriteLine(str.ToString());
// Replace
str.Replace(" ", "");
// New String
Console.WriteLine(str.ToString());
Console.ReadLine();
}
}
Patience is key!
Patienceiskey!
|
[
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Let’s say the following is the string −"
},
{
"code": null,
"e": 1161,
"s": 1102,
"text": "StringBuilder str = new StringBuilder(\"Patience is key!\");"
},
{
"code": null,
"e": 1215,
"s": 1161,
"text": "To remove whitespace, you can use the replace method."
},
{
"code": null,
"e": 1237,
"s": 1215,
"text": "str.Replace(\" \", \"\");"
},
{
"code": null,
"e": 1267,
"s": 1237,
"text": "Let us see the complete code."
},
{
"code": null,
"e": 1278,
"s": 1267,
"text": " Live Demo"
},
{
"code": null,
"e": 1619,
"s": 1278,
"text": "using System;\nusing System.Text;\nclass Demo {\n static void Main() {\n // Initial String\n StringBuilder str = new StringBuilder(\"Patience is key!\");\n Console.WriteLine(str.ToString());\n\n // Replace\n str.Replace(\" \", \"\");\n\n // New String\n Console.WriteLine(str.ToString());\n Console.ReadLine();\n }\n}"
},
{
"code": null,
"e": 1651,
"s": 1619,
"text": "Patience is key!\nPatienceiskey!"
}
] |
How to create a password field using JavaFX?
|
The text field accepts and displays the text. In the latest versions of JavaFX, it accepts only a single line. In JavaFX the javafx.scene.control.TextField class represents the text field, this class inherits the javafx.scene.control.TextInputControl (base class of all the text controls) class. Using this you can accept input from the user and read it to your application.
Similar to text field a password field accepts text but instead of displaying the
given text, it hides the typed characters by displaying an echo string.
In JavaFX the javafx.scene.control.PasswordField represents a password field and it inherits the Text class. To create a password field you need to instantiate this class.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PasswordFieldExample extends Application {
public void start(Stage stage) {
//Creating nodes
TextField textField = new TextField();
PasswordField pwdField = new PasswordField();
//Creating labels
Label label1 = new Label("Name: ");
Label label2 = new Label("Pass word: ");
//Adding labels for nodes
HBox box = new HBox(5);
box.setPadding(new Insets(25, 5 , 5, 50));
box.getChildren().addAll(label1, textField, label2, pwdField);
//Setting the stage
Scene scene = new Scene(box, 595, 150, Color.BEIGE);
stage.setTitle("Password Field Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1437,
"s": 1062,
"text": "The text field accepts and displays the text. In the latest versions of JavaFX, it accepts only a single line. In JavaFX the javafx.scene.control.TextField class represents the text field, this class inherits the javafx.scene.control.TextInputControl (base class of all the text controls) class. Using this you can accept input from the user and read it to your application."
},
{
"code": null,
"e": 1591,
"s": 1437,
"text": "Similar to text field a password field accepts text but instead of displaying the\ngiven text, it hides the typed characters by displaying an echo string."
},
{
"code": null,
"e": 1763,
"s": 1591,
"text": "In JavaFX the javafx.scene.control.PasswordField represents a password field and it inherits the Text class. To create a password field you need to instantiate this class."
},
{
"code": null,
"e": 2832,
"s": 1763,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.PasswordField;\nimport javafx.scene.control.TextField;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class PasswordFieldExample extends Application {\n public void start(Stage stage) {\n //Creating nodes\n TextField textField = new TextField();\n PasswordField pwdField = new PasswordField();\n //Creating labels\n Label label1 = new Label(\"Name: \");\n Label label2 = new Label(\"Pass word: \");\n //Adding labels for nodes\n HBox box = new HBox(5);\n box.setPadding(new Insets(25, 5 , 5, 50));\n box.getChildren().addAll(label1, textField, label2, pwdField);\n //Setting the stage\n Scene scene = new Scene(box, 595, 150, Color.BEIGE);\n stage.setTitle(\"Password Field Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
A Comprehensive Introduction to Bayesian Deep Learning | by Joris Baan | Towards Data Science
|
Table of Contents1. Preamble2. Neural Network Generalization3. Back to Basics: The Bayesian Approach 3.1 Frequentists 3.2 Bayesianists 3.3 Bayesian Inference and Marginalization4. How to Use a Posterior in Practice? 4.1 Maximum A Posteriori Estimation 4.2 Full Predictive Distribution 4.3 Approximate Predictive Distribution5. Bayesian Deep Learning 5.1 Recent Approaches to Bayesian Deep Learning6. Back to the Paper 6.1 Deep Ensembles are BMA 6.2 Combining Deep Ensembles With Bayesian Neural Networks 6.3 Neural Network Priors 6.4 Rethinking Generalization and Double Descent7. Final Words
Bayesian (deep) learning has always intrigued and intimidated me. Perhaps because it leans heavily on probabilistic theory, which can be daunting. I noticed that even though I knew basic probability theory, I had a hard time understanding and connecting that to modern Bayesian deep learning research. The aim of this blogpost is to bridge that gap and provide a comprehensive introduction.
Instead of starting with the basics, I will start with an incredible NeurIPS 2020 paper on Bayesian deep learning and generalization by Andrew Wilson and Pavel Izmailov (NYU) called Bayesian Deep Learning and a Probabilistic Perspective of Generalization. This paper serves as a tangible starting point in which we naturally encounter Bayesian concepts in the wild. I hope this makes the Bayesian perspective more concrete and speaks to its relevance.
I will start with the paper abstract and introduction to set the stage. As we encounter Bayesian concepts, I will zoom out to give a comprehensive overview with plenty of intuition, both from a probabilistic as well as ML/function approximation perspective. Finally, and throughout this entire post, I’ll circle back to and connect with the paper.
I hope you will walk away not only feeling at least slightly Bayesian, but also with an understanding of the paper’s numerous contributions, and generalization in general ;)
If your Bayesian is a bit rusty the abstract might seem rather cryptic. The first two sentences are of particular importance to our general understanding of Bayesian DL. The middle part presents three technical contributions. The last two highlighted sentences provide a primer on new insights into mysterious neural network phenomena. I’ll cover everything, but first things first: the paper’s introduction.
An important question in the introduction is how and why neural networks generalize. The authors argue that
“From a probabilistic perspective, generalization depends largely on two properties, the support and the inductive biases of a model.”
Support is the range of dataset classes that a model can support. In other words; the range of functions a model can represent, where a function is trying to represent the data generative process. The inductive bias defines how good a model class is at fitting a specific dataset class (e.g. images, text, numerical features). The authors call this, quite nicely, the “distribution of support”. In other words, model class performance (~inductive bias) distributed over the range of all possible datasets (support).
Let’s look at the examples the authors provide. A linear function has truncated support as it cannot even represent a quadratic function. An MLP is highly flexible but distributes its support across datasets too evenly to be interesting for many image datasets. A convolutional neural network exhibits a good balance between support and inductive bias for image recognition. Figure 2a illustrates this nicely.
The vertical axis represents what I naively explained as “how good a model is at fitting a specific dataset”. It actually is Bayesian evidence, or marginal likelihood; our first Bayesian concept! We’ll dive into it in the next section. Let’s first finish our line of thought.
A good model not only needs a large support to be able to represent the true solution, but also the right inductive bias to actually arrive at that solution. The Bayesian posterior, think of it as our model for now, should contract to the right solution due to the right inductive bias. However, the prior hypothesis space should be broad enough such that the true model is functionally possible (broad support). The illustrations below demonstrate this for the three example models. From left to right we see a CNN in green, linear function in purple, and MLP in pink.
At this point in the introduction, similar to first sentence of the abstract, the authors stress that
”The key distinguishing property of a Bayesian approach is marginalization instead of optimization, where we represent solutions given by all settings of parameters weighted by their posterior probabilities, rather than bet everything on a single setting of parameters.”
The time is ripe to dig into marginalization vs optimization, and broaden our general understanding of the Bayesian approach. We’ll touch on terms like the posterior, prior and predictive distribution, the marginal likelihood and bayesian evidence, bayesian model averaging, bayesian inference and more.
We can find claims about marginalization being at the core of Bayesian statistics everywhere. Even in Bishop’s ML bible Pattern Recognition and Machine Learning. The opposite to the Bayesian perspective is the frequentist perspective. This is what you encounter in most machine learning literature. It’s also easier to grasp. Let’s start there.
The frequentist approach to machine learning is to optimize a loss function to obtain an optimal setting of the model parameters. An example loss function is cross-entropy, used for classification tasks such as object detection or machine translation. The most commonly used optimization techniques are variations on (stochastic) gradient descent. In SGD the model parameters are iteratively updated in the direction of the steepest descent in loss space. This direction is determined by the gradient of the loss with respect to the parameters. The desired result is that for the same or similar inputs, this new parameter setting causes the output to closer represent the target value. In the case of neural networks, gradients are often computed using a computational trick called backpropagation.
From a probabilistic perspective, frequentists are trying to maximize the likelihood p(D|w, M}). In plain english: to pick our parameters w such that they maximize the probability of the observed dataset D given our choice of model M (Bishop, Chapter 1.2.3). M is often left out for simplicity. From a probabilistic perspective, a (statistical) model is simply a probability distribution over data D (Bishop, Chapter 3.4). For example; a language model outputs a distribution over a vocabulary, indicating how likely each word is to be the next word. It turns out this frequentist way of maximum likelihood estimation (MLE) to obtain, or “train”, predictive models can be viewed from a larger Bayesian context. In fact, MLE can be considered a special case of maximum a posteriori estimation (MAP, which I’ll discuss shortly) using a uniform prior.
A crucial property of the Bayesian approach is to realistically quantify uncertainty. This is vital in real world applications that require us to trust model predictions. So, instead of a parameter point estimate, a Bayesian approach defines a full probability distribution over parameters. We call this the posterior distribution. The posterior represents our belief/hypothesis/uncertainty about the value of each parameter (setting). We use Bayes’ Theorem to compute the posterior. This theorem lies at the heart of Bayesian ML — hence the name — and can be derived using simple rules of probability.
We start with specifying a prior distribution p(w) over the parameters to capture our belief about what our model parameters should look like prior to observing any data.
Then, using our dataset, we can update (multiply) our prior belief with the likelihood p(D|w). This likelihood is the same quantity we saw in the frequentist approach. It tells us how well the observed data is explained by a specific parameter setting w. In other words; how good our model is at fitting or generating that dataset. The likelihood is a function of our parameters w.
To obtain a valid posterior probability distribution, however, the product between the likelihood and the prior must be evaluated for each parameter setting, and normalized. This means marginalizing (summing or integrating) over all parameter settings. The normalizing constant is called the Bayesian (model) evidence or marginal likelihood p(D).
These names are quite intuitive as p(D) provides evidence for how good our model (i.e. how likely the data) is as a whole. With “model as a whole” I mean taking into account all possible parameter settings. In other words: marginalizing over them. We sometimes explicitly include the model choice Min the evidence as p(D|M). This enables us to compare different models with different parameter spaces. In fact, this comparison is exactly what happens in the paper when comparing the support and inductive bias between a CNN, MLP and linear model!
We’ve now arrived at the core of the matter. Bayesian inference is the learning process of finding (inferring) the posterior distribution over w. This contrasts with trying to find the optimal w using optimization through differentiation, the learning process for frequentists.
As we now know, to compute the full posterior we must marginalize over the whole parameter space. In practice this is often impossible (intractable) as we can have infinitely many such settings. This is why a Bayesian approach is fundamentally about marginalization instead of optimization.
The intractable integral in the posterior leads to a different family of methods to learn parameter values with. Instead of gradient descent, Bayesianists often uses sampling methods such as Markov Chain Monte Carlo (MCMC), or variational inference; techniques that try to mimic the posterior using a simpler, tractable family of distributions. Similar techniques are often used for generative models such as VAEs. A relatively new method to approximate a complex distribution is normalizing flows.
Now that we understand the Bayesian posterior distribution, how do we actually use it in practice? What if we want to predict, say, the next word, let’s call y given an unseen sentence x?
Well, we could simply take the posterior distribution over our parameters for our model M and pick the parameter setting w^ that has the highest probability assigned to it (the distribution’s mode). This method is called Maximum A Posteriori or MAP estimation. But... It would be quite a waste to go through all this effort of computing a proper probability distribution over our parameters only to settle for another point estimate, right? (Except when nearly all of the posterior’s mass is centered around one point in parameter space). Because MAP provides a point estimate, it is not considered a full Bayesian treatment.
The full fledged Bayesian approach is to specify a predictive distributionp(y|D,x).
This defines the probability for class label y given new input x and dataset D. To compute the predictive distribution we need to marginalize over our parameter settings again! We multiply the posterior probability of each setting w with the probability of label w given input x using parameter setting w. This is called Bayesian Model Averaging, or BMA, we take a weighted average over all possible models (parameter settings in this case). The predictive distribution is the second important place for marginalization in Bayesian ML, the first being the posterior computation itself. An intuitive way to visualize a predictive distribution is with a simple regression task, like in the Figure below. For a concrete example check out these slides (slide 9–21).
As we know by now, the integral in the predictive distribution is often intractable and at the very least extremely computationally expensive. A third method to using a posterior is by sampling a few parameters settings and combining the resulting models (e.g. approximate BMA). This is actually called a Monte Carlo approximation of the predictive distribution!
This last method is vaguely reminiscent of something perhaps more familiar to a humble frequentist: deep ensembles. Deep ensembles are formed by combining neural networks that are architecturally identical, but trained with different parameter initializations. This beautifully ties in with where we left off in the paper! Remember the abstract?
“We show that deep ensembles provide an effective mechanism for approximate Bayesian marginalization, and propose a related approach that further improves the predictive distribution by marginalizing within basins of attraction”.
Reading the abstract for the second time, the contributions should make a lot more sense. Also, we are now finally steering into Bayesian Deep Learning territory!
A Bayesian Neural Network (BNN) is simply posterior inference applied to a neural network architecture. To be precise, a prior distribution is specified for each weight and bias. Because of their huge parameter space, however, inferring the posterior is even more difficult than usual.
So why do Bayesian DL at all?
The classic answer is to obtain a realistic expression of uncertainty or calibration. A classifier is considered calibrated if the probability (confidence) of a class prediction aligns with its misclassification rate. As said before, this is crucial in real world applications.
”Neural networks are often miscalibrated in the sense that their predictions are typically overconfident.”
However, the authors of our running paper, Wilson and Izmailov, argue that Bayesian model averaging increases accuracy as well. According to Section 3.1, the Bayesian perspective is in fact especially compelling for neural networks! Because of their large parameter space, neural networks can represent many different solutions, e.g. they are underspecified by the data. This means a Bayesian model average is extremely useful because it combines a diverse range of functional forms, or “perspectives”, into one.
”A neural network can represent many models that are consistent with our observations. By selecting only one, in a classical procedure, we lose uncertainty when the models disagree for a test point.”
A number of people have recently been trying to combine the advantages of a traditional neural network (e.g. computationally efficient training using SGD & back propagation) with the advantages of a Bayesian approach (e.g. calibration).
One popular and conceptually easy approach is Monte Carlo dropout. Recall that dropout is traditionally used as regularization; it provides stochasticity or variation in a neural network by randomly shutting down weights during training It turns out dropout can be reinterpreted as approximate Bayesian inference and applied during testing, which leads to multiple different parameter settings. Sounds a little similar to sampling parameters from a posterior to approximate the predictive distribution, mh?
Another line of work follows from Stochastic Weight Averaging (SWA), an elegant approximation to ensembling that intelligently combines weights of the same network at different stages of training (check out this or this blogpost if you want to know more. SWA-Gaussian (SWAG) builds on it by approximating the shape (local geometry) of the posterior distribution using simple information provided by SGD. Recall that SGD “moves” through the parameter space looking for a (local) optimum in loss space. To approximate the local geometry of the posterior, they fit a Gaussian distribution to the first and second moment of the SGD iterate. Moments describe the shape of a function or distribution, where the zero moment is the the sum, the first moment is the mean, and the second moment is the variance. These fitted Gaussian distributions can then be used for BMA.
I have obviously failed to mention at least 99% of the field here (e.g. KFAC Laplace and temperature scaling for improved calibration), and picked the examples above in part because they are related to our running paper. I’ll finish with one last example of a recent frequentist (or is it...) alternative to uncertainty approximation. This is a popular method showing that one can train a deep ensemble and use it to form a predictive distribution, resulting in a well calibrated model. They use a few bells and whistles that I won’t go into, such as adversarial training to smoothen the predictive distribution. Check out the paper here.
By now we are more than ready to circle back to the paper and go over its contributions! They should be easier to grasp :)
Contrary to how recent literature (myself included) has framed it, Wilson and Izmailov argue that deep ensembles are not a frequentist alternative to obtain Bayesian advantages. In fact, they are a very good approximation of the posterior distribution. Because deep ensembles are formed by MAP or MLE retraining, they can form different basins of attraction. A basin of attraction is a “basin” or valley in the loss landscape that leads to some (locally) optimal solution. But there might be, and usually are, multiple optimal solutions, or valleys in the loss landscape. The use of multiple basins of attraction, found by different parts of an ensemble, results in more functional diversity than Bayesian approaches that focus on approximating posterior within single basin of attraction.
This idea of using multiple basins of attraction is important for the next contribution as well: an improved method for approximating predictive distributions. By combining the multiple basins of attraction property that deep ensembles have with the Bayesian treatment in SWAG, the authors propose a best-of-both-worlds solution: Multiple basins of attraction Stochastic Weight Averaging Gaussian or MultiSWAG:
”MultiSWAG combines multiple independently trained SWAG approximations, to create a mixture of Gaussians approximation to the posterior, with each Gaussian centred on a different basin. We note that MultiSWAG does not require any additional training time over standard deep ensembles.”
Have a look at the paper if you’re interested in the nitty gritty details ;)
How can we ever specify a meaningful prior over millions of parameters, I hear you ask? It turns out this is a pretty valid question. In fact, the Bayesian approach is sometimes criticised because of it.
However, in Section 5 of the paper Wilson and Izmailov provide evidence that specifying a vague prior, such as a simple Gaussian might actually not be such a bad idea.
”Vague Gaussian priors over parameters, when combined with a neural network architecture, induce a distribution over functions with useful inductive biases.” ...
... ”The distribution over functions controls the generalization properties of the model; the prior over parameters, in isolation, has no meaning.”
A vague prior combined with the functional form of a neural network results in a meaningful distribution in function space. The prior itself doesn’t matter, but its effect on the resulting predictive distribution does.
We have now arrived at the strange neural network phenomena I highlighted in the abstract. According to Section 6, the surprising fact that neural networks can fit random labels is actually not surprising at all. Not if you look at it from perspective of support and inductive bias. Broad support, the range of datasets for which p(D|M) > 0, is important for generalization. In fact, the ability to fit random labels is perfectly fine as long as we have the right inductive bias to steer the model towards a good solution. Wilson and Izmailov also show that this phenomena is not mysteriously specific to neural networks either, and that Gaussian Processes exhibit the same ability.
The second phenomena is double descent. Double descent is a recently discovered phenomena where bigger models and more data unexpectedly decreases performance.
Wilson and Izmailov find that models trained with SGD suffer from double descent, but that SWAG reduces it. More importantly, both MultiSWAG as well as deep ensembles completely mitigate the double descent phenomena! This is in line with their previously discussed claim that
”Deep ensembles provide a better approximation to the Bayesian predictive distribution than conventional single-basin Bayesian marginalization procedures.”
and highlights the importance of marginalization over multiple modes of the posterior.
You made it! Thank you for reading all the way through. This post became quite lengthy but I hope you learned a lot about Bayesian DL. I sure did.
Note that I am not affiliated to Wilson, Izmailov or their group at NYU. This post reflects my own interpretation of their work, except for the quote blocks taken directly from the paper.
Please feel free to ask any question or point out mistakes that I’ve undoubtedly made. I would also love to know whether you liked this post. You can find my contact details on my website, message me on Twitter or connect on LinkedIn. Check out my personal blog at jorisbaan.nl/posts for proper math rendering!
|
[
{
"code": null,
"e": 797,
"s": 171,
"text": "Table of Contents1. Preamble2. Neural Network Generalization3. Back to Basics: The Bayesian Approach 3.1 Frequentists 3.2 Bayesianists 3.3 Bayesian Inference and Marginalization4. How to Use a Posterior in Practice? 4.1 Maximum A Posteriori Estimation 4.2 Full Predictive Distribution 4.3 Approximate Predictive Distribution5. Bayesian Deep Learning 5.1 Recent Approaches to Bayesian Deep Learning6. Back to the Paper 6.1 Deep Ensembles are BMA 6.2 Combining Deep Ensembles With Bayesian Neural Networks 6.3 Neural Network Priors 6.4 Rethinking Generalization and Double Descent7. Final Words"
},
{
"code": null,
"e": 1188,
"s": 797,
"text": "Bayesian (deep) learning has always intrigued and intimidated me. Perhaps because it leans heavily on probabilistic theory, which can be daunting. I noticed that even though I knew basic probability theory, I had a hard time understanding and connecting that to modern Bayesian deep learning research. The aim of this blogpost is to bridge that gap and provide a comprehensive introduction."
},
{
"code": null,
"e": 1640,
"s": 1188,
"text": "Instead of starting with the basics, I will start with an incredible NeurIPS 2020 paper on Bayesian deep learning and generalization by Andrew Wilson and Pavel Izmailov (NYU) called Bayesian Deep Learning and a Probabilistic Perspective of Generalization. This paper serves as a tangible starting point in which we naturally encounter Bayesian concepts in the wild. I hope this makes the Bayesian perspective more concrete and speaks to its relevance."
},
{
"code": null,
"e": 1988,
"s": 1640,
"text": "I will start with the paper abstract and introduction to set the stage. As we encounter Bayesian concepts, I will zoom out to give a comprehensive overview with plenty of intuition, both from a probabilistic as well as ML/function approximation perspective. Finally, and throughout this entire post, I’ll circle back to and connect with the paper."
},
{
"code": null,
"e": 2162,
"s": 1988,
"text": "I hope you will walk away not only feeling at least slightly Bayesian, but also with an understanding of the paper’s numerous contributions, and generalization in general ;)"
},
{
"code": null,
"e": 2571,
"s": 2162,
"text": "If your Bayesian is a bit rusty the abstract might seem rather cryptic. The first two sentences are of particular importance to our general understanding of Bayesian DL. The middle part presents three technical contributions. The last two highlighted sentences provide a primer on new insights into mysterious neural network phenomena. I’ll cover everything, but first things first: the paper’s introduction."
},
{
"code": null,
"e": 2679,
"s": 2571,
"text": "An important question in the introduction is how and why neural networks generalize. The authors argue that"
},
{
"code": null,
"e": 2814,
"s": 2679,
"text": "“From a probabilistic perspective, generalization depends largely on two properties, the support and the inductive biases of a model.”"
},
{
"code": null,
"e": 3330,
"s": 2814,
"text": "Support is the range of dataset classes that a model can support. In other words; the range of functions a model can represent, where a function is trying to represent the data generative process. The inductive bias defines how good a model class is at fitting a specific dataset class (e.g. images, text, numerical features). The authors call this, quite nicely, the “distribution of support”. In other words, model class performance (~inductive bias) distributed over the range of all possible datasets (support)."
},
{
"code": null,
"e": 3740,
"s": 3330,
"text": "Let’s look at the examples the authors provide. A linear function has truncated support as it cannot even represent a quadratic function. An MLP is highly flexible but distributes its support across datasets too evenly to be interesting for many image datasets. A convolutional neural network exhibits a good balance between support and inductive bias for image recognition. Figure 2a illustrates this nicely."
},
{
"code": null,
"e": 4016,
"s": 3740,
"text": "The vertical axis represents what I naively explained as “how good a model is at fitting a specific dataset”. It actually is Bayesian evidence, or marginal likelihood; our first Bayesian concept! We’ll dive into it in the next section. Let’s first finish our line of thought."
},
{
"code": null,
"e": 4586,
"s": 4016,
"text": "A good model not only needs a large support to be able to represent the true solution, but also the right inductive bias to actually arrive at that solution. The Bayesian posterior, think of it as our model for now, should contract to the right solution due to the right inductive bias. However, the prior hypothesis space should be broad enough such that the true model is functionally possible (broad support). The illustrations below demonstrate this for the three example models. From left to right we see a CNN in green, linear function in purple, and MLP in pink."
},
{
"code": null,
"e": 4688,
"s": 4586,
"text": "At this point in the introduction, similar to first sentence of the abstract, the authors stress that"
},
{
"code": null,
"e": 4959,
"s": 4688,
"text": "”The key distinguishing property of a Bayesian approach is marginalization instead of optimization, where we represent solutions given by all settings of parameters weighted by their posterior probabilities, rather than bet everything on a single setting of parameters.”"
},
{
"code": null,
"e": 5263,
"s": 4959,
"text": "The time is ripe to dig into marginalization vs optimization, and broaden our general understanding of the Bayesian approach. We’ll touch on terms like the posterior, prior and predictive distribution, the marginal likelihood and bayesian evidence, bayesian model averaging, bayesian inference and more."
},
{
"code": null,
"e": 5608,
"s": 5263,
"text": "We can find claims about marginalization being at the core of Bayesian statistics everywhere. Even in Bishop’s ML bible Pattern Recognition and Machine Learning. The opposite to the Bayesian perspective is the frequentist perspective. This is what you encounter in most machine learning literature. It’s also easier to grasp. Let’s start there."
},
{
"code": null,
"e": 6408,
"s": 5608,
"text": "The frequentist approach to machine learning is to optimize a loss function to obtain an optimal setting of the model parameters. An example loss function is cross-entropy, used for classification tasks such as object detection or machine translation. The most commonly used optimization techniques are variations on (stochastic) gradient descent. In SGD the model parameters are iteratively updated in the direction of the steepest descent in loss space. This direction is determined by the gradient of the loss with respect to the parameters. The desired result is that for the same or similar inputs, this new parameter setting causes the output to closer represent the target value. In the case of neural networks, gradients are often computed using a computational trick called backpropagation."
},
{
"code": null,
"e": 7257,
"s": 6408,
"text": "From a probabilistic perspective, frequentists are trying to maximize the likelihood p(D|w, M}). In plain english: to pick our parameters w such that they maximize the probability of the observed dataset D given our choice of model M (Bishop, Chapter 1.2.3). M is often left out for simplicity. From a probabilistic perspective, a (statistical) model is simply a probability distribution over data D (Bishop, Chapter 3.4). For example; a language model outputs a distribution over a vocabulary, indicating how likely each word is to be the next word. It turns out this frequentist way of maximum likelihood estimation (MLE) to obtain, or “train”, predictive models can be viewed from a larger Bayesian context. In fact, MLE can be considered a special case of maximum a posteriori estimation (MAP, which I’ll discuss shortly) using a uniform prior."
},
{
"code": null,
"e": 7860,
"s": 7257,
"text": "A crucial property of the Bayesian approach is to realistically quantify uncertainty. This is vital in real world applications that require us to trust model predictions. So, instead of a parameter point estimate, a Bayesian approach defines a full probability distribution over parameters. We call this the posterior distribution. The posterior represents our belief/hypothesis/uncertainty about the value of each parameter (setting). We use Bayes’ Theorem to compute the posterior. This theorem lies at the heart of Bayesian ML — hence the name — and can be derived using simple rules of probability."
},
{
"code": null,
"e": 8031,
"s": 7860,
"text": "We start with specifying a prior distribution p(w) over the parameters to capture our belief about what our model parameters should look like prior to observing any data."
},
{
"code": null,
"e": 8413,
"s": 8031,
"text": "Then, using our dataset, we can update (multiply) our prior belief with the likelihood p(D|w). This likelihood is the same quantity we saw in the frequentist approach. It tells us how well the observed data is explained by a specific parameter setting w. In other words; how good our model is at fitting or generating that dataset. The likelihood is a function of our parameters w."
},
{
"code": null,
"e": 8760,
"s": 8413,
"text": "To obtain a valid posterior probability distribution, however, the product between the likelihood and the prior must be evaluated for each parameter setting, and normalized. This means marginalizing (summing or integrating) over all parameter settings. The normalizing constant is called the Bayesian (model) evidence or marginal likelihood p(D)."
},
{
"code": null,
"e": 9307,
"s": 8760,
"text": "These names are quite intuitive as p(D) provides evidence for how good our model (i.e. how likely the data) is as a whole. With “model as a whole” I mean taking into account all possible parameter settings. In other words: marginalizing over them. We sometimes explicitly include the model choice Min the evidence as p(D|M). This enables us to compare different models with different parameter spaces. In fact, this comparison is exactly what happens in the paper when comparing the support and inductive bias between a CNN, MLP and linear model!"
},
{
"code": null,
"e": 9585,
"s": 9307,
"text": "We’ve now arrived at the core of the matter. Bayesian inference is the learning process of finding (inferring) the posterior distribution over w. This contrasts with trying to find the optimal w using optimization through differentiation, the learning process for frequentists."
},
{
"code": null,
"e": 9876,
"s": 9585,
"text": "As we now know, to compute the full posterior we must marginalize over the whole parameter space. In practice this is often impossible (intractable) as we can have infinitely many such settings. This is why a Bayesian approach is fundamentally about marginalization instead of optimization."
},
{
"code": null,
"e": 10375,
"s": 9876,
"text": "The intractable integral in the posterior leads to a different family of methods to learn parameter values with. Instead of gradient descent, Bayesianists often uses sampling methods such as Markov Chain Monte Carlo (MCMC), or variational inference; techniques that try to mimic the posterior using a simpler, tractable family of distributions. Similar techniques are often used for generative models such as VAEs. A relatively new method to approximate a complex distribution is normalizing flows."
},
{
"code": null,
"e": 10563,
"s": 10375,
"text": "Now that we understand the Bayesian posterior distribution, how do we actually use it in practice? What if we want to predict, say, the next word, let’s call y given an unseen sentence x?"
},
{
"code": null,
"e": 11189,
"s": 10563,
"text": "Well, we could simply take the posterior distribution over our parameters for our model M and pick the parameter setting w^ that has the highest probability assigned to it (the distribution’s mode). This method is called Maximum A Posteriori or MAP estimation. But... It would be quite a waste to go through all this effort of computing a proper probability distribution over our parameters only to settle for another point estimate, right? (Except when nearly all of the posterior’s mass is centered around one point in parameter space). Because MAP provides a point estimate, it is not considered a full Bayesian treatment."
},
{
"code": null,
"e": 11273,
"s": 11189,
"text": "The full fledged Bayesian approach is to specify a predictive distributionp(y|D,x)."
},
{
"code": null,
"e": 12035,
"s": 11273,
"text": "This defines the probability for class label y given new input x and dataset D. To compute the predictive distribution we need to marginalize over our parameter settings again! We multiply the posterior probability of each setting w with the probability of label w given input x using parameter setting w. This is called Bayesian Model Averaging, or BMA, we take a weighted average over all possible models (parameter settings in this case). The predictive distribution is the second important place for marginalization in Bayesian ML, the first being the posterior computation itself. An intuitive way to visualize a predictive distribution is with a simple regression task, like in the Figure below. For a concrete example check out these slides (slide 9–21)."
},
{
"code": null,
"e": 12398,
"s": 12035,
"text": "As we know by now, the integral in the predictive distribution is often intractable and at the very least extremely computationally expensive. A third method to using a posterior is by sampling a few parameters settings and combining the resulting models (e.g. approximate BMA). This is actually called a Monte Carlo approximation of the predictive distribution!"
},
{
"code": null,
"e": 12744,
"s": 12398,
"text": "This last method is vaguely reminiscent of something perhaps more familiar to a humble frequentist: deep ensembles. Deep ensembles are formed by combining neural networks that are architecturally identical, but trained with different parameter initializations. This beautifully ties in with where we left off in the paper! Remember the abstract?"
},
{
"code": null,
"e": 12974,
"s": 12744,
"text": "“We show that deep ensembles provide an effective mechanism for approximate Bayesian marginalization, and propose a related approach that further improves the predictive distribution by marginalizing within basins of attraction”."
},
{
"code": null,
"e": 13137,
"s": 12974,
"text": "Reading the abstract for the second time, the contributions should make a lot more sense. Also, we are now finally steering into Bayesian Deep Learning territory!"
},
{
"code": null,
"e": 13423,
"s": 13137,
"text": "A Bayesian Neural Network (BNN) is simply posterior inference applied to a neural network architecture. To be precise, a prior distribution is specified for each weight and bias. Because of their huge parameter space, however, inferring the posterior is even more difficult than usual."
},
{
"code": null,
"e": 13453,
"s": 13423,
"text": "So why do Bayesian DL at all?"
},
{
"code": null,
"e": 13731,
"s": 13453,
"text": "The classic answer is to obtain a realistic expression of uncertainty or calibration. A classifier is considered calibrated if the probability (confidence) of a class prediction aligns with its misclassification rate. As said before, this is crucial in real world applications."
},
{
"code": null,
"e": 13838,
"s": 13731,
"text": "”Neural networks are often miscalibrated in the sense that their predictions are typically overconfident.”"
},
{
"code": null,
"e": 14351,
"s": 13838,
"text": "However, the authors of our running paper, Wilson and Izmailov, argue that Bayesian model averaging increases accuracy as well. According to Section 3.1, the Bayesian perspective is in fact especially compelling for neural networks! Because of their large parameter space, neural networks can represent many different solutions, e.g. they are underspecified by the data. This means a Bayesian model average is extremely useful because it combines a diverse range of functional forms, or “perspectives”, into one."
},
{
"code": null,
"e": 14551,
"s": 14351,
"text": "”A neural network can represent many models that are consistent with our observations. By selecting only one, in a classical procedure, we lose uncertainty when the models disagree for a test point.”"
},
{
"code": null,
"e": 14788,
"s": 14551,
"text": "A number of people have recently been trying to combine the advantages of a traditional neural network (e.g. computationally efficient training using SGD & back propagation) with the advantages of a Bayesian approach (e.g. calibration)."
},
{
"code": null,
"e": 15295,
"s": 14788,
"text": "One popular and conceptually easy approach is Monte Carlo dropout. Recall that dropout is traditionally used as regularization; it provides stochasticity or variation in a neural network by randomly shutting down weights during training It turns out dropout can be reinterpreted as approximate Bayesian inference and applied during testing, which leads to multiple different parameter settings. Sounds a little similar to sampling parameters from a posterior to approximate the predictive distribution, mh?"
},
{
"code": null,
"e": 16159,
"s": 15295,
"text": "Another line of work follows from Stochastic Weight Averaging (SWA), an elegant approximation to ensembling that intelligently combines weights of the same network at different stages of training (check out this or this blogpost if you want to know more. SWA-Gaussian (SWAG) builds on it by approximating the shape (local geometry) of the posterior distribution using simple information provided by SGD. Recall that SGD “moves” through the parameter space looking for a (local) optimum in loss space. To approximate the local geometry of the posterior, they fit a Gaussian distribution to the first and second moment of the SGD iterate. Moments describe the shape of a function or distribution, where the zero moment is the the sum, the first moment is the mean, and the second moment is the variance. These fitted Gaussian distributions can then be used for BMA."
},
{
"code": null,
"e": 16798,
"s": 16159,
"text": "I have obviously failed to mention at least 99% of the field here (e.g. KFAC Laplace and temperature scaling for improved calibration), and picked the examples above in part because they are related to our running paper. I’ll finish with one last example of a recent frequentist (or is it...) alternative to uncertainty approximation. This is a popular method showing that one can train a deep ensemble and use it to form a predictive distribution, resulting in a well calibrated model. They use a few bells and whistles that I won’t go into, such as adversarial training to smoothen the predictive distribution. Check out the paper here."
},
{
"code": null,
"e": 16921,
"s": 16798,
"text": "By now we are more than ready to circle back to the paper and go over its contributions! They should be easier to grasp :)"
},
{
"code": null,
"e": 17711,
"s": 16921,
"text": "Contrary to how recent literature (myself included) has framed it, Wilson and Izmailov argue that deep ensembles are not a frequentist alternative to obtain Bayesian advantages. In fact, they are a very good approximation of the posterior distribution. Because deep ensembles are formed by MAP or MLE retraining, they can form different basins of attraction. A basin of attraction is a “basin” or valley in the loss landscape that leads to some (locally) optimal solution. But there might be, and usually are, multiple optimal solutions, or valleys in the loss landscape. The use of multiple basins of attraction, found by different parts of an ensemble, results in more functional diversity than Bayesian approaches that focus on approximating posterior within single basin of attraction."
},
{
"code": null,
"e": 18122,
"s": 17711,
"text": "This idea of using multiple basins of attraction is important for the next contribution as well: an improved method for approximating predictive distributions. By combining the multiple basins of attraction property that deep ensembles have with the Bayesian treatment in SWAG, the authors propose a best-of-both-worlds solution: Multiple basins of attraction Stochastic Weight Averaging Gaussian or MultiSWAG:"
},
{
"code": null,
"e": 18408,
"s": 18122,
"text": "”MultiSWAG combines multiple independently trained SWAG approximations, to create a mixture of Gaussians approximation to the posterior, with each Gaussian centred on a different basin. We note that MultiSWAG does not require any additional training time over standard deep ensembles.”"
},
{
"code": null,
"e": 18485,
"s": 18408,
"text": "Have a look at the paper if you’re interested in the nitty gritty details ;)"
},
{
"code": null,
"e": 18689,
"s": 18485,
"text": "How can we ever specify a meaningful prior over millions of parameters, I hear you ask? It turns out this is a pretty valid question. In fact, the Bayesian approach is sometimes criticised because of it."
},
{
"code": null,
"e": 18857,
"s": 18689,
"text": "However, in Section 5 of the paper Wilson and Izmailov provide evidence that specifying a vague prior, such as a simple Gaussian might actually not be such a bad idea."
},
{
"code": null,
"e": 19019,
"s": 18857,
"text": "”Vague Gaussian priors over parameters, when combined with a neural network architecture, induce a distribution over functions with useful inductive biases.” ..."
},
{
"code": null,
"e": 19167,
"s": 19019,
"text": "... ”The distribution over functions controls the generalization properties of the model; the prior over parameters, in isolation, has no meaning.”"
},
{
"code": null,
"e": 19386,
"s": 19167,
"text": "A vague prior combined with the functional form of a neural network results in a meaningful distribution in function space. The prior itself doesn’t matter, but its effect on the resulting predictive distribution does."
},
{
"code": null,
"e": 20069,
"s": 19386,
"text": "We have now arrived at the strange neural network phenomena I highlighted in the abstract. According to Section 6, the surprising fact that neural networks can fit random labels is actually not surprising at all. Not if you look at it from perspective of support and inductive bias. Broad support, the range of datasets for which p(D|M) > 0, is important for generalization. In fact, the ability to fit random labels is perfectly fine as long as we have the right inductive bias to steer the model towards a good solution. Wilson and Izmailov also show that this phenomena is not mysteriously specific to neural networks either, and that Gaussian Processes exhibit the same ability."
},
{
"code": null,
"e": 20229,
"s": 20069,
"text": "The second phenomena is double descent. Double descent is a recently discovered phenomena where bigger models and more data unexpectedly decreases performance."
},
{
"code": null,
"e": 20505,
"s": 20229,
"text": "Wilson and Izmailov find that models trained with SGD suffer from double descent, but that SWAG reduces it. More importantly, both MultiSWAG as well as deep ensembles completely mitigate the double descent phenomena! This is in line with their previously discussed claim that"
},
{
"code": null,
"e": 20661,
"s": 20505,
"text": "”Deep ensembles provide a better approximation to the Bayesian predictive distribution than conventional single-basin Bayesian marginalization procedures.”"
},
{
"code": null,
"e": 20748,
"s": 20661,
"text": "and highlights the importance of marginalization over multiple modes of the posterior."
},
{
"code": null,
"e": 20895,
"s": 20748,
"text": "You made it! Thank you for reading all the way through. This post became quite lengthy but I hope you learned a lot about Bayesian DL. I sure did."
},
{
"code": null,
"e": 21083,
"s": 20895,
"text": "Note that I am not affiliated to Wilson, Izmailov or their group at NYU. This post reflects my own interpretation of their work, except for the quote blocks taken directly from the paper."
}
] |
Most Common Loss Functions in Machine Learning | by Sparsh Gupta | Towards Data Science
|
In mathematical optimization and decision theory, a loss function or cost function is a function that maps an event or values of one or more variables onto a real number intuitively representing some “cost” associated with the event. — Wikipedia
As a core element, the Loss function is a method of evaluating your Machine Learning algorithm that how well it models your featured dataset. It is defined as a measurement of how good your model is in terms of predicting the expected outcome.
The Cost function and Loss function refer to the same context. The cost function is a function that is calculated as the average of all loss function values. Whereas, the loss function is calculated for each sample output compared to its actual value.
The Loss function is directly related to the predictions of your model that you have built. So if your loss function value is less, your model will be providing good results. Loss function or I should rather say, the Cost function that is used to evaluate the model performance, needs to be minimized in order to improve its performance.
Lets now dive into the Loss functions.
Widely speaking, the Loss functions can be grouped into two major categories concerning the types of problems that we come across in the real world — Classification and Regression. In Classification, the task is to predict the respective probabilities of all classes that the problem is dealing with. In Regression, oppositely, the task is to predict the continuous value concerning a given set of independent features to the learning algorithm.
Assumptions: n/m — Number of training samples. i — ith training sample in a dataset. y(i) — Actual value for the ith training sample. y_hat(i) — Predicted value for the ith training sample.
This is the most common Loss function used in Classification problems. The cross-entropy loss decreases as the predicted probability converges to the actual label. It measures the performance of a classification model whose predicted output is a probability value between 0 and 1.
When the number of classes is 2, Binary Classification
When the number of classes is more than 2, Multi-class Classification
The Cross-Entropy Loss formula is derived from the regular likelihood function, but with logarithms added in.
The second most common loss function used for Classification problems and an alternative to Cross-Entropy loss function is Hinge Loss, primarily developed for Support Vector Machine (SVM) model evaluation.
Hinge Loss not only penalizes the wrong predictions but also the right predictions that are not confident. It is primarily used with SVM Classifiers with class labels as -1 and 1. Make sure you change your malignant class labels from 0 to -1.
MSE loss function is defined as the average of squared differences between the actual and the predicted value. It is the most commonly used Regression loss function.
The corresponding cost function is the Mean of these Squared Errors (MSE). The MSE Loss function penalizes the model for making large errors by squaring them and this property makes the MSE cost function less robust to outliers. Therefore, it should not be used if the data is prone to many outliers.
MSE loss function is defined as the average of absolute differences between the actual and the predicted value. It is the second most commonly used Regression loss function. It measures the average magnitude of errors in a set of predictions, without considering their directions.
The corresponding cost function is the Mean of these Absolute Errors (MAE). The MAE Loss function is more robust to outliers compared to MSE Loss function. Therefore, it should be used if the data is prone to many outliers.
Huber loss function is defined as the combination of MSE and MAE Loss function as it approaches MSE when δ ~ 0 and MAE when δ ~ ∞ (large numbers). It’s Mean Absolute Error, that becomes quadratic when the error is small. And to make the error quadratic depends on how small that error could be which is controlled by a hyperparameter, δ (delta), which can be tuned.
The choice of the delta value is critical because it determines what you’re willing to consider as an outlier. Hence, the Huber Loss function could be less sensitive to outliers compared to MSE Loss function depending upon the hyperparameter value. Therefore, it can be used if the data is prone to outliers and we might need to train hyperparameter delta which is an iterative process.
The Log-Cosh loss function is defined as the logarithm of the hyperbolic cosine of the prediction error. It is another function used in regression tasks which is much smoother than MSE Loss. It has all the advantages of Huber loss, and it’s twice differentiable everywhere, unlike Huber loss as some Learning algorithms like XGBoost use Newton’s method to find the optimum, and hence the second derivative (Hessian) is needed.
log(cosh(x)) is approximately equal to (x ** 2) / 2 for small x and to abs(x) - log(2) for large x. This means that ‘logcosh’ works mostly like the mean squared error, but will not be so strongly affected by the occasional wildly incorrect prediction. — Tensorflow Docs
A quantile is a value below which a fraction of samples in a group falls. Machine learning models work by minimizing (or maximizing) an objective function. As the name suggests, the quantile regression loss function is applied to predict quantiles. For a set of predictions, the loss will be its average.
Quantile loss function turns out to be useful when we are interested in predicting an interval instead of only point predictions.
Thank you for reading! I hope this post has been useful. I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can drop me a text here or on my LinkedIn account.
|
[
{
"code": null,
"e": 418,
"s": 172,
"text": "In mathematical optimization and decision theory, a loss function or cost function is a function that maps an event or values of one or more variables onto a real number intuitively representing some “cost” associated with the event. — Wikipedia"
},
{
"code": null,
"e": 662,
"s": 418,
"text": "As a core element, the Loss function is a method of evaluating your Machine Learning algorithm that how well it models your featured dataset. It is defined as a measurement of how good your model is in terms of predicting the expected outcome."
},
{
"code": null,
"e": 914,
"s": 662,
"text": "The Cost function and Loss function refer to the same context. The cost function is a function that is calculated as the average of all loss function values. Whereas, the loss function is calculated for each sample output compared to its actual value."
},
{
"code": null,
"e": 1252,
"s": 914,
"text": "The Loss function is directly related to the predictions of your model that you have built. So if your loss function value is less, your model will be providing good results. Loss function or I should rather say, the Cost function that is used to evaluate the model performance, needs to be minimized in order to improve its performance."
},
{
"code": null,
"e": 1291,
"s": 1252,
"text": "Lets now dive into the Loss functions."
},
{
"code": null,
"e": 1737,
"s": 1291,
"text": "Widely speaking, the Loss functions can be grouped into two major categories concerning the types of problems that we come across in the real world — Classification and Regression. In Classification, the task is to predict the respective probabilities of all classes that the problem is dealing with. In Regression, oppositely, the task is to predict the continuous value concerning a given set of independent features to the learning algorithm."
},
{
"code": null,
"e": 1939,
"s": 1737,
"text": "Assumptions: n/m — Number of training samples. i — ith training sample in a dataset. y(i) — Actual value for the ith training sample. y_hat(i) — Predicted value for the ith training sample."
},
{
"code": null,
"e": 2220,
"s": 1939,
"text": "This is the most common Loss function used in Classification problems. The cross-entropy loss decreases as the predicted probability converges to the actual label. It measures the performance of a classification model whose predicted output is a probability value between 0 and 1."
},
{
"code": null,
"e": 2275,
"s": 2220,
"text": "When the number of classes is 2, Binary Classification"
},
{
"code": null,
"e": 2345,
"s": 2275,
"text": "When the number of classes is more than 2, Multi-class Classification"
},
{
"code": null,
"e": 2455,
"s": 2345,
"text": "The Cross-Entropy Loss formula is derived from the regular likelihood function, but with logarithms added in."
},
{
"code": null,
"e": 2661,
"s": 2455,
"text": "The second most common loss function used for Classification problems and an alternative to Cross-Entropy loss function is Hinge Loss, primarily developed for Support Vector Machine (SVM) model evaluation."
},
{
"code": null,
"e": 2904,
"s": 2661,
"text": "Hinge Loss not only penalizes the wrong predictions but also the right predictions that are not confident. It is primarily used with SVM Classifiers with class labels as -1 and 1. Make sure you change your malignant class labels from 0 to -1."
},
{
"code": null,
"e": 3070,
"s": 2904,
"text": "MSE loss function is defined as the average of squared differences between the actual and the predicted value. It is the most commonly used Regression loss function."
},
{
"code": null,
"e": 3371,
"s": 3070,
"text": "The corresponding cost function is the Mean of these Squared Errors (MSE). The MSE Loss function penalizes the model for making large errors by squaring them and this property makes the MSE cost function less robust to outliers. Therefore, it should not be used if the data is prone to many outliers."
},
{
"code": null,
"e": 3652,
"s": 3371,
"text": "MSE loss function is defined as the average of absolute differences between the actual and the predicted value. It is the second most commonly used Regression loss function. It measures the average magnitude of errors in a set of predictions, without considering their directions."
},
{
"code": null,
"e": 3876,
"s": 3652,
"text": "The corresponding cost function is the Mean of these Absolute Errors (MAE). The MAE Loss function is more robust to outliers compared to MSE Loss function. Therefore, it should be used if the data is prone to many outliers."
},
{
"code": null,
"e": 4242,
"s": 3876,
"text": "Huber loss function is defined as the combination of MSE and MAE Loss function as it approaches MSE when δ ~ 0 and MAE when δ ~ ∞ (large numbers). It’s Mean Absolute Error, that becomes quadratic when the error is small. And to make the error quadratic depends on how small that error could be which is controlled by a hyperparameter, δ (delta), which can be tuned."
},
{
"code": null,
"e": 4629,
"s": 4242,
"text": "The choice of the delta value is critical because it determines what you’re willing to consider as an outlier. Hence, the Huber Loss function could be less sensitive to outliers compared to MSE Loss function depending upon the hyperparameter value. Therefore, it can be used if the data is prone to outliers and we might need to train hyperparameter delta which is an iterative process."
},
{
"code": null,
"e": 5056,
"s": 4629,
"text": "The Log-Cosh loss function is defined as the logarithm of the hyperbolic cosine of the prediction error. It is another function used in regression tasks which is much smoother than MSE Loss. It has all the advantages of Huber loss, and it’s twice differentiable everywhere, unlike Huber loss as some Learning algorithms like XGBoost use Newton’s method to find the optimum, and hence the second derivative (Hessian) is needed."
},
{
"code": null,
"e": 5326,
"s": 5056,
"text": "log(cosh(x)) is approximately equal to (x ** 2) / 2 for small x and to abs(x) - log(2) for large x. This means that ‘logcosh’ works mostly like the mean squared error, but will not be so strongly affected by the occasional wildly incorrect prediction. — Tensorflow Docs"
},
{
"code": null,
"e": 5631,
"s": 5326,
"text": "A quantile is a value below which a fraction of samples in a group falls. Machine learning models work by minimizing (or maximizing) an objective function. As the name suggests, the quantile regression loss function is applied to predict quantiles. For a set of predictions, the loss will be its average."
},
{
"code": null,
"e": 5761,
"s": 5631,
"text": "Quantile loss function turns out to be useful when we are interested in predicting an interval instead of only point predictions."
}
] |
How to calculate natural log of a number in Python?
|
In the math module, two functions for calculation of logarithmic value are defined. The log() function returns natural logarithm of a number, whereas log10() calculates the standard loarithm i.e. to the base 10
The log() function takes two arguments, the number and base
import math
print ("math.log(100.12) : ", math.log(100.12))
print ("math.log(100.72) : ", math.log(100.72))
print ("math.log(math.pi) : ", math.log(math.pi))
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "In the math module, two functions for calculation of logarithmic value are defined. The log() function returns natural logarithm of a number, whereas log10() calculates the standard loarithm i.e. to the base 10"
},
{
"code": null,
"e": 1333,
"s": 1273,
"text": "The log() function takes two arguments, the number and base"
},
{
"code": null,
"e": 1491,
"s": 1333,
"text": "import math\nprint (\"math.log(100.12) : \", math.log(100.12))\nprint (\"math.log(100.72) : \", math.log(100.72))\nprint (\"math.log(math.pi) : \", math.log(math.pi))"
}
] |
numpy.percentile() in python - GeeksforGeeks
|
01 Sep, 2020
numpy.percentile()function used to compute the nth percentile of the given data (array elements) along the specified axis.
Syntax : numpy.percentile(arr, n, axis=None, out=None) Parameters : arr :input array. n : percentile value. axis : axis along which we want to calculate the percentile value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row. out :Different array in which we want to place the result. The array must have same dimensions as expected output. Return :nth Percentile of the array (a scalar value if axis is none)or array with percentile values along specified axis.
Code #1 : Working
Python
# Python Program illustrating# numpy.percentile() method import numpy as np # 1D arrayarr = [20, 2, 7, 1, 34]print("arr : ", arr)print("50th percentile of arr : ", np.percentile(arr, 50))print("25th percentile of arr : ", np.percentile(arr, 25))print("75th percentile of arr : ", np.percentile(arr, 75))
Output :
arr : [20, 2, 7, 1, 34]
50th percentile of arr : 7.0
25th percentile of arr : 2.0
75th percentile of arr : 20.0
Code #2 :
Python
# Python Program illustrating# numpy.percentile() method import numpy as np # 2D arrayarr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]]print("\narr : \n", arr) # Percentile of the flattened arrayprint("\n50th Percentile of arr, axis = None : ", np.percentile(arr, 50))print("0th Percentile of arr, axis = None : ", np.percentile(arr, 0)) # Percentile along the axis = 0print("\n50th Percentile of arr, axis = 0 : ", np.percentile(arr, 50, axis =0))print("0th Percentile of arr, axis = 0 : ", np.percentile(arr, 0, axis =0))
Output :
arr :
[[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]
50th Percentile of arr, axis = None : 15.0
0th Percentile of arr, axis = None : 1.0
50th Percentile of arr, axis = 0 : [15. 6. 27. 8. 19.]
0th Percentile of arr, axis = 0 : [14. 2. 12. 1. 4.]
50th Percentile of arr, axis = 1 : [17. 15. 4.]
0th Percentile of arr, axis = 1 : [12. 6. 1.]
Code #3 :
Python
# Python Program illustrating# numpy.percentile() method import numpy as np # 2D arrayarr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]]print("\narr : \n", arr) # Percentile along the axis = 1print("\n50th Percentile of arr, axis = 1 : ", np.percentile(arr, 50, axis =1))print("0th Percentile of arr, axis = 1 : ", np.percentile(arr, 0, axis =1)) print("\n0th Percentile of arr, axis = 1 : \n", np.percentile(arr, 50, axis =1, keepdims=True))print("\n0th Percentile of arr, axis = 1 : \n", np.percentile(arr, 0, axis =1, keepdims=True))
Output :
arr :
[[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]
0th Percentile of arr, axis = 1 :
[[17.]
[15.]
[ 4.]]
0th Percentile of arr, axis = 1 :
[[12.]
[ 6.]
[ 1.]]
butterblob
kanishkgoyal
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
Deque in Python
How to Install PIP on Windows ?
Python String | replace()
|
[
{
"code": null,
"e": 23823,
"s": 23795,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 23948,
"s": 23823,
"text": "numpy.percentile()function used to compute the nth percentile of the given data (array elements) along the specified axis. "
},
{
"code": null,
"e": 24508,
"s": 23948,
"text": "Syntax : numpy.percentile(arr, n, axis=None, out=None) Parameters : arr :input array. n : percentile value. axis : axis along which we want to calculate the percentile value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row. out :Different array in which we want to place the result. The array must have same dimensions as expected output. Return :nth Percentile of the array (a scalar value if axis is none)or array with percentile values along specified axis. "
},
{
"code": null,
"e": 24528,
"s": 24508,
"text": "Code #1 : Working "
},
{
"code": null,
"e": 24535,
"s": 24528,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.percentile() method import numpy as np # 1D arrayarr = [20, 2, 7, 1, 34]print(\"arr : \", arr)print(\"50th percentile of arr : \", np.percentile(arr, 50))print(\"25th percentile of arr : \", np.percentile(arr, 25))print(\"75th percentile of arr : \", np.percentile(arr, 75))",
"e": 24861,
"s": 24535,
"text": null
},
{
"code": null,
"e": 24872,
"s": 24861,
"text": "Output : "
},
{
"code": null,
"e": 24991,
"s": 24872,
"text": "arr : [20, 2, 7, 1, 34]\n50th percentile of arr : 7.0\n25th percentile of arr : 2.0\n75th percentile of arr : 20.0\n\n\n"
},
{
"code": null,
"e": 25005,
"s": 24991,
"text": " Code #2 : "
},
{
"code": null,
"e": 25012,
"s": 25005,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.percentile() method import numpy as np # 2D arrayarr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]]print(\"\\narr : \\n\", arr) # Percentile of the flattened arrayprint(\"\\n50th Percentile of arr, axis = None : \", np.percentile(arr, 50))print(\"0th Percentile of arr, axis = None : \", np.percentile(arr, 0)) # Percentile along the axis = 0print(\"\\n50th Percentile of arr, axis = 0 : \", np.percentile(arr, 50, axis =0))print(\"0th Percentile of arr, axis = 0 : \", np.percentile(arr, 0, axis =0))",
"e": 25595,
"s": 25012,
"text": null
},
{
"code": null,
"e": 25606,
"s": 25595,
"text": "Output : "
},
{
"code": null,
"e": 25983,
"s": 25606,
"text": "arr : \n [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]\n\n50th Percentile of arr, axis = None : 15.0\n0th Percentile of arr, axis = None : 1.0\n\n50th Percentile of arr, axis = 0 : [15. 6. 27. 8. 19.]\n0th Percentile of arr, axis = 0 : [14. 2. 12. 1. 4.]\n\n50th Percentile of arr, axis = 1 : [17. 15. 4.]\n0th Percentile of arr, axis = 1 : [12. 6. 1.]\n\n\n\n"
},
{
"code": null,
"e": 25995,
"s": 25983,
"text": "Code #3 : "
},
{
"code": null,
"e": 26002,
"s": 25995,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.percentile() method import numpy as np # 2D arrayarr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4,]]print(\"\\narr : \\n\", arr) # Percentile along the axis = 1print(\"\\n50th Percentile of arr, axis = 1 : \", np.percentile(arr, 50, axis =1))print(\"0th Percentile of arr, axis = 1 : \", np.percentile(arr, 0, axis =1)) print(\"\\n0th Percentile of arr, axis = 1 : \\n\", np.percentile(arr, 50, axis =1, keepdims=True))print(\"\\n0th Percentile of arr, axis = 1 : \\n\", np.percentile(arr, 0, axis =1, keepdims=True))",
"e": 26591,
"s": 26002,
"text": null
},
{
"code": null,
"e": 26602,
"s": 26591,
"text": "Output : "
},
{
"code": null,
"e": 26793,
"s": 26602,
"text": "arr : \n [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]\n\n0th Percentile of arr, axis = 1 : \n [[17.]\n [15.]\n [ 4.]]\n\n0th Percentile of arr, axis = 1 : \n [[12.]\n [ 6.]\n [ 1.]]\n\n\n"
},
{
"code": null,
"e": 26806,
"s": 26795,
"text": "butterblob"
},
{
"code": null,
"e": 26819,
"s": 26806,
"text": "kanishkgoyal"
},
{
"code": null,
"e": 26853,
"s": 26819,
"text": "Python numpy-Statistics Functions"
},
{
"code": null,
"e": 26866,
"s": 26853,
"text": "Python-numpy"
},
{
"code": null,
"e": 26873,
"s": 26866,
"text": "Python"
},
{
"code": null,
"e": 26971,
"s": 26873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26980,
"s": 26971,
"text": "Comments"
},
{
"code": null,
"e": 26993,
"s": 26980,
"text": "Old Comments"
},
{
"code": null,
"e": 27011,
"s": 26993,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27033,
"s": 27011,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27068,
"s": 27033,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27090,
"s": 27068,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27132,
"s": 27090,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27157,
"s": 27132,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27187,
"s": 27157,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27203,
"s": 27187,
"text": "Deque in Python"
},
{
"code": null,
"e": 27235,
"s": 27203,
"text": "How to Install PIP on Windows ?"
}
] |
Garbage Collection in Python - GeeksforGeeks
|
24 Aug, 2021
Python’s memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory similar to using dynamic memory allocation in languages such as C or C++. Python uses two strategies for memory allocation:
Reference counting
Garbage collection
Prior to Python version 2.0, the Python interpreter only used reference counting for memory management. Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is deallocated. Ex-
Python
# Literal 9 is an objectb = 9 # Reference count of object 9# becomes 0.b = 4
The literal value 9 is an object. The reference count of object 9 is incremented to 1 in line 1. In line 2 its reference count becomes zero as it is dereferenced. So garbage collector deallocates the object.A reference cycle is created when there is no way the reference count of the object can reach. Reference cycles involving lists, tuples, instances, classes, dictionaries, and functions are common. The easiest way to create a reference cycle is to create an object which refers to itself as in the example below:
Python
def create_cycle(): # create a list x x = [ ] # A reference cycle is created # here as x contains reference to # to self. x.append(x) create_cycle()
Because create_cycle() creates an object x which refers to itself, the object x will not automatically be freed when the function returns. This will cause the memory that x is using to be held onto until the Python garbage collector is invoked.
Python
x = []x.append(l)x.append(2) # delete the list from memory or# assigning object x to None(Null)del x# x = None
The reference count for the list created is now two. However, since it cannot be reached from inside Python and cannot possibly be used again, it is considered garbage. In the current version of Python, this list is never freed.
Because reference cycles take computational work to discover, garbage collection must be a scheduled activity. Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations is greater than the threshold number, the garbage collector is run. One can inspect the threshold for new objects (objects in Python known as generation 0 objects) by importing the gc module and asking for garbage collection thresholds:
Python
# loading gcimport gc # get the current collection# thresholds as a tupleprint("Garbage collection thresholds:", gc.get_threshold())
Output:
Garbage collection thresholds: (700, 10, 10)
Here, the default threshold on the above system is 700. This means when the number of allocations vs. the number of deallocations is greater than 700 the automatic garbage collector will run. Thus any portion of your code which frees up large blocks of memory is a good candidate for running manual garbage collection.
Invoking the garbage collector manually during the execution of a program can be a good idea on how to handle memory being consumed by reference cycles. The garbage collection can be invoked manually in the following way:
Python
# Importing gc moduleimport gc # Returns the number of# objects it has collected# and deallocatedcollected = gc.collect() # Prints Garbage collector# as 0 objectprint("Garbage collector: collected", "%d objects." % collected)
Output:
('Garbage collector: collected', '0 objects.')
If few cycles are created, then how manual collection works: Example:
Python
import gci = 0 # create a cycle and on each iteration x as a dictionary# assigned to 1def create_cycle(): x = { } x[i+1] = x print x # lists are cleared whenever a full collection or# collection of the highest generation (2) is runcollected = gc.collect() # or gc.collect(2)print "Garbage collector: collected %d objects." % (collected) print "Creating cycles..."for i in range(10): create_cycle() collected = gc.collect() print "Garbage collector: collected %d objects." % (collected)
Output:
Garbage collector: collected 0 objects.
Creating cycles...
{1: {...}}
{2: {...}}
{3: {...}}
{4: {...}}
{5: {...}}
{6: {...}}
{7: {...}}
{8: {...}}
{9: {...}}
{10: {...}}
Garbage collector: collected 10 objects.
There are two ways for performing manual garbage collection: time-based and event-based garbage collection.
Time-based garbage collection is simple: the garbage collector is called after a fixed time interval. Event-based garbage collection calls the garbage collector on event occurrence. For example, when a user exits the application or when the application enters into idle state.
Time-based garbage collection is simple: the garbage collector is called after a fixed time interval.
Event-based garbage collection calls the garbage collector on event occurrence. For example, when a user exits the application or when the application enters into idle state.
Reference
Python Docs
Akanksha_Rai
cannycushalappa
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 24565,
"s": 24316,
"text": "Python’s memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory similar to using dynamic memory allocation in languages such as C or C++. Python uses two strategies for memory allocation: "
},
{
"code": null,
"e": 24584,
"s": 24565,
"text": "Reference counting"
},
{
"code": null,
"e": 24603,
"s": 24584,
"text": "Garbage collection"
},
{
"code": null,
"e": 24983,
"s": 24603,
"text": "Prior to Python version 2.0, the Python interpreter only used reference counting for memory management. Reference counting works by counting the number of times an object is referenced by other objects in the system. When references to an object are removed, the reference count for an object is decremented. When the reference count becomes zero, the object is deallocated. Ex- "
},
{
"code": null,
"e": 24990,
"s": 24983,
"text": "Python"
},
{
"code": "# Literal 9 is an objectb = 9 # Reference count of object 9# becomes 0.b = 4",
"e": 25067,
"s": 24990,
"text": null
},
{
"code": null,
"e": 25587,
"s": 25067,
"text": "The literal value 9 is an object. The reference count of object 9 is incremented to 1 in line 1. In line 2 its reference count becomes zero as it is dereferenced. So garbage collector deallocates the object.A reference cycle is created when there is no way the reference count of the object can reach. Reference cycles involving lists, tuples, instances, classes, dictionaries, and functions are common. The easiest way to create a reference cycle is to create an object which refers to itself as in the example below: "
},
{
"code": null,
"e": 25594,
"s": 25587,
"text": "Python"
},
{
"code": "def create_cycle(): # create a list x x = [ ] # A reference cycle is created # here as x contains reference to # to self. x.append(x) create_cycle()",
"e": 25764,
"s": 25594,
"text": null
},
{
"code": null,
"e": 26009,
"s": 25764,
"text": "Because create_cycle() creates an object x which refers to itself, the object x will not automatically be freed when the function returns. This will cause the memory that x is using to be held onto until the Python garbage collector is invoked."
},
{
"code": null,
"e": 26016,
"s": 26009,
"text": "Python"
},
{
"code": "x = []x.append(l)x.append(2) # delete the list from memory or# assigning object x to None(Null)del x# x = None",
"e": 26127,
"s": 26016,
"text": null
},
{
"code": null,
"e": 26358,
"s": 26127,
"text": "The reference count for the list created is now two. However, since it cannot be reached from inside Python and cannot possibly be used again, it is considered garbage. In the current version of Python, this list is never freed. "
},
{
"code": null,
"e": 26880,
"s": 26358,
"text": "Because reference cycles take computational work to discover, garbage collection must be a scheduled activity. Python schedules garbage collection based upon a threshold of object allocations and object deallocations. When the number of allocations minus the number of deallocations is greater than the threshold number, the garbage collector is run. One can inspect the threshold for new objects (objects in Python known as generation 0 objects) by importing the gc module and asking for garbage collection thresholds: "
},
{
"code": null,
"e": 26887,
"s": 26880,
"text": "Python"
},
{
"code": "# loading gcimport gc # get the current collection# thresholds as a tupleprint(\"Garbage collection thresholds:\", gc.get_threshold())",
"e": 27039,
"s": 26887,
"text": null
},
{
"code": null,
"e": 27048,
"s": 27039,
"text": "Output: "
},
{
"code": null,
"e": 27094,
"s": 27048,
"text": "Garbage collection thresholds: (700, 10, 10) "
},
{
"code": null,
"e": 27415,
"s": 27094,
"text": "Here, the default threshold on the above system is 700. This means when the number of allocations vs. the number of deallocations is greater than 700 the automatic garbage collector will run. Thus any portion of your code which frees up large blocks of memory is a good candidate for running manual garbage collection. "
},
{
"code": null,
"e": 27638,
"s": 27415,
"text": "Invoking the garbage collector manually during the execution of a program can be a good idea on how to handle memory being consumed by reference cycles. The garbage collection can be invoked manually in the following way: "
},
{
"code": null,
"e": 27645,
"s": 27638,
"text": "Python"
},
{
"code": "# Importing gc moduleimport gc # Returns the number of# objects it has collected# and deallocatedcollected = gc.collect() # Prints Garbage collector# as 0 objectprint(\"Garbage collector: collected\", \"%d objects.\" % collected)",
"e": 27880,
"s": 27645,
"text": null
},
{
"code": null,
"e": 27888,
"s": 27880,
"text": "Output:"
},
{
"code": null,
"e": 27935,
"s": 27888,
"text": "('Garbage collector: collected', '0 objects.')"
},
{
"code": null,
"e": 28006,
"s": 27935,
"text": "If few cycles are created, then how manual collection works: Example: "
},
{
"code": null,
"e": 28013,
"s": 28006,
"text": "Python"
},
{
"code": "import gci = 0 # create a cycle and on each iteration x as a dictionary# assigned to 1def create_cycle(): x = { } x[i+1] = x print x # lists are cleared whenever a full collection or# collection of the highest generation (2) is runcollected = gc.collect() # or gc.collect(2)print \"Garbage collector: collected %d objects.\" % (collected) print \"Creating cycles...\"for i in range(10): create_cycle() collected = gc.collect() print \"Garbage collector: collected %d objects.\" % (collected)",
"e": 28511,
"s": 28013,
"text": null
},
{
"code": null,
"e": 28520,
"s": 28511,
"text": "Output: "
},
{
"code": null,
"e": 28731,
"s": 28520,
"text": "Garbage collector: collected 0 objects.\nCreating cycles...\n{1: {...}}\n{2: {...}}\n{3: {...}}\n{4: {...}}\n{5: {...}}\n{6: {...}}\n{7: {...}}\n{8: {...}}\n{9: {...}}\n{10: {...}}\nGarbage collector: collected 10 objects."
},
{
"code": null,
"e": 28840,
"s": 28731,
"text": "There are two ways for performing manual garbage collection: time-based and event-based garbage collection. "
},
{
"code": null,
"e": 29119,
"s": 28840,
"text": "Time-based garbage collection is simple: the garbage collector is called after a fixed time interval. Event-based garbage collection calls the garbage collector on event occurrence. For example, when a user exits the application or when the application enters into idle state. "
},
{
"code": null,
"e": 29222,
"s": 29119,
"text": "Time-based garbage collection is simple: the garbage collector is called after a fixed time interval. "
},
{
"code": null,
"e": 29399,
"s": 29222,
"text": "Event-based garbage collection calls the garbage collector on event occurrence. For example, when a user exits the application or when the application enters into idle state. "
},
{
"code": null,
"e": 29410,
"s": 29399,
"text": "Reference "
},
{
"code": null,
"e": 29422,
"s": 29410,
"text": "Python Docs"
},
{
"code": null,
"e": 29435,
"s": 29422,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29451,
"s": 29435,
"text": "cannycushalappa"
},
{
"code": null,
"e": 29465,
"s": 29451,
"text": "python-basics"
},
{
"code": null,
"e": 29472,
"s": 29465,
"text": "Python"
},
{
"code": null,
"e": 29570,
"s": 29472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29588,
"s": 29570,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29610,
"s": 29588,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29642,
"s": 29610,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29672,
"s": 29642,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29714,
"s": 29672,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29740,
"s": 29714,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29777,
"s": 29740,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29820,
"s": 29777,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29849,
"s": 29820,
"text": "*args and **kwargs in Python"
}
] |
Find the number of distinct islands in a 2D matrix in Python
|
Suppose we have a binary matrix. We have to count the number of islands in it. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water.
Suppose the grid is like −
There are three islands.
To solve this, we will follow these steps −
There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −
There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −
if number of rows in the grid is 0, then return 0
if number of rows in the grid is 0, then return 0
n = row count and m := column count, and ans := 0
n = row count and m := column count, and ans := 0
for i in range 0 to n – 1for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)
for i in range 0 to n – 1
for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)
for j in range 0 to m
if grid[i, j] = 1, then ans := ans + 1
if grid[i, j] = 1, then ans := ans + 1
makeWater(i, j, n, m, grid)
makeWater(i, j, n, m, grid)
the makeWater() will take the indices i, j, row and col count n and m, and grid
the makeWater() will take the indices i, j, row and col count n and m, and grid
if i <0 or j < 0 or i >= n or j >= m, then return from this method
if i <0 or j < 0 or i >= n or j >= m, then return from this method
if grid[i, j] = 0, then return otherwise make grid[i, j] := 0
if grid[i, j] = 0, then return otherwise make grid[i, j] := 0
call makeWater(i + 1, j, n, m, grid)
call makeWater(i + 1, j, n, m, grid)
call makeWater(i, j + 1, n, m, grid)
call makeWater(i, j + 1, n, m, grid)
Let us see the following implementation to get better understanding −
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if len(grid) == 0:
return 0
n= len(grid)
m = len(grid[0])
ans = 0
for i in range(n):
for j in range(m):
if grid[i][j] == "1":
ans+=1
self.make_water(i,j,n,m,grid)
return ans
def make_water(self,i,j,n,m,grid):
if i<0 or j<0 or i>=n or j>=m:
return
if grid[i][j] == "0":
return
else:
grid[i][j]="0"
self.make_water(i+1,j,n,m,grid)
self.make_water(i,j+1,n,m,grid)
self.make_water(i-1,j,n,m,grid)
self.make_water(i,j-1,n,m,grid)
[["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]]
3
|
[
{
"code": null,
"e": 1334,
"s": 1062,
"text": "Suppose we have a binary matrix. We have to count the number of islands in it. An island is place that is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. We can assume that all four edges of the grid are all surrounded by water."
},
{
"code": null,
"e": 1361,
"s": 1334,
"text": "Suppose the grid is like −"
},
{
"code": null,
"e": 1386,
"s": 1361,
"text": "There are three islands."
},
{
"code": null,
"e": 1430,
"s": 1386,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1569,
"s": 1430,
"text": "There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −"
},
{
"code": null,
"e": 1708,
"s": 1569,
"text": "There will be two methods, one will be used to count number of islands called numIslands() and makeWater(). The makeWater() will be like −"
},
{
"code": null,
"e": 1758,
"s": 1708,
"text": "if number of rows in the grid is 0, then return 0"
},
{
"code": null,
"e": 1808,
"s": 1758,
"text": "if number of rows in the grid is 0, then return 0"
},
{
"code": null,
"e": 1858,
"s": 1808,
"text": "n = row count and m := column count, and ans := 0"
},
{
"code": null,
"e": 1908,
"s": 1858,
"text": "n = row count and m := column count, and ans := 0"
},
{
"code": null,
"e": 2020,
"s": 1908,
"text": "for i in range 0 to n – 1for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)"
},
{
"code": null,
"e": 2046,
"s": 2020,
"text": "for i in range 0 to n – 1"
},
{
"code": null,
"e": 2133,
"s": 2046,
"text": "for j in range 0 to mif grid[i, j] = 1, then ans := ans + 1makeWater(i, j, n, m, grid)"
},
{
"code": null,
"e": 2155,
"s": 2133,
"text": "for j in range 0 to m"
},
{
"code": null,
"e": 2194,
"s": 2155,
"text": "if grid[i, j] = 1, then ans := ans + 1"
},
{
"code": null,
"e": 2233,
"s": 2194,
"text": "if grid[i, j] = 1, then ans := ans + 1"
},
{
"code": null,
"e": 2261,
"s": 2233,
"text": "makeWater(i, j, n, m, grid)"
},
{
"code": null,
"e": 2289,
"s": 2261,
"text": "makeWater(i, j, n, m, grid)"
},
{
"code": null,
"e": 2369,
"s": 2289,
"text": "the makeWater() will take the indices i, j, row and col count n and m, and grid"
},
{
"code": null,
"e": 2449,
"s": 2369,
"text": "the makeWater() will take the indices i, j, row and col count n and m, and grid"
},
{
"code": null,
"e": 2516,
"s": 2449,
"text": "if i <0 or j < 0 or i >= n or j >= m, then return from this method"
},
{
"code": null,
"e": 2583,
"s": 2516,
"text": "if i <0 or j < 0 or i >= n or j >= m, then return from this method"
},
{
"code": null,
"e": 2645,
"s": 2583,
"text": "if grid[i, j] = 0, then return otherwise make grid[i, j] := 0"
},
{
"code": null,
"e": 2707,
"s": 2645,
"text": "if grid[i, j] = 0, then return otherwise make grid[i, j] := 0"
},
{
"code": null,
"e": 2744,
"s": 2707,
"text": "call makeWater(i + 1, j, n, m, grid)"
},
{
"code": null,
"e": 2781,
"s": 2744,
"text": "call makeWater(i + 1, j, n, m, grid)"
},
{
"code": null,
"e": 2818,
"s": 2781,
"text": "call makeWater(i, j + 1, n, m, grid)"
},
{
"code": null,
"e": 2855,
"s": 2818,
"text": "call makeWater(i, j + 1, n, m, grid)"
},
{
"code": null,
"e": 2925,
"s": 2855,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3645,
"s": 2925,
"text": "class Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if len(grid) == 0:\n return 0\n n= len(grid)\n m = len(grid[0])\n ans = 0\n for i in range(n):\n for j in range(m):\n if grid[i][j] == \"1\":\n ans+=1\n self.make_water(i,j,n,m,grid)\n return ans\n def make_water(self,i,j,n,m,grid):\n if i<0 or j<0 or i>=n or j>=m:\n return\n if grid[i][j] == \"0\":\n return\n else:\n grid[i][j]=\"0\"\n self.make_water(i+1,j,n,m,grid)\n self.make_water(i,j+1,n,m,grid)\n self.make_water(i-1,j,n,m,grid)\n self.make_water(i,j-1,n,m,grid)"
},
{
"code": null,
"e": 3738,
"s": 3645,
"text": "[[\"1\",\"1\",\"0\",\"0\",\"0\"],\n[\"1\",\"1\",\"0\",\"0\",\"0\"],\n[\"0\",\"0\",\"1\",\"0\",\"0\"],\n[\"0\",\"0\",\"0\",\"1\",\"1\"]]"
},
{
"code": null,
"e": 3740,
"s": 3738,
"text": "3"
}
] |
VBA - Date Function
|
The Function returns the current system date.
date()
Add a button and add the following function.
Private Sub Constant_demo_Click()
Dim a as Variant
a = date()
msgbox "The Value of a : " & a
End Sub
When you execute the function, it produces the following output.
The Value of a : 19/07/2014
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": 1981,
"s": 1935,
"text": "The Function returns the current system date."
},
{
"code": null,
"e": 1989,
"s": 1981,
"text": "date()\n"
},
{
"code": null,
"e": 2034,
"s": 1989,
"text": "Add a button and add the following function."
},
{
"code": null,
"e": 2144,
"s": 2034,
"text": "Private Sub Constant_demo_Click()\n Dim a as Variant\n a = date()\n msgbox \"The Value of a : \" & a\nEnd Sub"
},
{
"code": null,
"e": 2209,
"s": 2144,
"text": "When you execute the function, it produces the following output."
},
{
"code": null,
"e": 2239,
"s": 2209,
"text": "The Value of a : 19/07/2014 \n"
},
{
"code": null,
"e": 2273,
"s": 2239,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2288,
"s": 2273,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2321,
"s": 2288,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2336,
"s": 2321,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2371,
"s": 2336,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2389,
"s": 2371,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2422,
"s": 2389,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2440,
"s": 2422,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2473,
"s": 2440,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2488,
"s": 2473,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2524,
"s": 2488,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 2552,
"s": 2524,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 2559,
"s": 2552,
"text": " Print"
},
{
"code": null,
"e": 2570,
"s": 2559,
"text": " Add Notes"
}
] |
How to create a smooth scrolling effect with CSS?
|
To create a smooth scrolling effect with CSS, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
* {
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0px;
padding: 0px;
}
#firstSection {
height: 100vh;
background-color: rgb(119, 77, 219);
color: white;
padding: 20px;
}
#secondSection {
height: 100vh;
color: white;
background-color: rgb(42, 128, 168);
padding: 20px;
}
a {
text-decoration: none;
font-size: 20px;
font-weight: bold;
color: yellow;
}
</style>
</head>
<body>
<h1>Smooth Scroll Example</h1>
<div id="firstSection">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
<a href="#secondSection">Click Here to Smooth Scroll to Section 2 Below</a>
</div>
<div id="secondSection">
<h2>Section 2</h2>
<a href="#firstSection">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
</body>
</html>
The above code will produce the following output −
On clicking the smooth scroll text we will scroll to section 2 smoothly −
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "To create a smooth scrolling effect with CSS, the code is as follows −"
},
{
"code": null,
"e": 1144,
"s": 1133,
"text": " Live Demo"
},
{
"code": null,
"e": 2145,
"s": 1144,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n html {\n scroll-behavior: smooth;\n }\n * {\n box-sizing: border-box;\n }\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n margin: 0px;\n padding: 0px;\n }\n #firstSection {\n height: 100vh;\n background-color: rgb(119, 77, 219);\n color: white;\n padding: 20px;\n }\n #secondSection {\n height: 100vh;\n color: white;\n background-color: rgb(42, 128, 168);\n padding: 20px;\n }\n a {\n text-decoration: none;\n font-size: 20px;\n font-weight: bold;\n color: yellow;\n }\n</style>\n</head>\n<body>\n<h1>Smooth Scroll Example</h1>\n<div id=\"firstSection\">\n<h2>Section 1</h2>\n<p>Click on the link to see the \"smooth\" scrolling effect.</p>\n<a href=\"#secondSection\">Click Here to Smooth Scroll to Section 2 Below</a>\n</div>\n<div id=\"secondSection\">\n<h2>Section 2</h2>\n<a href=\"#firstSection\">Click Me to Smooth Scroll to Section 1 Above</a>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 2196,
"s": 2145,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2270,
"s": 2196,
"text": "On clicking the smooth scroll text we will scroll to section 2 smoothly −"
}
] |
Tryit Editor v3.7
|
Tryit: class on span elements
|
[] |
Creating an associative array in JavaScript?
|
You can create an associative array in JavaScript using an array of objects with key and value pair.
Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys.
var customerDetails=
[
{
"customerId":"customer-1",
"customerName":"David",
"customerCountryName":"US"
},
{
"customerId":"customer-2",
"customerName":"Bob",
"customerCountryName":"UK"
},
{
"customerId":"customer-3",
"customerName":"Carol",
"customerCountryName":"AUS"
}
]
for(var i=0;i<customerDetails.length;i++){
console.log(customerDetails[i].customerName);
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo115.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo115.js
David
Bob
Carol
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "You can create an associative array in JavaScript using an array of objects with key and value pair."
},
{
"code": null,
"e": 1267,
"s": 1163,
"text": "Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys."
},
{
"code": null,
"e": 1705,
"s": 1267,
"text": "var customerDetails=\n[\n {\n \"customerId\":\"customer-1\",\n \"customerName\":\"David\",\n \"customerCountryName\":\"US\"\n },\n {\n \"customerId\":\"customer-2\",\n \"customerName\":\"Bob\",\n \"customerCountryName\":\"UK\"\n },\n {\n \"customerId\":\"customer-3\",\n \"customerName\":\"Carol\",\n \"customerCountryName\":\"AUS\"\n }\n]\nfor(var i=0;i<customerDetails.length;i++){\n console.log(customerDetails[i].customerName);\n}"
},
{
"code": null,
"e": 1771,
"s": 1705,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1789,
"s": 1771,
"text": "node fileName.js."
},
{
"code": null,
"e": 1823,
"s": 1789,
"text": "Here, my file name is demo115.js."
},
{
"code": null,
"e": 1864,
"s": 1823,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1930,
"s": 1864,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo115.js\nDavid\nBob\nCarol"
}
] |
How to Make XGBoost 200x Faster | Towards Data Science
|
As Data Scientists, we like to run many time-intensive experiments. Reducing the training speed of our models means that we can conduct more experiments in the same amount of time. Moreover, we can also leverage this speed by creating bigger model ensembles, ultimately resulting in higher accuracy.
Chen and Guestrin (from the University of Washington) released XGBoost dates in 2016. They achieved significant speedups and increased predictive power compared to regular gradient boosting (see my book for a comparison, see scikit-learn for regular gradient boosting). This new model soon became data scientists' favorite on Kaggle.
Let’s run XGBoost ‘vanilla’ version on a dummy dataset with 10M rows and 30 columns.
times_cpu = []for trial in range(trials): start = time.time() XGB = XGBRegressor() XGB = XGB.fit(X,Y) print(time.time() — start) times_cpu.append(time.time() — start)
The running time (on my intel i7–7700K CPU @ 4.20GHz computer) is around 2000 seconds. I only tried this setup once since it takes about half an hour of running time.
LGBM was released in 2017 by a Microsoft team. Their groundbreaking idea to make the training faster was to bucket continuous features (read training data) in discrete bins (histograms).
Histogram-based boosting is now considered the best practice for boosting trees. It is now implemented by XGBoost, CatBoost, as well as scikit-learn.
You can use this new histogram-based method by setting tree_method = ‘hist’ when training XGBoost.
times_cpu_hist = []for trial in range(trials): start = time.time() XGB = XGBRegressor(tree_method = “hist”) XGB = XGB.fit(X,Y) print(time.time() — start) times_cpu.append(time.time() — start)
Running time is now 57.7 seconds on average. We just achieved a 35x speed-up!
XGBoost allows you to use your GPU to train models. This usually runs faster than regular CPUs and can be activated easily.
To use your GPU, change tree_method to ‘gpu_hist’
times_gpu = []for trial in range(trials): start = time.time() XGB = XGBRegressor(tree_method = “gpu_hist”) XGB = XGB.fit(X,Y) print(time.time() — start) times_gpu.append(time.time() — start)
Running time is now around 13.1 seconds (using an Nvidia GeForce GTX 1080). That’s 4.4 times faster than the CPU.
Here is how you can use your GPU to run XGBoost on your windows machine.
You can skip this part if you can already run XGBoost on your GPU.
If you installed XGBoost via conda/anaconda, you won’t be able to use your GPU. (If you are unsure how you got XGBoost on your machine, it is 95% likely you got it with anaconda/conda).
Instead, we will install it using pip install.
Open a console and type the two following prompts
First, uninstall XGBoost.
pip uninstall xgboost
Then, reinstall it.
pip install xgboost
Cuda is required to use an Nvidia GPU for machine learning and deep learning.
Download it here: https://developer.nvidia.com/cuda-downloads.
You need to install it using the standard procedure (using the express settings)—nothing specific to do here.
That’s it!
You need to set ‘single_precision_histogram’ to True.
times_gpu_single = []for trial in range(trials): start = time.time() XGB = XGBRegressor(tree_method = “gpu_hist”, single_precision_histogram=True) XGB = XGB.fit(X,Y) print(time.time() — start) times_gpu.append(time.time() — start)
Running time is now 8.7 seconds. That’s a reduction of around 32% compared to the standard GPU method.
⚠️ Note that the single-precision mode won’t always work. If your data exceed the limitations of single-precision floats, you will run into problems. When tracking the squared error of forecasting models, this happened to me: the squared error exceeded the maximum limit that single-precision floating numbers could handle.
Using our GPU (instead of a CPU), histogram-boosting, and single-precision floating numbers, we achieved a 228x training time speed up for XGBoost.
CPU: 2000 seconds
CPU & Histogram: 57.7 seconds
GPU & Histogram: 13.1 seconds
GPU, Histogram & single-precision: 8.7 seconds
🚀 You could speed up the experimentation process further by running experiments in parallel on your GPU and on your CPUs.
⚠️🔬 Don’t forget that this article is using a dummy dataset. The results on your datasets and machine might be different. You should experiment with GPU, histograms, and single-precision before choosing your favorite method.
You might also be interested in this article:
towardsdatascience.com
Nicolas Vandeput is a supply chain data scientist specialized in demand forecasting and inventory optimization. He founded his consultancy company SupChains in 2016 and co-founded SKU Science — a fast, simple, and affordable demand forecasting platform — in 2018. Passionate about education, Nicolas is both an avid learner and enjoys teaching at universities: he has taught forecasting and inventory optimization to master students since 2014 in Brussels, Belgium. Since 2020 he is also teaching both subjects at CentraleSupelec, Paris, France. He published Data Science for Supply Chain Forecasting in 2018 (2nd edition in 2021) and Inventory Optimization: Models and Simulations in 2020.
|
[
{
"code": null,
"e": 472,
"s": 172,
"text": "As Data Scientists, we like to run many time-intensive experiments. Reducing the training speed of our models means that we can conduct more experiments in the same amount of time. Moreover, we can also leverage this speed by creating bigger model ensembles, ultimately resulting in higher accuracy."
},
{
"code": null,
"e": 806,
"s": 472,
"text": "Chen and Guestrin (from the University of Washington) released XGBoost dates in 2016. They achieved significant speedups and increased predictive power compared to regular gradient boosting (see my book for a comparison, see scikit-learn for regular gradient boosting). This new model soon became data scientists' favorite on Kaggle."
},
{
"code": null,
"e": 891,
"s": 806,
"text": "Let’s run XGBoost ‘vanilla’ version on a dummy dataset with 10M rows and 30 columns."
},
{
"code": null,
"e": 1058,
"s": 891,
"text": "times_cpu = []for trial in range(trials): start = time.time() XGB = XGBRegressor() XGB = XGB.fit(X,Y) print(time.time() — start) times_cpu.append(time.time() — start)"
},
{
"code": null,
"e": 1225,
"s": 1058,
"text": "The running time (on my intel i7–7700K CPU @ 4.20GHz computer) is around 2000 seconds. I only tried this setup once since it takes about half an hour of running time."
},
{
"code": null,
"e": 1412,
"s": 1225,
"text": "LGBM was released in 2017 by a Microsoft team. Their groundbreaking idea to make the training faster was to bucket continuous features (read training data) in discrete bins (histograms)."
},
{
"code": null,
"e": 1562,
"s": 1412,
"text": "Histogram-based boosting is now considered the best practice for boosting trees. It is now implemented by XGBoost, CatBoost, as well as scikit-learn."
},
{
"code": null,
"e": 1661,
"s": 1562,
"text": "You can use this new histogram-based method by setting tree_method = ‘hist’ when training XGBoost."
},
{
"code": null,
"e": 1853,
"s": 1661,
"text": "times_cpu_hist = []for trial in range(trials): start = time.time() XGB = XGBRegressor(tree_method = “hist”) XGB = XGB.fit(X,Y) print(time.time() — start) times_cpu.append(time.time() — start)"
},
{
"code": null,
"e": 1931,
"s": 1853,
"text": "Running time is now 57.7 seconds on average. We just achieved a 35x speed-up!"
},
{
"code": null,
"e": 2055,
"s": 1931,
"text": "XGBoost allows you to use your GPU to train models. This usually runs faster than regular CPUs and can be activated easily."
},
{
"code": null,
"e": 2105,
"s": 2055,
"text": "To use your GPU, change tree_method to ‘gpu_hist’"
},
{
"code": null,
"e": 2296,
"s": 2105,
"text": "times_gpu = []for trial in range(trials): start = time.time() XGB = XGBRegressor(tree_method = “gpu_hist”) XGB = XGB.fit(X,Y) print(time.time() — start) times_gpu.append(time.time() — start)"
},
{
"code": null,
"e": 2410,
"s": 2296,
"text": "Running time is now around 13.1 seconds (using an Nvidia GeForce GTX 1080). That’s 4.4 times faster than the CPU."
},
{
"code": null,
"e": 2483,
"s": 2410,
"text": "Here is how you can use your GPU to run XGBoost on your windows machine."
},
{
"code": null,
"e": 2550,
"s": 2483,
"text": "You can skip this part if you can already run XGBoost on your GPU."
},
{
"code": null,
"e": 2736,
"s": 2550,
"text": "If you installed XGBoost via conda/anaconda, you won’t be able to use your GPU. (If you are unsure how you got XGBoost on your machine, it is 95% likely you got it with anaconda/conda)."
},
{
"code": null,
"e": 2783,
"s": 2736,
"text": "Instead, we will install it using pip install."
},
{
"code": null,
"e": 2833,
"s": 2783,
"text": "Open a console and type the two following prompts"
},
{
"code": null,
"e": 2859,
"s": 2833,
"text": "First, uninstall XGBoost."
},
{
"code": null,
"e": 2881,
"s": 2859,
"text": "pip uninstall xgboost"
},
{
"code": null,
"e": 2901,
"s": 2881,
"text": "Then, reinstall it."
},
{
"code": null,
"e": 2921,
"s": 2901,
"text": "pip install xgboost"
},
{
"code": null,
"e": 2999,
"s": 2921,
"text": "Cuda is required to use an Nvidia GPU for machine learning and deep learning."
},
{
"code": null,
"e": 3062,
"s": 2999,
"text": "Download it here: https://developer.nvidia.com/cuda-downloads."
},
{
"code": null,
"e": 3172,
"s": 3062,
"text": "You need to install it using the standard procedure (using the express settings)—nothing specific to do here."
},
{
"code": null,
"e": 3183,
"s": 3172,
"text": "That’s it!"
},
{
"code": null,
"e": 3237,
"s": 3183,
"text": "You need to set ‘single_precision_histogram’ to True."
},
{
"code": null,
"e": 3468,
"s": 3237,
"text": "times_gpu_single = []for trial in range(trials): start = time.time() XGB = XGBRegressor(tree_method = “gpu_hist”, single_precision_histogram=True) XGB = XGB.fit(X,Y) print(time.time() — start) times_gpu.append(time.time() — start)"
},
{
"code": null,
"e": 3571,
"s": 3468,
"text": "Running time is now 8.7 seconds. That’s a reduction of around 32% compared to the standard GPU method."
},
{
"code": null,
"e": 3895,
"s": 3571,
"text": "⚠️ Note that the single-precision mode won’t always work. If your data exceed the limitations of single-precision floats, you will run into problems. When tracking the squared error of forecasting models, this happened to me: the squared error exceeded the maximum limit that single-precision floating numbers could handle."
},
{
"code": null,
"e": 4043,
"s": 3895,
"text": "Using our GPU (instead of a CPU), histogram-boosting, and single-precision floating numbers, we achieved a 228x training time speed up for XGBoost."
},
{
"code": null,
"e": 4061,
"s": 4043,
"text": "CPU: 2000 seconds"
},
{
"code": null,
"e": 4091,
"s": 4061,
"text": "CPU & Histogram: 57.7 seconds"
},
{
"code": null,
"e": 4121,
"s": 4091,
"text": "GPU & Histogram: 13.1 seconds"
},
{
"code": null,
"e": 4168,
"s": 4121,
"text": "GPU, Histogram & single-precision: 8.7 seconds"
},
{
"code": null,
"e": 4290,
"s": 4168,
"text": "🚀 You could speed up the experimentation process further by running experiments in parallel on your GPU and on your CPUs."
},
{
"code": null,
"e": 4515,
"s": 4290,
"text": "⚠️🔬 Don’t forget that this article is using a dummy dataset. The results on your datasets and machine might be different. You should experiment with GPU, histograms, and single-precision before choosing your favorite method."
},
{
"code": null,
"e": 4561,
"s": 4515,
"text": "You might also be interested in this article:"
},
{
"code": null,
"e": 4584,
"s": 4561,
"text": "towardsdatascience.com"
}
] |
C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays
|
A matrix is a rectangular array of numbers that is arranged in the form of rows and columns.
An example of a matrix is as follows.
A 3*3 matrix has 3 rows and 3 columns as shown below −
8 6 3
7 1 9
5 1 9
A program that multiplies two matrices using multidimensional arrays is as follows.
Live Demo
#include<iostream>
using namespace std;
int main() {
int product[10][10], r1=2, c1=3, r2=3, c2=3, i, j, k;
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
} else {
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
product[i][j]+=a[i][k]*b[k][j];
}
cout<<"Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}
}
return 0;
}
The first matrix is:
2 4 1
2 3 9
The second matrix is:
1 2 3
3 6 1
2 9 7
Product of the two matrices is:
16 37 17
29 103 72
In the above program, the two matrices a and b are initialized as follows.
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };
If the number of columns in the first matrix are not equal to the number of rows in the second matrix then multiplication cannot be performed. In this case an error message is printed. It is given as follows.
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
}
Both the matrices a and b are displayed using a nested for loop. This is demonstrated by the following code snippet.
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
After this, the product[][] matrix is initialized to 0. Then a nested for loop is used to find the product of the 2 matrices a and b. This is demonstrated in the below code snippet.
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
product[i][j]+=a[i][k]*b[k][j];
}
After the product is obtained, it is printed. This is shown as follows.
cout<<"Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "A matrix is a rectangular array of numbers that is arranged in the form of rows and columns."
},
{
"code": null,
"e": 1193,
"s": 1155,
"text": "An example of a matrix is as follows."
},
{
"code": null,
"e": 1248,
"s": 1193,
"text": "A 3*3 matrix has 3 rows and 3 columns as shown below −"
},
{
"code": null,
"e": 1266,
"s": 1248,
"text": "8 6 3\n7 1 9\n5 1 9"
},
{
"code": null,
"e": 1350,
"s": 1266,
"text": "A program that multiplies two matrices using multidimensional arrays is as follows."
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": " Live Demo"
},
{
"code": null,
"e": 2444,
"s": 1361,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int product[10][10], r1=2, c1=3, r2=3, c2=3, i, j, k;\n int a[2][3] = { {2, 4, 1} , {2, 3, 9} };\n int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };\n if (c1 != r2) {\n cout<<\"Column of first matrix should be equal to row of second matrix\";\n } else {\n cout<<\"The first matrix is:\"<<endl;\n for(i=0; i<r1; ++i) {\n for(j=0; j<c1; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n cout<<\"The second matrix is:\"<<endl;\n for(i=0; i<r2; ++i) {\n for(j=0; j<c2; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n }\n cout<<endl;\n for(i=0; i<r1; ++i)\n for(j=0; j<c2; ++j) {\n product[i][j] = 0;\n }\n for(i=0; i<r1; ++i)\n for(j=0; j<c2; ++j)\n for(k=0; k<c1; ++k) {\n product[i][j]+=a[i][k]*b[k][j];\n }\n cout<<\"Product of the two matrices is:\"<<endl;\n for(i=0; i<r1; ++i) {\n for(j=0; j<c2; ++j)\n cout<<product[i][j]<<\" \";\n cout<<endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 2570,
"s": 2444,
"text": "The first matrix is:\n2 4 1\n2 3 9\n\nThe second matrix is:\n1 2 3\n3 6 1\n2 9 7\n\nProduct of the two matrices is:\n16 37 17\n29 103 72"
},
{
"code": null,
"e": 2645,
"s": 2570,
"text": "In the above program, the two matrices a and b are initialized as follows."
},
{
"code": null,
"e": 2739,
"s": 2645,
"text": "int a[2][3] = { {2, 4, 1} , {2, 3, 9} };\nint b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };"
},
{
"code": null,
"e": 2948,
"s": 2739,
"text": "If the number of columns in the first matrix are not equal to the number of rows in the second matrix then multiplication cannot be performed. In this case an error message is printed. It is given as follows."
},
{
"code": null,
"e": 3041,
"s": 2948,
"text": "if (c1 != r2) {\n cout<<\"Column of first matrix should be equal to row of second matrix\";\n}"
},
{
"code": null,
"e": 3158,
"s": 3041,
"text": "Both the matrices a and b are displayed using a nested for loop. This is demonstrated by the following code snippet."
},
{
"code": null,
"e": 3425,
"s": 3158,
"text": "cout<<\"The first matrix is:\"<<endl;\nfor(i=0; i<r1; ++i) {\n for(j=0; j<c1; ++j)\n cout<<a[i][j]<<\" \";\n cout<<endl;\n}\ncout<<endl;\ncout<<\"The second matrix is:\"<<endl;\nfor(i=0; i<r2; ++i) {\n for(j=0; j<c2; ++j)\n cout<<b[i][j]<<\" \";\n cout<<endl;\n}\ncout<<endl;"
},
{
"code": null,
"e": 3607,
"s": 3425,
"text": "After this, the product[][] matrix is initialized to 0. Then a nested for loop is used to find the product of the 2 matrices a and b. This is demonstrated in the below code snippet."
},
{
"code": null,
"e": 3772,
"s": 3607,
"text": "for(i=0; i<r1; ++i)\nfor(j=0; j<c2; ++j) {\n product[i][j] = 0;\n}\nfor(i=0; i<r1; ++i)\nfor(j=0; j<c2; ++j)\nfor(k=0; k<c1; ++k) {\n product[i][j]+=a[i][k]*b[k][j];\n}"
},
{
"code": null,
"e": 3844,
"s": 3772,
"text": "After the product is obtained, it is printed. This is shown as follows."
},
{
"code": null,
"e": 3982,
"s": 3844,
"text": "cout<<\"Product of the two matrices is:\"<<endl;\nfor(i=0; i<r1; ++i) {\n for(j=0; j<c2; ++j)\n cout<<product[i][j]<<\" \";\n cout<<endl;\n}"
}
] |
How to use Link Component in ReactJS? - GeeksforGeeks
|
08 Feb, 2021
The Link component allows you to easily customize anchor elements with our own theme colors and typography styles. Material UI for React has this component available for us and it is very easy to integrate. We can use Link Component 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 Link from "@material-ui/core/Link"; const App = () => { const preventDefault = (event) => event.preventDefault(); return ( <div style={{ margin: "auto", display: "table", }} > <h4>How to use Link Component in ReactJS?</h4> <Link href="http://geeksforgeeks.org/" onClick={() => { alert("Redirecting to GeeksforGeeks"); }} > Click GeeksforGeeks </Link> </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:
React-Questions
JavaScript
ReactJS
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
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
How to remove an HTML element using JavaScript ?
Remove elements from a JavaScript Array
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 navigate on path by button click in react router ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 24945,
"s": 24917,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 25219,
"s": 24945,
"text": "The Link component allows you to easily customize anchor elements with our own theme colors and typography styles. Material UI for React has this component available for us and it is very easy to integrate. We can use Link Component in ReactJS using the following approach:"
},
{
"code": null,
"e": 25269,
"s": 25219,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 25333,
"s": 25269,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 25365,
"s": 25333,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 25465,
"s": 25365,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 25479,
"s": 25465,
"text": "cd foldername"
},
{
"code": null,
"e": 25588,
"s": 25479,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:"
},
{
"code": null,
"e": 25618,
"s": 25588,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 25670,
"s": 25618,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25688,
"s": 25670,
"text": "Project Structure"
},
{
"code": null,
"e": 25817,
"s": 25688,
"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": 25828,
"s": 25817,
"text": "Javascript"
},
{
"code": "import React from \"react\";import Link from \"@material-ui/core/Link\"; const App = () => { const preventDefault = (event) => event.preventDefault(); return ( <div style={{ margin: \"auto\", display: \"table\", }} > <h4>How to use Link Component in ReactJS?</h4> <Link href=\"http://geeksforgeeks.org/\" onClick={() => { alert(\"Redirecting to GeeksforGeeks\"); }} > Click GeeksforGeeks </Link> </div> );}; export default App;",
"e": 26341,
"s": 25828,
"text": null
},
{
"code": null,
"e": 26454,
"s": 26341,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 26464,
"s": 26454,
"text": "npm start"
},
{
"code": null,
"e": 26563,
"s": 26464,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 26579,
"s": 26563,
"text": "React-Questions"
},
{
"code": null,
"e": 26590,
"s": 26579,
"text": "JavaScript"
},
{
"code": null,
"e": 26598,
"s": 26590,
"text": "ReactJS"
},
{
"code": null,
"e": 26696,
"s": 26598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26705,
"s": 26696,
"text": "Comments"
},
{
"code": null,
"e": 26718,
"s": 26705,
"text": "Old Comments"
},
{
"code": null,
"e": 26779,
"s": 26718,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26816,
"s": 26779,
"text": "How to create a link in JavaScript ?"
},
{
"code": null,
"e": 26857,
"s": 26816,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 26906,
"s": 26857,
"text": "How to remove an HTML element using JavaScript ?"
},
{
"code": null,
"e": 26946,
"s": 26906,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26989,
"s": 26946,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27034,
"s": 26989,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 27099,
"s": 27034,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 27157,
"s": 27099,
"text": "How to navigate on path by button click in react router ?"
}
] |
WebAssembly - Text Format
|
WebAssembly has the code in a binary format called WASM. You can also get the text format in WebAssembly and it is called WAT (WebAssembly Text format). As a developer you are not supposed to write code in WebAssembly, instead, you have to compile high-level languages like C, C++ and Rust to WebAssembly.
Let us write WAT code stepwise.
Step 1 − The starting point in a WAT is to declare the module.
(module)
Step 2 − Let us now, add some functionality to it in the form of function.
The function is declared as shown below −
(func <parameters/result> <local variables> <function body>)
The function starts with func keyword which is followed by parameters or result.
The parameters and the return value as a result.
The parameters can have the following type supported by wasm −
i32: 32-bit integer
i64: 64-bit integer
f32: 32-bit float
f64: 64-bit float
The params for the functions are written as given below −
(param i32)
(param i64)
(param f32)
(param f64)
The result will be written as follows −
(result i32)
(result i64)
(result f32)
(result f64)
The function with parameters and return value will be defined as follows −
(func (param i32) (param i32) (result i64) <function body>)
The local variables are those that you need in your function. A local value to the function will be defined as follows −
(func (param i32) (param i32) (local i32) (result i64) <function body>)
Function body is the logic to be performed. The final program will look like this −
(module (func (param i32) (param i32) (local i32) (result i64) <function body>) )
Step 3 − To read and set parameters and local variables.
To read the parameters and local variables, make use of get_local and set_local command.
Example
(module
(func (param i32) (param i32) (local i32) (result i64) get_local 0
get_local 1
get_local 2
)
)
As per the function signature,
get_local 0 will give the param i32
get_local 0 will give the param i32
get_local 1 will give the next parameter param i32
get_local 1 will give the next parameter param i32
get_local 2 will give local value i32
get_local 2 will give local value i32
Instead of referring to the parameters and locals using numeric values like 0,1,2, you can also use the name before the parameters, prefixing the name with a dollar sign.
The following example shows, how to use the name with parameters and locals.
Example
(module
(func
(param $a i32)
(param $b i32)
(local $c i32)
(result i64) get_local $a get_local $b get_local $c
)
)
Step 4 − Instruction in Function body and execution.
The execution in wasm follows the stack strategy. The instructions executed are sent one by one on the stack. For example, the instruction get_local $a will push the value, it reads on the stack.
The instruction like i32.add that will add the will pop the elements from the stack.
(func (param $a i32) (param $b i32)
get_local $a
get_local $b
i32.add
)
The instruction for i32.add is ($a+$b). The final value of i32.add, will be pushed on the stack and that will be assigned to the result.
If the function signature has a result declared, there should be one value in the stack at the end of the execution. If there is no result param, the stack has to be empty at the end.
So, the final code along with function body will be as follows −
(module
(func (param $a i32) (param $b i32) (result i32)
get_local $a
get_local $b
i32.add
)
)
Step 5 − Making call to the function.
The final code with the function body is as shown in step 4. Now, to call the function, we need to export it.
To export the function, it can be done with index values like 0,1, but, we can also give names. The name will be prefixed by $ and it will be added after the func keyword.
Example
(module
(func $add (param $a i32) (param $b i32) (result i32)
get_local $a
get_local $b i32.add
)
)
The function $add has to be exported, using export keyword as shown below −
(module
(func $add
(param $a i32)
(param $b i32)
(result i32)
get_local $a get_local $b i32.add
)
(export "add" (func $add))
)
To test the above code in the browser, you will have to convert it into binary form (.wasm). Refer to the next chapter that shows how to convert .WAT to .WASM.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2539,
"s": 2233,
"text": "WebAssembly has the code in a binary format called WASM. You can also get the text format in WebAssembly and it is called WAT (WebAssembly Text format). As a developer you are not supposed to write code in WebAssembly, instead, you have to compile high-level languages like C, C++ and Rust to WebAssembly."
},
{
"code": null,
"e": 2571,
"s": 2539,
"text": "Let us write WAT code stepwise."
},
{
"code": null,
"e": 2634,
"s": 2571,
"text": "Step 1 − The starting point in a WAT is to declare the module."
},
{
"code": null,
"e": 2644,
"s": 2634,
"text": "(module)\n"
},
{
"code": null,
"e": 2719,
"s": 2644,
"text": "Step 2 − Let us now, add some functionality to it in the form of function."
},
{
"code": null,
"e": 2761,
"s": 2719,
"text": "The function is declared as shown below −"
},
{
"code": null,
"e": 2823,
"s": 2761,
"text": "(func <parameters/result> <local variables> <function body>)\n"
},
{
"code": null,
"e": 2904,
"s": 2823,
"text": "The function starts with func keyword which is followed by parameters or result."
},
{
"code": null,
"e": 2953,
"s": 2904,
"text": "The parameters and the return value as a result."
},
{
"code": null,
"e": 3016,
"s": 2953,
"text": "The parameters can have the following type supported by wasm −"
},
{
"code": null,
"e": 3036,
"s": 3016,
"text": "i32: 32-bit integer"
},
{
"code": null,
"e": 3056,
"s": 3036,
"text": "i64: 64-bit integer"
},
{
"code": null,
"e": 3074,
"s": 3056,
"text": "f32: 32-bit float"
},
{
"code": null,
"e": 3092,
"s": 3074,
"text": "f64: 64-bit float"
},
{
"code": null,
"e": 3150,
"s": 3092,
"text": "The params for the functions are written as given below −"
},
{
"code": null,
"e": 3162,
"s": 3150,
"text": "(param i32)"
},
{
"code": null,
"e": 3174,
"s": 3162,
"text": "(param i64)"
},
{
"code": null,
"e": 3186,
"s": 3174,
"text": "(param f32)"
},
{
"code": null,
"e": 3198,
"s": 3186,
"text": "(param f64)"
},
{
"code": null,
"e": 3238,
"s": 3198,
"text": "The result will be written as follows −"
},
{
"code": null,
"e": 3251,
"s": 3238,
"text": "(result i32)"
},
{
"code": null,
"e": 3264,
"s": 3251,
"text": "(result i64)"
},
{
"code": null,
"e": 3277,
"s": 3264,
"text": "(result f32)"
},
{
"code": null,
"e": 3290,
"s": 3277,
"text": "(result f64)"
},
{
"code": null,
"e": 3365,
"s": 3290,
"text": "The function with parameters and return value will be defined as follows −"
},
{
"code": null,
"e": 3426,
"s": 3365,
"text": "(func (param i32) (param i32) (result i64) <function body>)\n"
},
{
"code": null,
"e": 3547,
"s": 3426,
"text": "The local variables are those that you need in your function. A local value to the function will be defined as follows −"
},
{
"code": null,
"e": 3620,
"s": 3547,
"text": "(func (param i32) (param i32) (local i32) (result i64) <function body>)\n"
},
{
"code": null,
"e": 3704,
"s": 3620,
"text": "Function body is the logic to be performed. The final program will look like this −"
},
{
"code": null,
"e": 3787,
"s": 3704,
"text": "(module (func (param i32) (param i32) (local i32) (result i64) <function body>) )\n"
},
{
"code": null,
"e": 3844,
"s": 3787,
"text": "Step 3 − To read and set parameters and local variables."
},
{
"code": null,
"e": 3933,
"s": 3844,
"text": "To read the parameters and local variables, make use of get_local and set_local command."
},
{
"code": null,
"e": 3941,
"s": 3933,
"text": "Example"
},
{
"code": null,
"e": 4068,
"s": 3941,
"text": "(module \n (func (param i32) (param i32) (local i32) (result i64) get_local 0 \n get_local 1 \n get_local 2 \n ) \n)\n"
},
{
"code": null,
"e": 4099,
"s": 4068,
"text": "As per the function signature,"
},
{
"code": null,
"e": 4135,
"s": 4099,
"text": "get_local 0 will give the param i32"
},
{
"code": null,
"e": 4171,
"s": 4135,
"text": "get_local 0 will give the param i32"
},
{
"code": null,
"e": 4222,
"s": 4171,
"text": "get_local 1 will give the next parameter param i32"
},
{
"code": null,
"e": 4273,
"s": 4222,
"text": "get_local 1 will give the next parameter param i32"
},
{
"code": null,
"e": 4311,
"s": 4273,
"text": "get_local 2 will give local value i32"
},
{
"code": null,
"e": 4349,
"s": 4311,
"text": "get_local 2 will give local value i32"
},
{
"code": null,
"e": 4520,
"s": 4349,
"text": "Instead of referring to the parameters and locals using numeric values like 0,1,2, you can also use the name before the parameters, prefixing the name with a dollar sign."
},
{
"code": null,
"e": 4597,
"s": 4520,
"text": "The following example shows, how to use the name with parameters and locals."
},
{
"code": null,
"e": 4605,
"s": 4597,
"text": "Example"
},
{
"code": null,
"e": 4758,
"s": 4605,
"text": "(module \n (func \n (param $a i32) \n (param $b i32) \n (local $c i32) \n (result i64) get_local $a get_local $b get_local $c \n ) \n)\n"
},
{
"code": null,
"e": 4811,
"s": 4758,
"text": "Step 4 − Instruction in Function body and execution."
},
{
"code": null,
"e": 5007,
"s": 4811,
"text": "The execution in wasm follows the stack strategy. The instructions executed are sent one by one on the stack. For example, the instruction get_local $a will push the value, it reads on the stack."
},
{
"code": null,
"e": 5092,
"s": 5007,
"text": "The instruction like i32.add that will add the will pop the elements from the stack."
},
{
"code": null,
"e": 5177,
"s": 5092,
"text": "(func (param $a i32) (param $b i32) \n get_local $a \n get_local $b \n i32.add\n)\n"
},
{
"code": null,
"e": 5314,
"s": 5177,
"text": "The instruction for i32.add is ($a+$b). The final value of i32.add, will be pushed on the stack and that will be assigned to the result."
},
{
"code": null,
"e": 5498,
"s": 5314,
"text": "If the function signature has a result declared, there should be one value in the stack at the end of the execution. If there is no result param, the stack has to be empty at the end."
},
{
"code": null,
"e": 5563,
"s": 5498,
"text": "So, the final code along with function body will be as follows −"
},
{
"code": null,
"e": 5685,
"s": 5563,
"text": "(module \n (func (param $a i32) (param $b i32) (result i32) \n get_local $a\n get_local $b \n i32.add\n )\n)"
},
{
"code": null,
"e": 5723,
"s": 5685,
"text": "Step 5 − Making call to the function."
},
{
"code": null,
"e": 5833,
"s": 5723,
"text": "The final code with the function body is as shown in step 4. Now, to call the function, we need to export it."
},
{
"code": null,
"e": 6005,
"s": 5833,
"text": "To export the function, it can be done with index values like 0,1, but, we can also give names. The name will be prefixed by $ and it will be added after the func keyword."
},
{
"code": null,
"e": 6013,
"s": 6005,
"text": "Example"
},
{
"code": null,
"e": 6135,
"s": 6013,
"text": "(module \n (func $add (param $a i32) (param $b i32) (result i32) \n get_local $a \n get_local $b i32.add\n ) \n)"
},
{
"code": null,
"e": 6211,
"s": 6135,
"text": "The function $add has to be exported, using export keyword as shown below −"
},
{
"code": null,
"e": 6377,
"s": 6211,
"text": "(module \n (func $add \n (param $a i32) \n (param $b i32) \n (result i32) \n get_local $a get_local $b i32.add\n ) \n (export \"add\" (func $add))\n)"
},
{
"code": null,
"e": 6537,
"s": 6377,
"text": "To test the above code in the browser, you will have to convert it into binary form (.wasm). Refer to the next chapter that shows how to convert .WAT to .WASM."
},
{
"code": null,
"e": 6544,
"s": 6537,
"text": " Print"
},
{
"code": null,
"e": 6555,
"s": 6544,
"text": " Add Notes"
}
] |
Authentication Using Fingerprint in Android - GeeksforGeeks
|
20 Dec, 2021
Fingerprint authentication came with Android 6.0 (Marshmallow), with the newly released APIs allowing users to authenticate their smartphones with fingerprint sensors. In order to authenticate users using fingerprint sensors we need the instance of FingerprintManager class and call the authenticate() method. Also, we should take care of the devices that must have fingerprint sensors.
Advantages of using fingerprint authentication:
Fast, Reliable, and Ease to use
High security as each individual has unique fingerprints
Most importantly, it doesn’t matter that you are physically or medically fit or not able to remember your password, fingerprints are always faultless
In this example, we will build an application that asks for users’ fingerprints to authenticate and if the users enter the correct fingerprint then they are allowed to enter into the application.
Step by Step Implementation
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. Make sure while creating a new android project you set the minimum API level to be 23 (Android 6.0).
Step 2: Permission required
In order to use fingerprint authentication, we need to the permission USE_FINGERPRINT to our AndroidMainfest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest> <uses-permission android:name="android.permission.USE_FINGERPRINT" /></manifest>
Before moving further let’s add some color attributes for our application in the colors.xml file.
XML
<resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> <color name="black">#000</color></resources>
Step 3: Creating image assets
In this step, we will create an image asset for fingerprint. Go to drawable > right-click > New > Vector Asset > Clip Art and search for fingerprint and add it to the drawable folder.
Step 4: Creating fingerprint layout
Now, we will create the layout for our fingerprint sensor. Go to activity_main.xml and copy the following code.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:background="@color/colorAccent" tools:context=".MainActivity"> <ImageView android:layout_width="72dp" android:layout_height="72dp" android:layout_margin="8dp" android:src="@drawable/ic_fingerprint" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="#000" android:layout_margin="8dp" android:text="One Touch Sing In"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="#000" android:layout_margin="8dp" android:text="Please place user finger for authentication"/> <TextView android:id="@+id/textMsg" android:textColor="#000" android:layout_width="match_parent" android:gravity="center" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:layout_margin="8dp" android:layout_height="wrap_content"/> </LinearLayout>
Step 5: Working with MainActivity.java file
In this step, we will introduce our FingerprintManager class and initialize it. We will use generateKey() method which will generate an encryption key that is stored securely on the device, we will also use cipherInit() method which initialized the cipher that will be used to create the encrypted FingerprintManager. Below is the code for the MainActivity.java file.
Java
package com.paulsofts.gfgfingerprintauthentication; import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import android.Manifest;import android.annotation.TargetApi;import android.app.KeyguardManager;import android.content.pm.PackageManager;import android.hardware.fingerprint.FingerprintManager;import android.os.Build;import android.os.Bundle;import android.security.keystore.KeyGenParameterSpec;import android.security.keystore.KeyPermanentlyInvalidatedException;import android.security.keystore.KeyProperties;import android.widget.TextView; import java.io.IOException;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.UnrecoverableKeyException;import java.security.cert.CertificateException; import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey; public class MainActivity extends AppCompatActivity { private KeyStore keyStore; // Defining variable for storing // key in android keystore container private static final String KEY_NAME = "GEEKSFORGEEKS"; private Cipher cipher; private TextView errorText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing KeyguardManager and FingerprintManager KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE); // Initializing our error text errorText = (TextView) findViewById(R.id.errorText); // Here, we are using various security checks // Checking device is inbuilt with fingerprint sensor or not if(!fingerprintManager.isHardwareDetected()){ // Setting error message if device // doesn't have fingerprint sensor errorText.setText("Device does not support fingerprint sensor"); }else { // Checking fingerprint permission if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { errorText.setText("Fingerprint authentication is not enabled"); }else{ // Check for at least one registered finger if (!fingerprintManager.hasEnrolledFingerprints()) { errorText.setText("Register at least one finger"); }else{ // Checking for screen lock security if (!keyguardManager.isKeyguardSecure()) { errorText.setText("Screen lock security not enabled"); }else{ // if everything is enabled and correct then we will generate // the encryption key which will be stored on the device generateKey(); if (cipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler helper = new FingerprintHandler(this); helper.startAuth(fingerprintManager, cryptoObject); } } } } } } @TargetApi(Build.VERSION_CODES.M) protected void generateKey() { try { keyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (Exception e) { e.printStackTrace(); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("KeyGenerator instance failed", e); } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings( KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { throw new RuntimeException(e); } } @TargetApi(Build.VERSION_CODES.M) public boolean cipherInit() { try { cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new RuntimeException("Cipher failed", e); } try { keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null); cipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException("Cipher initialization failed", e); } }}
Step 6: Create Fingerprint Authentication Handler class
In this step, we will create a FingerprintHandler.java class and extends FingerprintManager.AuthenticationCallback and override the methods and provide our definitions. Below is the code of FingerpirntHandler class.
Java
import android.Manifest;import android.app.Activity;import android.content.Context;import android.content.pm.PackageManager;import android.hardware.fingerprint.FingerprintManager;import android.os.CancellationSignal;import android.widget.TextView; import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; public class FingerprintHandler extends FingerprintManager.AuthenticationCallback { private Context context; // Constructor public FingerprintHandler(Context mContext) { context = mContext; } // Fingerprint authentication starts here.. public void Authentication(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { CancellationSignal cancellationSignal = new CancellationSignal(); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { return; } manager.authenticate(cryptoObject, cancellationSignal, 0, this, null); } // On authentication failed @Override public void onAuthenticationFailed() { this.update("Authentication Failed!!!", false); } // On successful authentication @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { this.update("Successfully Authenticated...", true); } // This method is used to update the text message // depending on the authentication result public void update(String e, Boolean success){ TextView textView = (TextView) ((Activity)context).findViewById(R.id.textMsg); textView.setText(e); if(success){ textView.setTextColor(ContextCompat.getColor(context,R.color.black)); } }}
Output:
We will test our application on a device that supports a fingerprint sensor. Here, firstly we entered the incorrect finger and we get the Authentication failed message, and then we will enter the correct finger.
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 25112,
"s": 24725,
"text": "Fingerprint authentication came with Android 6.0 (Marshmallow), with the newly released APIs allowing users to authenticate their smartphones with fingerprint sensors. In order to authenticate users using fingerprint sensors we need the instance of FingerprintManager class and call the authenticate() method. Also, we should take care of the devices that must have fingerprint sensors."
},
{
"code": null,
"e": 25160,
"s": 25112,
"text": "Advantages of using fingerprint authentication:"
},
{
"code": null,
"e": 25192,
"s": 25160,
"text": "Fast, Reliable, and Ease to use"
},
{
"code": null,
"e": 25249,
"s": 25192,
"text": "High security as each individual has unique fingerprints"
},
{
"code": null,
"e": 25399,
"s": 25249,
"text": "Most importantly, it doesn’t matter that you are physically or medically fit or not able to remember your password, fingerprints are always faultless"
},
{
"code": null,
"e": 25595,
"s": 25399,
"text": "In this example, we will build an application that asks for users’ fingerprints to authenticate and if the users enter the correct fingerprint then they are allowed to enter into the application."
},
{
"code": null,
"e": 25623,
"s": 25595,
"text": "Step by Step Implementation"
},
{
"code": null,
"e": 25652,
"s": 25623,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 25915,
"s": 25652,
"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. Make sure while creating a new android project you set the minimum API level to be 23 (Android 6.0)."
},
{
"code": null,
"e": 25943,
"s": 25915,
"text": "Step 2: Permission required"
},
{
"code": null,
"e": 26062,
"s": 25943,
"text": "In order to use fingerprint authentication, we need to the permission USE_FINGERPRINT to our AndroidMainfest.xml file."
},
{
"code": null,
"e": 26066,
"s": 26062,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest> <uses-permission android:name=\"android.permission.USE_FINGERPRINT\" /></manifest>",
"e": 26202,
"s": 26066,
"text": null
},
{
"code": null,
"e": 26300,
"s": 26202,
"text": "Before moving further let’s add some color attributes for our application in the colors.xml file."
},
{
"code": null,
"e": 26304,
"s": 26300,
"text": "XML"
},
{
"code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> <color name=\"black\">#000</color></resources>",
"e": 26505,
"s": 26304,
"text": null
},
{
"code": null,
"e": 26535,
"s": 26505,
"text": "Step 3: Creating image assets"
},
{
"code": null,
"e": 26720,
"s": 26535,
"text": "In this step, we will create an image asset for fingerprint. Go to drawable > right-click > New > Vector Asset > Clip Art and search for fingerprint and add it to the drawable folder."
},
{
"code": null,
"e": 26756,
"s": 26720,
"text": "Step 4: Creating fingerprint layout"
},
{
"code": null,
"e": 26868,
"s": 26756,
"text": "Now, we will create the layout for our fingerprint sensor. Go to activity_main.xml and copy the following code."
},
{
"code": null,
"e": 26872,
"s": 26868,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" android:background=\"@color/colorAccent\" tools:context=\".MainActivity\"> <ImageView android:layout_width=\"72dp\" android:layout_height=\"72dp\" android:layout_margin=\"8dp\" android:src=\"@drawable/ic_fingerprint\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:textColor=\"#000\" android:layout_margin=\"8dp\" android:text=\"One Touch Sing In\"/> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:textColor=\"#000\" android:layout_margin=\"8dp\" android:text=\"Please place user finger for authentication\"/> <TextView android:id=\"@+id/textMsg\" android:textColor=\"#000\" android:layout_width=\"match_parent\" android:gravity=\"center\" android:textAppearance=\"@style/TextAppearance.AppCompat.Large\" android:layout_margin=\"8dp\" android:layout_height=\"wrap_content\"/> </LinearLayout>",
"e": 28315,
"s": 26872,
"text": null
},
{
"code": null,
"e": 28359,
"s": 28315,
"text": "Step 5: Working with MainActivity.java file"
},
{
"code": null,
"e": 28727,
"s": 28359,
"text": "In this step, we will introduce our FingerprintManager class and initialize it. We will use generateKey() method which will generate an encryption key that is stored securely on the device, we will also use cipherInit() method which initialized the cipher that will be used to create the encrypted FingerprintManager. Below is the code for the MainActivity.java file."
},
{
"code": null,
"e": 28732,
"s": 28727,
"text": "Java"
},
{
"code": "package com.paulsofts.gfgfingerprintauthentication; import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityCompat; import android.Manifest;import android.annotation.TargetApi;import android.app.KeyguardManager;import android.content.pm.PackageManager;import android.hardware.fingerprint.FingerprintManager;import android.os.Build;import android.os.Bundle;import android.security.keystore.KeyGenParameterSpec;import android.security.keystore.KeyPermanentlyInvalidatedException;import android.security.keystore.KeyProperties;import android.widget.TextView; import java.io.IOException;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.UnrecoverableKeyException;import java.security.cert.CertificateException; import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey; public class MainActivity extends AppCompatActivity { private KeyStore keyStore; // Defining variable for storing // key in android keystore container private static final String KEY_NAME = \"GEEKSFORGEEKS\"; private Cipher cipher; private TextView errorText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing KeyguardManager and FingerprintManager KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE); // Initializing our error text errorText = (TextView) findViewById(R.id.errorText); // Here, we are using various security checks // Checking device is inbuilt with fingerprint sensor or not if(!fingerprintManager.isHardwareDetected()){ // Setting error message if device // doesn't have fingerprint sensor errorText.setText(\"Device does not support fingerprint sensor\"); }else { // Checking fingerprint permission if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { errorText.setText(\"Fingerprint authentication is not enabled\"); }else{ // Check for at least one registered finger if (!fingerprintManager.hasEnrolledFingerprints()) { errorText.setText(\"Register at least one finger\"); }else{ // Checking for screen lock security if (!keyguardManager.isKeyguardSecure()) { errorText.setText(\"Screen lock security not enabled\"); }else{ // if everything is enabled and correct then we will generate // the encryption key which will be stored on the device generateKey(); if (cipherInit()) { FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher); FingerprintHandler helper = new FingerprintHandler(this); helper.startAuth(fingerprintManager, cryptoObject); } } } } } } @TargetApi(Build.VERSION_CODES.M) protected void generateKey() { try { keyStore = KeyStore.getInstance(\"AndroidKeyStore\"); } catch (Exception e) { e.printStackTrace(); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, \"AndroidKeyStore\"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException(\"KeyGenerator instance failed\", e); } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings( KeyProperties.ENCRYPTION_PADDING_PKCS7) .build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { throw new RuntimeException(e); } } @TargetApi(Build.VERSION_CODES.M) public boolean cipherInit() { try { cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + \"/\" + KeyProperties.BLOCK_MODE_CBC + \"/\" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new RuntimeException(\"Cipher failed\", e); } try { keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null); cipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(\"Cipher initialization failed\", e); } }}",
"e": 34548,
"s": 28732,
"text": null
},
{
"code": null,
"e": 34604,
"s": 34548,
"text": "Step 6: Create Fingerprint Authentication Handler class"
},
{
"code": null,
"e": 34820,
"s": 34604,
"text": "In this step, we will create a FingerprintHandler.java class and extends FingerprintManager.AuthenticationCallback and override the methods and provide our definitions. Below is the code of FingerpirntHandler class."
},
{
"code": null,
"e": 34825,
"s": 34820,
"text": "Java"
},
{
"code": "import android.Manifest;import android.app.Activity;import android.content.Context;import android.content.pm.PackageManager;import android.hardware.fingerprint.FingerprintManager;import android.os.CancellationSignal;import android.widget.TextView; import androidx.core.app.ActivityCompat;import androidx.core.content.ContextCompat; public class FingerprintHandler extends FingerprintManager.AuthenticationCallback { private Context context; // Constructor public FingerprintHandler(Context mContext) { context = mContext; } // Fingerprint authentication starts here.. public void Authentication(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { CancellationSignal cancellationSignal = new CancellationSignal(); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { return; } manager.authenticate(cryptoObject, cancellationSignal, 0, this, null); } // On authentication failed @Override public void onAuthenticationFailed() { this.update(\"Authentication Failed!!!\", false); } // On successful authentication @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { this.update(\"Successfully Authenticated...\", true); } // This method is used to update the text message // depending on the authentication result public void update(String e, Boolean success){ TextView textView = (TextView) ((Activity)context).findViewById(R.id.textMsg); textView.setText(e); if(success){ textView.setTextColor(ContextCompat.getColor(context,R.color.black)); } }}",
"e": 36578,
"s": 34825,
"text": null
},
{
"code": null,
"e": 36587,
"s": 36578,
"text": "Output: "
},
{
"code": null,
"e": 36799,
"s": 36587,
"text": "We will test our application on a device that supports a fingerprint sensor. Here, firstly we entered the incorrect finger and we get the Authentication failed message, and then we will enter the correct finger."
},
{
"code": null,
"e": 36806,
"s": 36799,
"text": "Picked"
},
{
"code": null,
"e": 36814,
"s": 36806,
"text": "Android"
},
{
"code": null,
"e": 36819,
"s": 36814,
"text": "Java"
},
{
"code": null,
"e": 36824,
"s": 36819,
"text": "Java"
},
{
"code": null,
"e": 36832,
"s": 36824,
"text": "Android"
},
{
"code": null,
"e": 36930,
"s": 36832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36939,
"s": 36930,
"text": "Comments"
},
{
"code": null,
"e": 36952,
"s": 36939,
"text": "Old Comments"
},
{
"code": null,
"e": 36991,
"s": 36952,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37041,
"s": 36991,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37092,
"s": 37041,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37130,
"s": 37092,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 37172,
"s": 37130,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37187,
"s": 37172,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37231,
"s": 37187,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37253,
"s": 37231,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37278,
"s": 37253,
"text": "Reverse a string in Java"
}
] |
Check valid date format in JavaScript?
|
To check for valid date format, match the date with −
const dateFormat = /^\d{4}\-\d{2}\-\d{2}$/;
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.check-valid-date {
border: 1px solid red;
}
</style>
</head>
<body>
<input type="date" id="check-valid-date" class="form-control
calender-black" name="dateCalender">
<script>
const dateFormat = /^\d{4}\-\d{2}\-\d{2}$/;
document.getElementById("check-valid-date").addEventListener("change",
checkingForValidDate);
function checkingForValidDate() {
console.log(this.value, dateFormat.test(this.value));
this.classList.toggle('check-valid-date',
dateFormat.test(this.value));
}
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now, I am picking a date. The snapshot is as follows −
Above, the console displays TRUE i.e. valid date format.
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "To check for valid date format, match the date with −"
},
{
"code": null,
"e": 1160,
"s": 1116,
"text": "const dateFormat = /^\\d{4}\\-\\d{2}\\-\\d{2}$/;"
},
{
"code": null,
"e": 1171,
"s": 1160,
"text": " Live Demo"
},
{
"code": null,
"e": 2104,
"s": 1171,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<style>\n .check-valid-date {\n border: 1px solid red;\n }\n</style>\n</head>\n<body>\n<input type=\"date\" id=\"check-valid-date\" class=\"form-control\ncalender-black\" name=\"dateCalender\">\n<script>\n const dateFormat = /^\\d{4}\\-\\d{2}\\-\\d{2}$/;\n document.getElementById(\"check-valid-date\").addEventListener(\"change\",\n checkingForValidDate);\n function checkingForValidDate() {\n console.log(this.value, dateFormat.test(this.value));\n this.classList.toggle('check-valid-date',\n dateFormat.test(this.value));\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2266,
"s": 2104,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2307,
"s": 2266,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2362,
"s": 2307,
"text": "Now, I am picking a date. The snapshot is as follows −"
},
{
"code": null,
"e": 2419,
"s": 2362,
"text": "Above, the console displays TRUE i.e. valid date format."
}
] |
HTML - <a> Tag
|
The HTML <a> tag is used for creating a hyperlink to either another document, or somewhere within the current document.
<!DOCTYPE html>
<html>
<head>
<title>HTML a Tag</title>
</head>
<body>
<p>This is a link to <a href = "http://www.amrood.com">AMROOD.com</a></p>
</body>
</html>
This will produce the following result −
This is a link to AMROOD.com
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <a> tag also supports the following additional attributes −
if shape = "rect" then
coords = "left, top, right, bottom"
if shape = "circ" then
coords = "centerx,centery,radius"
if shape = "poly" then
coords = "x1, y1, x2, y2,..,xn,yn"
Where to open the target URL.
_blank - the target URL will open in a new window.
_self - the target URL will open in the same frame as it was clicked.
_parent - the target URL will open in the parent frameset.
_top - the target URL will open in the full body of the window.
This tag supports all the event attributes described in HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2494,
"s": 2374,
"text": "The HTML <a> tag is used for creating a hyperlink to either another document, or somewhere within the current document."
},
{
"code": null,
"e": 2683,
"s": 2494,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML a Tag</title>\n </head>\n\n <body>\n <p>This is a link to <a href = \"http://www.amrood.com\">AMROOD.com</a></p>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 2724,
"s": 2683,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2756,
"s": 2724,
"text": " \nThis is a link to AMROOD.com\n"
},
{
"code": null,
"e": 2838,
"s": 2756,
"text": "This tag supports all the global attributes described in HTML Attribute Reference"
},
{
"code": null,
"e": 2907,
"s": 2838,
"text": "The HTML <a> tag also supports the following additional attributes −"
},
{
"code": null,
"e": 2966,
"s": 2907,
"text": "if shape = \"rect\" then\ncoords = \"left, top, right, bottom\""
},
{
"code": null,
"e": 3023,
"s": 2966,
"text": "if shape = \"circ\" then\ncoords = \"centerx,centery,radius\""
},
{
"code": null,
"e": 3081,
"s": 3023,
"text": "if shape = \"poly\" then\ncoords = \"x1, y1, x2, y2,..,xn,yn\""
},
{
"code": null,
"e": 3111,
"s": 3081,
"text": "Where to open the target URL."
},
{
"code": null,
"e": 3162,
"s": 3111,
"text": "_blank - the target URL will open in a new window."
},
{
"code": null,
"e": 3232,
"s": 3162,
"text": "_self - the target URL will open in the same frame as it was clicked."
},
{
"code": null,
"e": 3291,
"s": 3232,
"text": "_parent - the target URL will open in the parent frameset."
},
{
"code": null,
"e": 3355,
"s": 3291,
"text": "_top - the target URL will open in the full body of the window."
},
{
"code": null,
"e": 3433,
"s": 3355,
"text": "This tag supports all the event attributes described in HTML Events Reference"
},
{
"code": null,
"e": 3466,
"s": 3433,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3480,
"s": 3466,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3515,
"s": 3480,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3529,
"s": 3515,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3564,
"s": 3529,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3581,
"s": 3564,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3616,
"s": 3581,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3647,
"s": 3616,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3680,
"s": 3647,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3711,
"s": 3680,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3746,
"s": 3711,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3777,
"s": 3746,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3784,
"s": 3777,
"text": " Print"
},
{
"code": null,
"e": 3795,
"s": 3784,
"text": " Add Notes"
}
] |
Demand Forecasting: Boston Crime Data | by Alptekin Uzel | Towards Data Science
|
A model that can predict how likely a violent crime may happen on a certain day and at a specific location.
Demand forecasting is a hot topic and a never ending goal in retail, supply-chain management and logistics. Decision makers need to optimize their resources based on the predicted demand, so it is directly linked with optimization problems as well.
Forecast in its common machine learning usage deals with time series data which is one dimensional. Forecasting stock price or number of purchases spanning years are the most common use cases. Additive models like ARIMA are one of the oldest mathematical models in the domain:
Using this well known data — the number of airline passengers for several years — to understand the basics of forecasting is of course helpful. But even upon first glance, it is not hard to guess that real life problems are rarely this easy.
Introduction to the Boston Crime Data
Analyze Boston which is City of Boston’s open data hub publishes various city data. Its Crime incident report is one of them. The city’s tabular data lists crime incidents since 2015. We can see here the leading features (it has 16 columns in total) in their data set:
Incident number: Unique identifier for the incident
Offense Code Group: Incidents are grouped with crime types
Reporting Area: The code for the reporting areas or zones.
Occurred On Date: Date of the incident
Lat: Latitude of the crime location
Long: Longitude of the crime location
Their most up-to-date data has more than 400K rows. They have also uploaded their data set to Kaggle to introduce it and challenge the data science community.
Analysis of the crime types and their trends can surely help us to understand the crime dynamics in the city. But what if we can go a little bit further than that?
The historical data set has a time and space dimension for different types of crimes in the city.
So the most exciting project that can be built is to predict crimes for neighborhoods before they actually happen!
Now we need a frame to structure the problem. Just predicting the number of crimes in a neighborhood or generally in the whole city does not say much and is not useful. We need to predict whether or not rare crimes are going to happen in a specific region.
Also... Problems of this kind are not studied often and Boston Crime Data gives us an opportunity to investigate a challenging problem. Why? More on that in the Challenge section.
Here I will follow the approach that is shared in another paper, “Crime Prediction Using Data Analytics: the Case of the City of Boston.” It contains the core of the solution. I will implement it by using Python with some modifications to the features (less spatial engineering) and the model (Xgboost for increasing accuracy). I will also share the code so that everyone can follow along, and try to improve the predictions. We can summarize it as follows:
We need to predict the probability of some rare event (violent crimes in this case) happening on a specific date with a spatial feature. That way, the police force can use this to concentrate on specific parts of the city each day to prevent violent crimes or at least increase the chance of patrolling there.
And how does this framework shape the data solution? Without too much thought we can say that we are going to:
Aggregate historical crime data for each region/reporting area for each day.
Label those location & days combinations such that if violent crime happened there on that day or not.
Predict a binary value with a probability. This is a classification problem. Logistics regression or decision tree based models can be used.
Since our data set is going to be highly imbalanced, some tuning for the machine learning model and the decision threshold is going to be necessary. Remember that we are predicting rare events.
Notice that we have translated a forecasting problem into a traditional machine learning classification. Why is that?
Difficulties start to arise if we need to forecast multiple values since setting and analyzing ARIMA type models is not easy.
So do we need to build multiple models for that? What happens if we need to build a model for hundreds of time series data? Is that feasible at all?
Let’s list the challenges for forecasting demand when demand is distributed in the city without clear boundaries for a long period of time like a year.
Thinking about the Taxi Demand Prediction can be a good starting point since we will follow a similar logic. In that case we have taxi trip data starting from a certain location at a certain date. Here’s what the challenge in forecasting demand there would be:
Demand is distributed spatially and it is continuous. It does not have centers. Think about several markets in the city, they have fixed locations. You can build forecast models to predict total sales for each of them but here it is not the case.
Even if you cluster demand, there might be way too many cluster centers to build forecast models for each of them.
You know that certain features (like weather or times — like a holiday season) heavily affect the demand. But in traditional time series modelling, it is not possible to add those features. Deep learning (LSTM models for instance) allows that though.
And now, for the Crime Prediction, there is an additional challenge. We need to predict rare events like violent crimes:
Remember that traditional time series forecasting deals with numerical data. Here we need to predict a binary value: 0 or 1.
Method
Now let’s list what we are going to do to create a predictive model:
Divide the space to cluster demand for each spatial unit (grids or reporting areas)
Group crime types into violent and nonviolent crimes.
Aggregate historical crime data for each spatial unit for each day. The label for that row is going to be 1 or 0 depending on whether a violent crime has happened that day in that location.
Integrate historical weather data as a feature for each day in Boston.
Divide the data into a train and test set. Use a specific date such that before that day train data is around 70% and after that date test data is 30% of the all data set.
Build a model which focuses on predicting positive labels: increasing True Positive rate which is sensitivity. (more on that later)
Evaluate the accuracy and sensitivity of the test set by choosing a threshold.
From this point on you can follow the code in the github repo.
After a bit of exploration in the data we can start from the “Cluster Centers from Reporting Area” section. The reporting area centers are calculated by taking the average of the latitude and longitude:
Obviously, there are some outliers. By using the city boundaries file here we draw and extract the reporting areas that are outside the Boston polygon:
# load shape file for 500 citiescity_data = gpd.read_file("geodata/CityBoundaries.shp")# some spatial processing here...# select the reporting areas (points in geodf_ra) that are # in geodf_boston polygon. using spatial join function# in geopandas package geodf_ra_inboston=gpd.sjoin(geodf_ra, geodf_boston, how="inner", op='within')
In the paper, 500 hundred grids are used. So, following the same logic, we can create 500 clusters to have fewer demand centers with a more equally distributed demand surface.
# create 500 centers with K-meansclusterer = KMeans(n_clusters=500,random_state=101).fit(reporting_area_centers[["Long","Lat"]])# get predictions from our Kmeans modelpreds_1 = clusterer.predict(reporting_area_centers[["Long","Lat"]])# set our new column: cluster_noreporting_area_centers["cluster_no"]=preds_1
Now we need to group crime categories (OFFENSE_CODE_GROUP) so that some of them will be labeled as violent crimes. I’ve added the categories based on my assumption about which of these would be violent crimes, but of course you can cross reference the legal definition..
# check labeled crime groups: violent, property and other# the crimes are grouped manually into 3 groups: violent, property or otherdata_1718_ocg=pd.read_csv("./data/data_1718_ocg_grouped.csv")
The ones that are labeled as violent crimes are:
At this point, in the notebook file, we have reached the “Preparing Data for ML: Aggregate data for each cluster&day combination” section.
We have cluster centers labeled with their latitude and longitude. Now we need predictive features!
This is the workhorse of the script: For each day, calculate the past crime statistics of the all cluster centers. It is done for the past 120 days, 30 days, 7 days and 1 day.
For preparation of the script I have first done the calculation for just one day. Then I wrote a “for loop” for the all days.
# check one of the lists:# here we calculated sums for different crimes for the date: 2017-10-3# they are aggregated for each clusters.# in this table we see the results for the past 120 daysworking_120_results.head()
Here we can see the sum of different crime types in different regions for just one day. It is calculated by counting the relevant crime types for that region prior to 120 days.
After checking the sanity of the results we can move on to the larger calculation in: “Calculate the stats for each day for the last 365 days and the last day.” Now we run a loop to aggregate the historical crime data for each cluster and day combination.
# check resulting dataframe. This is going to be our baseline for train&test datacrime_stats_fordays_df.info()
Again, following the paper, we would like to integrate Weather Data into our training set as a predictive feature. We think the weather conditions might affect the violent crimes.
For this reason, we can use the Python Package wwo-hist which encapsulates the Weather API from World Weather Online. I have created a free trial account to gather the API key needed. You might try other options but this seems to be the fastest solution.
# use package: https://github.com/ekapope/WorldWeatherOnlinefrom wwo_hist import retrieve_hist_data# daily frequency.frequency=24start_date = '1-JAN-2015'end_date = '31-DEC-2018'api_key = 'your-api-key-comes-here'location_list = ['boston,ma']# this one runs for all days from start_date to end_date# and saves the results as csv to the current directory.hist_weather_data = retrieve_hist_data(api_key, location_list, start_date, end_date, frequency, location_label = False, export_csv = True, store_df = True)## some processing# include weather data to our aggregated data for: rain, cloud cover and minimum temperature. # you can include more features herecrime_stats_fordays_df=pd.merge(crime_stats_fordays_df,weather_data[["date_time","precipMM","cloudcover","mintempC"]],left_on="theday",right_on="date_time")
We used cloud coverage, minimum temperature and precipitation amount as predictive features.
First we split the data into a train and test set. Since this is time series prediction, we choose a cut-off date such that the data prior to it corresponds to the 70 percent of the data.
Then we decide on the feature columns:
# feature setx_columns=[ 'Lat', 'Long', 'sumviolentcrime120', 'sumpropertycrime120', 'sumothercrime120', 'sumviolentcrime30','sumpropertycrime30', 'sumothercrime30', 'sumviolentcrime7','sumpropertycrime7', 'sumothercrime7', 'sumviolentcrime1','sumpropertycrime1', 'sumothercrime1', 'precipMM','cloudcover', 'mintempC']# outcomey_column=["isviolentcrime"]
Notice that unlike the paper we’ve been following, we use here Longitude and Latitude to identify the location. This is because if you use income data for each grid, you lose the “locality-sensitive” feature of the space coding. To put it simply, we need spatial features such that their coding is close to each other if they are close to each other in two dimensional space. We lose that feature if we just use “income data” since far away neighborhoods might have the same average income.
Another outcome of this choice is that we need to go with the tree based models since Latitude and Longitude do not carry information in linear models like Logistics Regression.
I continued with “Xgboost Classifier” for the model. As we said in the beginning, this a classification problem. We have created aggregated historical features for each cluster center and day. And now we’re going to predict if violent crime happened on that day based on those historical features and the weather data.
I skip the tuning of the model so as not to expand the article too much, but it can be checked in the Jupyter Notebook: “Tune Parameters” section.
# tuned parameters: in the next session we run hyperparameter search with cross validation# these parameters are gathered from that tuning session.# so you can just continue with the tuned parameters# you can switch back and forth between the baseline model and the tuned model to see the# change in accuracy and other parametersxgb_model=xgb.XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, learning_rate=0.1, max_delta_step=0, missing=None, n_estimators=100, n_jobs=1, nthread=None,scale_pos_weight=83, objective='binary:logistic', random_state=101, subsample= 0.6, min_child_weight= 10, max_depth= 3, gamma= 1, colsample_bytree= 0.8)
Now we have probabilities for labeling the “isviolentcrime” target either 1 or 0. But how should we select the decision threshold to label rows (region & day combinations) as 1 or 0?
The assumption derived from the paper is as follows: Let’s assume the police force can patrol 30 percent of the city each day. This finalizes the frame of our problem. We need such a model that predicts positive labels 30 percent of the time. So the police force is going to have 30 percent of the regions labeled as positive in each day.
# 30 percent of the labels: 38250.0X_train.shape[0]* 0.3# tune threshold so that 30 percent of all the labels are predicted as positive# we found we can use 0.48 as our threshold# (38819,)y_pred_prob_pos[y_pred_prob_pos>0.48].shape# it is 1 if greater than 0.48xgb_predictions=np.where(y_pred_prob_pos>0.48,1,0)
Let’s check the metrics for train data:
# my accuracy score: 0.7031058823529411accuracy_score(y_train,xgb_predictions)train_confusion_matrix=confusion_matrix(y_train, xgb_predictions)pd.DataFrame.from_dict({"Negatives":train_confusion_matrix[0], "Positives":train_confusion_matrix[1]},orient='index',columns=["Negative Pred.","Positive Pred."])
Notice out of 1523 positive cases our model predicted 1244 correctly thus having 1244/1523=0.82 True Positive Rate.
Now for the Test set:
Our True Positive Rate (Recall) decreases to 0.73.
It is calculated as 191 / (191+524)
Also we set the threshold for the training data to have 30 percent positive labels. We used the same threshold in the test set and if you check:
# our predictor predicts 28 percent positive labels# police needs to travel 28 percent of the areaxgb_predictions_test.sum() /y_test.shape[0]
In the test set there are even fewer positive predicted labels, which is even better.
So what have we done here? And most importantly, how can this method be used?
First, we clustered crime report areas to have 500 demand centers that are smoothly distributed in the Boston city.
We labeled some crime categories as violent crimes.
Then we used historical crime data to create a training data set. For each cluster center and day we aggregated past crime data to use them as predictive features: Total number of violent crimes in that region for the past 120 days, 30 days, 7 days etc... Total number of property crimes in that region for the past 120 days, 30 days, 7 days etc...
We integrated historical weather data as a predictive feature.
We built a machine learning model to predict if violent crime happened on that day and in that region.
We selected a threshold for our classification model such that the 30 percent of the predictions are positive.
Now this means if historical crime data is aggregated accordingly for each spatial unit (which in our case 500 demand centers distributed in the city) the police can use the model to predict violent crimes. Each day, the police can run the model and they are going to get around 30 percent of the cluster centers with positive predictions for violent crimes. This corresponds to 150 locations out of 500. They can even order those areas with positive labels. The ordering is going to consider corresponding probabilities, and thus prioritize the most risky areas for violent crimes.
With this performance of the model, the police can expect to capture 70 percent of violent crimes by just patrolling 30 percent of the area. If you analyze the historical crime data you can see that there are around seven violent crimes daily. With our True Positive Rate police can expect to be around five of those violent crimes daily.
The problem of predicting violent crimes across Boston City was particularly challenging. It differs from the usual demand forecasting problems:
The usual demand forecasting models have fixed demand and supply centers.
Demand is a continuous feature like total sales or total requests.
In our case:
Demand is distributed in the city continuously. Clustering is needed.
Demand is a categorical feature. The problem is whether violent crime happened there or not.
And as a binary classification problem, our data set is highly imbalanced. Positive labels are only around 2 percent. This adds an extra challenge to the modelling and tuning.
We know that there are 12 police departments / districts in Boston City. So we can try to find optimal locations of 12 supply centers to capture demand for violent crime.
This problem corresponds to facility location problem. And actually I already did that using optimization packages of Python. My next article is going to be about introducing and implementing those packages to solve a linear optimization problem.
I shared my Python code and the prepared data in my github repo.
[1] G. Martegiani, L. Berrada, Crime Prediction Using Data Analytics: the Case of the City of Boston (2016)
[2] A. Jain, Boston Crime Data / Kaggle Data Set, (2018)
[3] Analyze Boston, Crimes in Boston / Kaggle Dataset, (2018)
[4] G. Sharma, Taxi Demand Prediction — New York City — Good Audience (2018)
|
[
{
"code": null,
"e": 279,
"s": 171,
"text": "A model that can predict how likely a violent crime may happen on a certain day and at a specific location."
},
{
"code": null,
"e": 528,
"s": 279,
"text": "Demand forecasting is a hot topic and a never ending goal in retail, supply-chain management and logistics. Decision makers need to optimize their resources based on the predicted demand, so it is directly linked with optimization problems as well."
},
{
"code": null,
"e": 805,
"s": 528,
"text": "Forecast in its common machine learning usage deals with time series data which is one dimensional. Forecasting stock price or number of purchases spanning years are the most common use cases. Additive models like ARIMA are one of the oldest mathematical models in the domain:"
},
{
"code": null,
"e": 1047,
"s": 805,
"text": "Using this well known data — the number of airline passengers for several years — to understand the basics of forecasting is of course helpful. But even upon first glance, it is not hard to guess that real life problems are rarely this easy."
},
{
"code": null,
"e": 1085,
"s": 1047,
"text": "Introduction to the Boston Crime Data"
},
{
"code": null,
"e": 1354,
"s": 1085,
"text": "Analyze Boston which is City of Boston’s open data hub publishes various city data. Its Crime incident report is one of them. The city’s tabular data lists crime incidents since 2015. We can see here the leading features (it has 16 columns in total) in their data set:"
},
{
"code": null,
"e": 1406,
"s": 1354,
"text": "Incident number: Unique identifier for the incident"
},
{
"code": null,
"e": 1465,
"s": 1406,
"text": "Offense Code Group: Incidents are grouped with crime types"
},
{
"code": null,
"e": 1524,
"s": 1465,
"text": "Reporting Area: The code for the reporting areas or zones."
},
{
"code": null,
"e": 1563,
"s": 1524,
"text": "Occurred On Date: Date of the incident"
},
{
"code": null,
"e": 1599,
"s": 1563,
"text": "Lat: Latitude of the crime location"
},
{
"code": null,
"e": 1637,
"s": 1599,
"text": "Long: Longitude of the crime location"
},
{
"code": null,
"e": 1796,
"s": 1637,
"text": "Their most up-to-date data has more than 400K rows. They have also uploaded their data set to Kaggle to introduce it and challenge the data science community."
},
{
"code": null,
"e": 1960,
"s": 1796,
"text": "Analysis of the crime types and their trends can surely help us to understand the crime dynamics in the city. But what if we can go a little bit further than that?"
},
{
"code": null,
"e": 2058,
"s": 1960,
"text": "The historical data set has a time and space dimension for different types of crimes in the city."
},
{
"code": null,
"e": 2173,
"s": 2058,
"text": "So the most exciting project that can be built is to predict crimes for neighborhoods before they actually happen!"
},
{
"code": null,
"e": 2430,
"s": 2173,
"text": "Now we need a frame to structure the problem. Just predicting the number of crimes in a neighborhood or generally in the whole city does not say much and is not useful. We need to predict whether or not rare crimes are going to happen in a specific region."
},
{
"code": null,
"e": 2610,
"s": 2430,
"text": "Also... Problems of this kind are not studied often and Boston Crime Data gives us an opportunity to investigate a challenging problem. Why? More on that in the Challenge section."
},
{
"code": null,
"e": 3068,
"s": 2610,
"text": "Here I will follow the approach that is shared in another paper, “Crime Prediction Using Data Analytics: the Case of the City of Boston.” It contains the core of the solution. I will implement it by using Python with some modifications to the features (less spatial engineering) and the model (Xgboost for increasing accuracy). I will also share the code so that everyone can follow along, and try to improve the predictions. We can summarize it as follows:"
},
{
"code": null,
"e": 3378,
"s": 3068,
"text": "We need to predict the probability of some rare event (violent crimes in this case) happening on a specific date with a spatial feature. That way, the police force can use this to concentrate on specific parts of the city each day to prevent violent crimes or at least increase the chance of patrolling there."
},
{
"code": null,
"e": 3489,
"s": 3378,
"text": "And how does this framework shape the data solution? Without too much thought we can say that we are going to:"
},
{
"code": null,
"e": 3566,
"s": 3489,
"text": "Aggregate historical crime data for each region/reporting area for each day."
},
{
"code": null,
"e": 3669,
"s": 3566,
"text": "Label those location & days combinations such that if violent crime happened there on that day or not."
},
{
"code": null,
"e": 3810,
"s": 3669,
"text": "Predict a binary value with a probability. This is a classification problem. Logistics regression or decision tree based models can be used."
},
{
"code": null,
"e": 4004,
"s": 3810,
"text": "Since our data set is going to be highly imbalanced, some tuning for the machine learning model and the decision threshold is going to be necessary. Remember that we are predicting rare events."
},
{
"code": null,
"e": 4122,
"s": 4004,
"text": "Notice that we have translated a forecasting problem into a traditional machine learning classification. Why is that?"
},
{
"code": null,
"e": 4248,
"s": 4122,
"text": "Difficulties start to arise if we need to forecast multiple values since setting and analyzing ARIMA type models is not easy."
},
{
"code": null,
"e": 4397,
"s": 4248,
"text": "So do we need to build multiple models for that? What happens if we need to build a model for hundreds of time series data? Is that feasible at all?"
},
{
"code": null,
"e": 4549,
"s": 4397,
"text": "Let’s list the challenges for forecasting demand when demand is distributed in the city without clear boundaries for a long period of time like a year."
},
{
"code": null,
"e": 4810,
"s": 4549,
"text": "Thinking about the Taxi Demand Prediction can be a good starting point since we will follow a similar logic. In that case we have taxi trip data starting from a certain location at a certain date. Here’s what the challenge in forecasting demand there would be:"
},
{
"code": null,
"e": 5057,
"s": 4810,
"text": "Demand is distributed spatially and it is continuous. It does not have centers. Think about several markets in the city, they have fixed locations. You can build forecast models to predict total sales for each of them but here it is not the case."
},
{
"code": null,
"e": 5172,
"s": 5057,
"text": "Even if you cluster demand, there might be way too many cluster centers to build forecast models for each of them."
},
{
"code": null,
"e": 5423,
"s": 5172,
"text": "You know that certain features (like weather or times — like a holiday season) heavily affect the demand. But in traditional time series modelling, it is not possible to add those features. Deep learning (LSTM models for instance) allows that though."
},
{
"code": null,
"e": 5544,
"s": 5423,
"text": "And now, for the Crime Prediction, there is an additional challenge. We need to predict rare events like violent crimes:"
},
{
"code": null,
"e": 5669,
"s": 5544,
"text": "Remember that traditional time series forecasting deals with numerical data. Here we need to predict a binary value: 0 or 1."
},
{
"code": null,
"e": 5676,
"s": 5669,
"text": "Method"
},
{
"code": null,
"e": 5745,
"s": 5676,
"text": "Now let’s list what we are going to do to create a predictive model:"
},
{
"code": null,
"e": 5829,
"s": 5745,
"text": "Divide the space to cluster demand for each spatial unit (grids or reporting areas)"
},
{
"code": null,
"e": 5883,
"s": 5829,
"text": "Group crime types into violent and nonviolent crimes."
},
{
"code": null,
"e": 6073,
"s": 5883,
"text": "Aggregate historical crime data for each spatial unit for each day. The label for that row is going to be 1 or 0 depending on whether a violent crime has happened that day in that location."
},
{
"code": null,
"e": 6144,
"s": 6073,
"text": "Integrate historical weather data as a feature for each day in Boston."
},
{
"code": null,
"e": 6316,
"s": 6144,
"text": "Divide the data into a train and test set. Use a specific date such that before that day train data is around 70% and after that date test data is 30% of the all data set."
},
{
"code": null,
"e": 6448,
"s": 6316,
"text": "Build a model which focuses on predicting positive labels: increasing True Positive rate which is sensitivity. (more on that later)"
},
{
"code": null,
"e": 6527,
"s": 6448,
"text": "Evaluate the accuracy and sensitivity of the test set by choosing a threshold."
},
{
"code": null,
"e": 6590,
"s": 6527,
"text": "From this point on you can follow the code in the github repo."
},
{
"code": null,
"e": 6793,
"s": 6590,
"text": "After a bit of exploration in the data we can start from the “Cluster Centers from Reporting Area” section. The reporting area centers are calculated by taking the average of the latitude and longitude:"
},
{
"code": null,
"e": 6945,
"s": 6793,
"text": "Obviously, there are some outliers. By using the city boundaries file here we draw and extract the reporting areas that are outside the Boston polygon:"
},
{
"code": null,
"e": 7279,
"s": 6945,
"text": "# load shape file for 500 citiescity_data = gpd.read_file(\"geodata/CityBoundaries.shp\")# some spatial processing here...# select the reporting areas (points in geodf_ra) that are # in geodf_boston polygon. using spatial join function# in geopandas package geodf_ra_inboston=gpd.sjoin(geodf_ra, geodf_boston, how=\"inner\", op='within')"
},
{
"code": null,
"e": 7455,
"s": 7279,
"text": "In the paper, 500 hundred grids are used. So, following the same logic, we can create 500 clusters to have fewer demand centers with a more equally distributed demand surface."
},
{
"code": null,
"e": 7766,
"s": 7455,
"text": "# create 500 centers with K-meansclusterer = KMeans(n_clusters=500,random_state=101).fit(reporting_area_centers[[\"Long\",\"Lat\"]])# get predictions from our Kmeans modelpreds_1 = clusterer.predict(reporting_area_centers[[\"Long\",\"Lat\"]])# set our new column: cluster_noreporting_area_centers[\"cluster_no\"]=preds_1"
},
{
"code": null,
"e": 8037,
"s": 7766,
"text": "Now we need to group crime categories (OFFENSE_CODE_GROUP) so that some of them will be labeled as violent crimes. I’ve added the categories based on my assumption about which of these would be violent crimes, but of course you can cross reference the legal definition.."
},
{
"code": null,
"e": 8231,
"s": 8037,
"text": "# check labeled crime groups: violent, property and other# the crimes are grouped manually into 3 groups: violent, property or otherdata_1718_ocg=pd.read_csv(\"./data/data_1718_ocg_grouped.csv\")"
},
{
"code": null,
"e": 8280,
"s": 8231,
"text": "The ones that are labeled as violent crimes are:"
},
{
"code": null,
"e": 8419,
"s": 8280,
"text": "At this point, in the notebook file, we have reached the “Preparing Data for ML: Aggregate data for each cluster&day combination” section."
},
{
"code": null,
"e": 8519,
"s": 8419,
"text": "We have cluster centers labeled with their latitude and longitude. Now we need predictive features!"
},
{
"code": null,
"e": 8695,
"s": 8519,
"text": "This is the workhorse of the script: For each day, calculate the past crime statistics of the all cluster centers. It is done for the past 120 days, 30 days, 7 days and 1 day."
},
{
"code": null,
"e": 8821,
"s": 8695,
"text": "For preparation of the script I have first done the calculation for just one day. Then I wrote a “for loop” for the all days."
},
{
"code": null,
"e": 9039,
"s": 8821,
"text": "# check one of the lists:# here we calculated sums for different crimes for the date: 2017-10-3# they are aggregated for each clusters.# in this table we see the results for the past 120 daysworking_120_results.head()"
},
{
"code": null,
"e": 9216,
"s": 9039,
"text": "Here we can see the sum of different crime types in different regions for just one day. It is calculated by counting the relevant crime types for that region prior to 120 days."
},
{
"code": null,
"e": 9472,
"s": 9216,
"text": "After checking the sanity of the results we can move on to the larger calculation in: “Calculate the stats for each day for the last 365 days and the last day.” Now we run a loop to aggregate the historical crime data for each cluster and day combination."
},
{
"code": null,
"e": 9583,
"s": 9472,
"text": "# check resulting dataframe. This is going to be our baseline for train&test datacrime_stats_fordays_df.info()"
},
{
"code": null,
"e": 9763,
"s": 9583,
"text": "Again, following the paper, we would like to integrate Weather Data into our training set as a predictive feature. We think the weather conditions might affect the violent crimes."
},
{
"code": null,
"e": 10018,
"s": 9763,
"text": "For this reason, we can use the Python Package wwo-hist which encapsulates the Weather API from World Weather Online. I have created a free trial account to gather the API key needed. You might try other options but this seems to be the fastest solution."
},
{
"code": null,
"e": 11049,
"s": 10018,
"text": "# use package: https://github.com/ekapope/WorldWeatherOnlinefrom wwo_hist import retrieve_hist_data# daily frequency.frequency=24start_date = '1-JAN-2015'end_date = '31-DEC-2018'api_key = 'your-api-key-comes-here'location_list = ['boston,ma']# this one runs for all days from start_date to end_date# and saves the results as csv to the current directory.hist_weather_data = retrieve_hist_data(api_key, location_list, start_date, end_date, frequency, location_label = False, export_csv = True, store_df = True)## some processing# include weather data to our aggregated data for: rain, cloud cover and minimum temperature. # you can include more features herecrime_stats_fordays_df=pd.merge(crime_stats_fordays_df,weather_data[[\"date_time\",\"precipMM\",\"cloudcover\",\"mintempC\"]],left_on=\"theday\",right_on=\"date_time\")"
},
{
"code": null,
"e": 11142,
"s": 11049,
"text": "We used cloud coverage, minimum temperature and precipitation amount as predictive features."
},
{
"code": null,
"e": 11330,
"s": 11142,
"text": "First we split the data into a train and test set. Since this is time series prediction, we choose a cut-off date such that the data prior to it corresponds to the 70 percent of the data."
},
{
"code": null,
"e": 11369,
"s": 11330,
"text": "Then we decide on the feature columns:"
},
{
"code": null,
"e": 11769,
"s": 11369,
"text": "# feature setx_columns=[ 'Lat', 'Long', 'sumviolentcrime120', 'sumpropertycrime120', 'sumothercrime120', 'sumviolentcrime30','sumpropertycrime30', 'sumothercrime30', 'sumviolentcrime7','sumpropertycrime7', 'sumothercrime7', 'sumviolentcrime1','sumpropertycrime1', 'sumothercrime1', 'precipMM','cloudcover', 'mintempC']# outcomey_column=[\"isviolentcrime\"]"
},
{
"code": null,
"e": 12260,
"s": 11769,
"text": "Notice that unlike the paper we’ve been following, we use here Longitude and Latitude to identify the location. This is because if you use income data for each grid, you lose the “locality-sensitive” feature of the space coding. To put it simply, we need spatial features such that their coding is close to each other if they are close to each other in two dimensional space. We lose that feature if we just use “income data” since far away neighborhoods might have the same average income."
},
{
"code": null,
"e": 12438,
"s": 12260,
"text": "Another outcome of this choice is that we need to go with the tree based models since Latitude and Longitude do not carry information in linear models like Logistics Regression."
},
{
"code": null,
"e": 12757,
"s": 12438,
"text": "I continued with “Xgboost Classifier” for the model. As we said in the beginning, this a classification problem. We have created aggregated historical features for each cluster center and day. And now we’re going to predict if violent crime happened on that day based on those historical features and the weather data."
},
{
"code": null,
"e": 12904,
"s": 12757,
"text": "I skip the tuning of the model so as not to expand the article too much, but it can be checked in the Jupyter Notebook: “Tune Parameters” section."
},
{
"code": null,
"e": 13644,
"s": 12904,
"text": "# tuned parameters: in the next session we run hyperparameter search with cross validation# these parameters are gathered from that tuning session.# so you can just continue with the tuned parameters# you can switch back and forth between the baseline model and the tuned model to see the# change in accuracy and other parametersxgb_model=xgb.XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, learning_rate=0.1, max_delta_step=0, missing=None, n_estimators=100, n_jobs=1, nthread=None,scale_pos_weight=83, objective='binary:logistic', random_state=101, subsample= 0.6, min_child_weight= 10, max_depth= 3, gamma= 1, colsample_bytree= 0.8)"
},
{
"code": null,
"e": 13827,
"s": 13644,
"text": "Now we have probabilities for labeling the “isviolentcrime” target either 1 or 0. But how should we select the decision threshold to label rows (region & day combinations) as 1 or 0?"
},
{
"code": null,
"e": 14166,
"s": 13827,
"text": "The assumption derived from the paper is as follows: Let’s assume the police force can patrol 30 percent of the city each day. This finalizes the frame of our problem. We need such a model that predicts positive labels 30 percent of the time. So the police force is going to have 30 percent of the regions labeled as positive in each day."
},
{
"code": null,
"e": 14478,
"s": 14166,
"text": "# 30 percent of the labels: 38250.0X_train.shape[0]* 0.3# tune threshold so that 30 percent of all the labels are predicted as positive# we found we can use 0.48 as our threshold# (38819,)y_pred_prob_pos[y_pred_prob_pos>0.48].shape# it is 1 if greater than 0.48xgb_predictions=np.where(y_pred_prob_pos>0.48,1,0)"
},
{
"code": null,
"e": 14518,
"s": 14478,
"text": "Let’s check the metrics for train data:"
},
{
"code": null,
"e": 14846,
"s": 14518,
"text": "# my accuracy score: 0.7031058823529411accuracy_score(y_train,xgb_predictions)train_confusion_matrix=confusion_matrix(y_train, xgb_predictions)pd.DataFrame.from_dict({\"Negatives\":train_confusion_matrix[0], \"Positives\":train_confusion_matrix[1]},orient='index',columns=[\"Negative Pred.\",\"Positive Pred.\"])"
},
{
"code": null,
"e": 14962,
"s": 14846,
"text": "Notice out of 1523 positive cases our model predicted 1244 correctly thus having 1244/1523=0.82 True Positive Rate."
},
{
"code": null,
"e": 14984,
"s": 14962,
"text": "Now for the Test set:"
},
{
"code": null,
"e": 15035,
"s": 14984,
"text": "Our True Positive Rate (Recall) decreases to 0.73."
},
{
"code": null,
"e": 15071,
"s": 15035,
"text": "It is calculated as 191 / (191+524)"
},
{
"code": null,
"e": 15216,
"s": 15071,
"text": "Also we set the threshold for the training data to have 30 percent positive labels. We used the same threshold in the test set and if you check:"
},
{
"code": null,
"e": 15358,
"s": 15216,
"text": "# our predictor predicts 28 percent positive labels# police needs to travel 28 percent of the areaxgb_predictions_test.sum() /y_test.shape[0]"
},
{
"code": null,
"e": 15444,
"s": 15358,
"text": "In the test set there are even fewer positive predicted labels, which is even better."
},
{
"code": null,
"e": 15522,
"s": 15444,
"text": "So what have we done here? And most importantly, how can this method be used?"
},
{
"code": null,
"e": 15638,
"s": 15522,
"text": "First, we clustered crime report areas to have 500 demand centers that are smoothly distributed in the Boston city."
},
{
"code": null,
"e": 15690,
"s": 15638,
"text": "We labeled some crime categories as violent crimes."
},
{
"code": null,
"e": 16039,
"s": 15690,
"text": "Then we used historical crime data to create a training data set. For each cluster center and day we aggregated past crime data to use them as predictive features: Total number of violent crimes in that region for the past 120 days, 30 days, 7 days etc... Total number of property crimes in that region for the past 120 days, 30 days, 7 days etc..."
},
{
"code": null,
"e": 16102,
"s": 16039,
"text": "We integrated historical weather data as a predictive feature."
},
{
"code": null,
"e": 16205,
"s": 16102,
"text": "We built a machine learning model to predict if violent crime happened on that day and in that region."
},
{
"code": null,
"e": 16316,
"s": 16205,
"text": "We selected a threshold for our classification model such that the 30 percent of the predictions are positive."
},
{
"code": null,
"e": 16899,
"s": 16316,
"text": "Now this means if historical crime data is aggregated accordingly for each spatial unit (which in our case 500 demand centers distributed in the city) the police can use the model to predict violent crimes. Each day, the police can run the model and they are going to get around 30 percent of the cluster centers with positive predictions for violent crimes. This corresponds to 150 locations out of 500. They can even order those areas with positive labels. The ordering is going to consider corresponding probabilities, and thus prioritize the most risky areas for violent crimes."
},
{
"code": null,
"e": 17238,
"s": 16899,
"text": "With this performance of the model, the police can expect to capture 70 percent of violent crimes by just patrolling 30 percent of the area. If you analyze the historical crime data you can see that there are around seven violent crimes daily. With our True Positive Rate police can expect to be around five of those violent crimes daily."
},
{
"code": null,
"e": 17383,
"s": 17238,
"text": "The problem of predicting violent crimes across Boston City was particularly challenging. It differs from the usual demand forecasting problems:"
},
{
"code": null,
"e": 17457,
"s": 17383,
"text": "The usual demand forecasting models have fixed demand and supply centers."
},
{
"code": null,
"e": 17524,
"s": 17457,
"text": "Demand is a continuous feature like total sales or total requests."
},
{
"code": null,
"e": 17537,
"s": 17524,
"text": "In our case:"
},
{
"code": null,
"e": 17607,
"s": 17537,
"text": "Demand is distributed in the city continuously. Clustering is needed."
},
{
"code": null,
"e": 17700,
"s": 17607,
"text": "Demand is a categorical feature. The problem is whether violent crime happened there or not."
},
{
"code": null,
"e": 17876,
"s": 17700,
"text": "And as a binary classification problem, our data set is highly imbalanced. Positive labels are only around 2 percent. This adds an extra challenge to the modelling and tuning."
},
{
"code": null,
"e": 18047,
"s": 17876,
"text": "We know that there are 12 police departments / districts in Boston City. So we can try to find optimal locations of 12 supply centers to capture demand for violent crime."
},
{
"code": null,
"e": 18294,
"s": 18047,
"text": "This problem corresponds to facility location problem. And actually I already did that using optimization packages of Python. My next article is going to be about introducing and implementing those packages to solve a linear optimization problem."
},
{
"code": null,
"e": 18359,
"s": 18294,
"text": "I shared my Python code and the prepared data in my github repo."
},
{
"code": null,
"e": 18467,
"s": 18359,
"text": "[1] G. Martegiani, L. Berrada, Crime Prediction Using Data Analytics: the Case of the City of Boston (2016)"
},
{
"code": null,
"e": 18524,
"s": 18467,
"text": "[2] A. Jain, Boston Crime Data / Kaggle Data Set, (2018)"
},
{
"code": null,
"e": 18586,
"s": 18524,
"text": "[3] Analyze Boston, Crimes in Boston / Kaggle Dataset, (2018)"
}
] |
Sentiment Analysis using LSTM Step by Step Tutorial | Deep Learning | Towards Data Science
|
I think this result from google dictionary gives a very succinct definition. I don’t have to re-emphasize how important sentiment analysis has become. So, here we will build a classifier on IMDB movie dataset using a Deep Learning technique called RNN.
I’m outlining a step-by-step process for how Recurrent Neural Networks (RNN) can be implemented using Long Short Term Memory (LSTM) architecture:
Load in and visualize the dataData Processing — convert to lower caseData Processing — Remove punctuationData Processing — Create list of reviewsTokenize — Create Vocab to Int mapping dictionaryTokenize — Encode the wordsTokenize — Encode the labelsAnalyze Reviews LengthRemoving Outliers — Getting rid of extremely long or short reviewsPadding / Truncating the remaining dataTraining, Validation, Test Dataset SplitDataloaders and BatchingDefine the LSTM Network ArchitectureDefine the Model ClassTraining the NetworkTesting (on Test data and User- generated data)
Load in and visualize the data
Data Processing — convert to lower case
Data Processing — Remove punctuation
Data Processing — Create list of reviews
Tokenize — Create Vocab to Int mapping dictionary
Tokenize — Encode the words
Tokenize — Encode the labels
Analyze Reviews Length
Removing Outliers — Getting rid of extremely long or short reviews
Padding / Truncating the remaining data
Training, Validation, Test Dataset Split
Dataloaders and Batching
Define the LSTM Network Architecture
Define the Model Class
Training the Network
Testing (on Test data and User- generated data)
1) Load in and visualize the data
We are using IMDB movies review dataset. If it is stored in your machine in a txt file then we just load it in
# read data from text fileswith open(‘data/reviews.txt’, ‘r’) as f: reviews = f.read()with open(‘data/labels.txt’, ‘r’) as f: labels = f.read()print(reviews[:50])print()print(labels[:26])--- Output ---bromwell high is a cartoon comedy . it ran at the same time as some other programs about school life such as teachers . my yearspositivenegativepositive
2) Data Processing — convert to lower case
reviews = reviews.lower()
3) Data Processing — remove punctuation
from string import punctuationprint(punctuation)--- Output ---!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
We saw all the punctuation symbols predefined in python. To get rid of all these punctuation we will simply use
all_text = ''.join([c for c in reviews if c not in punctuation])
4) Data Processing — create list of reviews
We have got all the strings in one huge string. Now we will separate out individual reviews and store them as individual list elements. Like, [review_1, review_2, review_3....... review_n]
reviews_split = all_text.split(‘\n’)print ('Number of reviews :', len(reviews_split))
Number of reviews : 25001
5) Tokenize — Create Vocab to Int mapping dictionary
In most of the NLP tasks, you will create an index mapping dictionary in such a way that your frequently occurring words are assigned lower indexes. One of the most common way of doing this is to use Counter method from Collections library.
from collections import Counterall_text2 = ' '.join(reviews_split)# create a list of wordswords = all_text2.split()# Count all the words using Counter Methodcount_words = Counter(words)total_words = len(words)sorted_words = count_words.most_common(total_words)
Let’s have a look at these objects we have created
print (count_words)--- Output ---Counter({'the': 336713, 'and': 164107, 'a': 163009, 'of': 145864
In order to create a vocab to int mapping dictionary, you would simply do this
vocab_to_int = {w:i for i, (w,c) in enumerate(sorted_words)}
There is a small trick here, in this mapping index will start from 0 i.e. mapping of ‘the’ will be 0. But later on we are going to do padding for shorter reviews and conventional choice for padding is 0. So we need to start this indexing from 1
vocab_to_int = {w:i+1 for i, (w,c) in enumerate(sorted_words)}
Let’s have a look at this mapping dictionary. We can see that mapping for ‘the’ is 1 now
print (vocab_to_int)--- Output ---{'the': 1, 'and': 2, 'a': 3, 'of': 4,
6) Tokenize — Encode the words
So far we have created a) list of reviews and b) index mapping dictionary using vocab from all our reviews. All this was to create an encoding of reviews (replace words in our reviews by integers)
reviews_int = []for review in reviews_split: r = [vocab_to_int[w] for w in review.split()] reviews_int.append(r)print (reviews_int[0:3])--- Output ---[[21025, 308, 6, 3, 1050, 207, 8, 2138, 32, 1, 171, 57, 15, 49, 81, 5785, 44, 382, 110, 140, 15, .....], [5194, 60, 154, 9, 1, 4975, 5852, 475, 71, 5, 260, 12, 21025, 308, 13, 1978, 6, 74, 2395, 5, 613, 73, 6, 5194, 1, 24103, 5, ....], [1983, 10166, 1, 5786, 1499, 36, 51, 66, 204, 145, 67, 1199, 5194.....]]
Note: what we have created now is a list of lists. Each individual review is a list of integer values and all of them are stored in one huge list
7) Tokenize — Encode the labels
This is simple because we only have 2 output labels. So, we will just label ‘positive’ as 1 and ‘negative’ as 0
encoded_labels = [1 if label =='positive' else 0 for label in labels_split]encoded_labels = np.array(encoded_labels)
8) Analyze Reviews Length
import pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinereviews_len = [len(x) for x in reviews_int]pd.Series(reviews_len).hist()plt.show()pd.Series(reviews_len).describe()
Observations : a) Mean review length = 240 b) Some reviews are of 0 length. Keeping this review won’t make any sense for our analysis c) Most of the reviews less than 500 words or more d) There are quite a few reviews that are extremely long, we can manually investigate them to check whether we need to include or exclude them from our analysis
9) Removing Outliers — Getting rid of extremely long or short reviews
reviews_int = [ reviews_int[i] for i, l in enumerate(reviews_len) if l>0 ]encoded_labels = [ encoded_labels[i] for i, l in enumerate(reviews_len) if l> 0 ]
10) Padding / Truncating the remaining data
To deal with both short and long reviews, we will pad or truncate all our reviews to a specific length. We define this length by Sequence Length. This sequence length is same as number of time steps for LSTM layer.
For reviews shorter than seq_length, we will pad with 0s. For reviews longer than seq_length we will truncate them to the first seq_length words.
def pad_features(reviews_int, seq_length): ''' Return features of review_ints, where each review is padded with 0's or truncated to the input seq_length. ''' features = np.zeros((len(reviews_int), seq_length), dtype = int) for i, review in enumerate(reviews_int): review_len = len(review) if review_len <= seq_length: zeroes = list(np.zeros(seq_length-review_len)) new = zeroes+review elif review_len > seq_length: new = review[0:seq_length] features[i,:] = np.array(new) return features
Note: We are creating/maintaining a 2D array structure as we created for reviews_int . Output will look like this
print (features[:10,:])
11) Training, Validation, Test Dataset Split
Once we have got our data in nice shape, we will split it into training, validation and test sets
train= 80% | valid = 10% | test = 10%
split_frac = 0.8train_x = features[0:int(split_frac*len_feat)]train_y = encoded_labels[0:int(split_frac*len_feat)]remaining_x = features[int(split_frac*len_feat):]remaining_y = encoded_labels[int(split_frac*len_feat):]valid_x = remaining_x[0:int(len(remaining_x)*0.5)]valid_y = remaining_y[0:int(len(remaining_y)*0.5)]test_x = remaining_x[int(len(remaining_x)*0.5):]test_y = remaining_y[int(len(remaining_y)*0.5):]
12) Dataloaders and Batching
After creating our training, test and validation data. Next step is to create dataloaders for this data. We can use generator function for batching our data into batches instead we will use a TensorDataset. This is one of a very useful utility in PyTorch for using our data with DataLoaders with exact same ease as of torchvision datasets
import torchfrom torch.utils.data import DataLoader, TensorDataset# create Tensor datasetstrain_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))valid_data = TensorDataset(torch.from_numpy(valid_x), torch.from_numpy(valid_y))test_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy(test_y))# dataloadersbatch_size = 50# make sure to SHUFFLE your datatrain_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)valid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)test_loader = DataLoader(test_data, shuffle=True, batch_size=batch_size)
In order to obtain one batch of training data for visualization purpose we will create a data iterator
# obtain one batch of training datadataiter = iter(train_loader)sample_x, sample_y = dataiter.next()print('Sample input size: ', sample_x.size()) # batch_size, seq_lengthprint('Sample input: \n', sample_x)print()print('Sample label size: ', sample_y.size()) # batch_sizeprint('Sample label: \n', sample_y)
Here, 50 is the batch size and 200 is the sequence length that we have defined. Now our data prep step is complete and next we will look at the LSTM network architecture for start building our model
13) Define the LSTM Network Architecture
The layers are as follows:
0. Tokenize : This is not a layer for LSTM network but a mandatory step of converting our words into tokens (integers)
Embedding Layer: that converts our word tokens (integers) into embedding of specific sizeLSTM Layer: defined by hidden state dims and number of layersFully Connected Layer: that maps output of LSTM layer to a desired output sizeSigmoid Activation Layer: that turns all output values in a value between 0 and 1Output: Sigmoid output from the last timestep is considered as the final output of this network
Embedding Layer: that converts our word tokens (integers) into embedding of specific size
LSTM Layer: defined by hidden state dims and number of layers
Fully Connected Layer: that maps output of LSTM layer to a desired output size
Sigmoid Activation Layer: that turns all output values in a value between 0 and 1
Output: Sigmoid output from the last timestep is considered as the final output of this network
Note: If you want to understand more about these LSTM layers and get a microscopic view of things. Read this one —
towardsdatascience.com
14) Define the Model Class
15) Training the Network
Instantiate the network
# Instantiate the model w/ hyperparamsvocab_size = len(vocab_to_int)+1 # +1 for the 0 paddingoutput_size = 1embedding_dim = 400hidden_dim = 256n_layers = 2net = SentimentLSTM(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)print(net)SentimentLSTM( (embedding): Embedding(74073, 400) (lstm): LSTM(400, 256, num_layers=2, batch_first=True, dropout=0.5) (dropout): Dropout(p=0.3) (fc): Linear(in_features=256, out_features=1, bias=True) (sig): Sigmoid())
Training Loop
Most of the code in training loop is pretty standard Deep Learning training code that you might see often in all the implementations that’s using PyTorch framework.
16) Testing
On Test Data
On User-generated Data
First, we will define a tokenize function that will take care of pre-processing steps and then we will create a predict function that will give us the final output after parsing the user provided review.
test_review = 'This movie had the best acting and the dialogue was so good. I loved it.'seq_length=200 # good to use the length that was trained onpredict(net, test_review_neg, seq_length)
Positive review detected
If you enjoyed this, follow me on medium for more.
Your claps are a huge encouragement and help in writing more and writing better.
Interested in collaborating? Let’s connect on Linkedin.
Please feel free to write your thoughts/suggestions/feedback.
Update: Another article to give you a microscopic view of what happens within the layers.
|
[
{
"code": null,
"e": 425,
"s": 172,
"text": "I think this result from google dictionary gives a very succinct definition. I don’t have to re-emphasize how important sentiment analysis has become. So, here we will build a classifier on IMDB movie dataset using a Deep Learning technique called RNN."
},
{
"code": null,
"e": 571,
"s": 425,
"text": "I’m outlining a step-by-step process for how Recurrent Neural Networks (RNN) can be implemented using Long Short Term Memory (LSTM) architecture:"
},
{
"code": null,
"e": 1137,
"s": 571,
"text": "Load in and visualize the dataData Processing — convert to lower caseData Processing — Remove punctuationData Processing — Create list of reviewsTokenize — Create Vocab to Int mapping dictionaryTokenize — Encode the wordsTokenize — Encode the labelsAnalyze Reviews LengthRemoving Outliers — Getting rid of extremely long or short reviewsPadding / Truncating the remaining dataTraining, Validation, Test Dataset SplitDataloaders and BatchingDefine the LSTM Network ArchitectureDefine the Model ClassTraining the NetworkTesting (on Test data and User- generated data)"
},
{
"code": null,
"e": 1168,
"s": 1137,
"text": "Load in and visualize the data"
},
{
"code": null,
"e": 1208,
"s": 1168,
"text": "Data Processing — convert to lower case"
},
{
"code": null,
"e": 1245,
"s": 1208,
"text": "Data Processing — Remove punctuation"
},
{
"code": null,
"e": 1286,
"s": 1245,
"text": "Data Processing — Create list of reviews"
},
{
"code": null,
"e": 1336,
"s": 1286,
"text": "Tokenize — Create Vocab to Int mapping dictionary"
},
{
"code": null,
"e": 1364,
"s": 1336,
"text": "Tokenize — Encode the words"
},
{
"code": null,
"e": 1393,
"s": 1364,
"text": "Tokenize — Encode the labels"
},
{
"code": null,
"e": 1416,
"s": 1393,
"text": "Analyze Reviews Length"
},
{
"code": null,
"e": 1483,
"s": 1416,
"text": "Removing Outliers — Getting rid of extremely long or short reviews"
},
{
"code": null,
"e": 1523,
"s": 1483,
"text": "Padding / Truncating the remaining data"
},
{
"code": null,
"e": 1564,
"s": 1523,
"text": "Training, Validation, Test Dataset Split"
},
{
"code": null,
"e": 1589,
"s": 1564,
"text": "Dataloaders and Batching"
},
{
"code": null,
"e": 1626,
"s": 1589,
"text": "Define the LSTM Network Architecture"
},
{
"code": null,
"e": 1649,
"s": 1626,
"text": "Define the Model Class"
},
{
"code": null,
"e": 1670,
"s": 1649,
"text": "Training the Network"
},
{
"code": null,
"e": 1718,
"s": 1670,
"text": "Testing (on Test data and User- generated data)"
},
{
"code": null,
"e": 1752,
"s": 1718,
"text": "1) Load in and visualize the data"
},
{
"code": null,
"e": 1863,
"s": 1752,
"text": "We are using IMDB movies review dataset. If it is stored in your machine in a txt file then we just load it in"
},
{
"code": null,
"e": 2222,
"s": 1863,
"text": "# read data from text fileswith open(‘data/reviews.txt’, ‘r’) as f: reviews = f.read()with open(‘data/labels.txt’, ‘r’) as f: labels = f.read()print(reviews[:50])print()print(labels[:26])--- Output ---bromwell high is a cartoon comedy . it ran at the same time as some other programs about school life such as teachers . my yearspositivenegativepositive"
},
{
"code": null,
"e": 2265,
"s": 2222,
"text": "2) Data Processing — convert to lower case"
},
{
"code": null,
"e": 2291,
"s": 2265,
"text": "reviews = reviews.lower()"
},
{
"code": null,
"e": 2331,
"s": 2291,
"text": "3) Data Processing — remove punctuation"
},
{
"code": null,
"e": 2426,
"s": 2331,
"text": "from string import punctuationprint(punctuation)--- Output ---!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
},
{
"code": null,
"e": 2538,
"s": 2426,
"text": "We saw all the punctuation symbols predefined in python. To get rid of all these punctuation we will simply use"
},
{
"code": null,
"e": 2603,
"s": 2538,
"text": "all_text = ''.join([c for c in reviews if c not in punctuation])"
},
{
"code": null,
"e": 2647,
"s": 2603,
"text": "4) Data Processing — create list of reviews"
},
{
"code": null,
"e": 2836,
"s": 2647,
"text": "We have got all the strings in one huge string. Now we will separate out individual reviews and store them as individual list elements. Like, [review_1, review_2, review_3....... review_n]"
},
{
"code": null,
"e": 2922,
"s": 2836,
"text": "reviews_split = all_text.split(‘\\n’)print ('Number of reviews :', len(reviews_split))"
},
{
"code": null,
"e": 2948,
"s": 2922,
"text": "Number of reviews : 25001"
},
{
"code": null,
"e": 3001,
"s": 2948,
"text": "5) Tokenize — Create Vocab to Int mapping dictionary"
},
{
"code": null,
"e": 3242,
"s": 3001,
"text": "In most of the NLP tasks, you will create an index mapping dictionary in such a way that your frequently occurring words are assigned lower indexes. One of the most common way of doing this is to use Counter method from Collections library."
},
{
"code": null,
"e": 3503,
"s": 3242,
"text": "from collections import Counterall_text2 = ' '.join(reviews_split)# create a list of wordswords = all_text2.split()# Count all the words using Counter Methodcount_words = Counter(words)total_words = len(words)sorted_words = count_words.most_common(total_words)"
},
{
"code": null,
"e": 3554,
"s": 3503,
"text": "Let’s have a look at these objects we have created"
},
{
"code": null,
"e": 3652,
"s": 3554,
"text": "print (count_words)--- Output ---Counter({'the': 336713, 'and': 164107, 'a': 163009, 'of': 145864"
},
{
"code": null,
"e": 3731,
"s": 3652,
"text": "In order to create a vocab to int mapping dictionary, you would simply do this"
},
{
"code": null,
"e": 3792,
"s": 3731,
"text": "vocab_to_int = {w:i for i, (w,c) in enumerate(sorted_words)}"
},
{
"code": null,
"e": 4037,
"s": 3792,
"text": "There is a small trick here, in this mapping index will start from 0 i.e. mapping of ‘the’ will be 0. But later on we are going to do padding for shorter reviews and conventional choice for padding is 0. So we need to start this indexing from 1"
},
{
"code": null,
"e": 4100,
"s": 4037,
"text": "vocab_to_int = {w:i+1 for i, (w,c) in enumerate(sorted_words)}"
},
{
"code": null,
"e": 4189,
"s": 4100,
"text": "Let’s have a look at this mapping dictionary. We can see that mapping for ‘the’ is 1 now"
},
{
"code": null,
"e": 4261,
"s": 4189,
"text": "print (vocab_to_int)--- Output ---{'the': 1, 'and': 2, 'a': 3, 'of': 4,"
},
{
"code": null,
"e": 4292,
"s": 4261,
"text": "6) Tokenize — Encode the words"
},
{
"code": null,
"e": 4489,
"s": 4292,
"text": "So far we have created a) list of reviews and b) index mapping dictionary using vocab from all our reviews. All this was to create an encoding of reviews (replace words in our reviews by integers)"
},
{
"code": null,
"e": 4954,
"s": 4489,
"text": "reviews_int = []for review in reviews_split: r = [vocab_to_int[w] for w in review.split()] reviews_int.append(r)print (reviews_int[0:3])--- Output ---[[21025, 308, 6, 3, 1050, 207, 8, 2138, 32, 1, 171, 57, 15, 49, 81, 5785, 44, 382, 110, 140, 15, .....], [5194, 60, 154, 9, 1, 4975, 5852, 475, 71, 5, 260, 12, 21025, 308, 13, 1978, 6, 74, 2395, 5, 613, 73, 6, 5194, 1, 24103, 5, ....], [1983, 10166, 1, 5786, 1499, 36, 51, 66, 204, 145, 67, 1199, 5194.....]]"
},
{
"code": null,
"e": 5100,
"s": 4954,
"text": "Note: what we have created now is a list of lists. Each individual review is a list of integer values and all of them are stored in one huge list"
},
{
"code": null,
"e": 5132,
"s": 5100,
"text": "7) Tokenize — Encode the labels"
},
{
"code": null,
"e": 5244,
"s": 5132,
"text": "This is simple because we only have 2 output labels. So, we will just label ‘positive’ as 1 and ‘negative’ as 0"
},
{
"code": null,
"e": 5361,
"s": 5244,
"text": "encoded_labels = [1 if label =='positive' else 0 for label in labels_split]encoded_labels = np.array(encoded_labels)"
},
{
"code": null,
"e": 5387,
"s": 5361,
"text": "8) Analyze Reviews Length"
},
{
"code": null,
"e": 5571,
"s": 5387,
"text": "import pandas as pdimport matplotlib.pyplot as plt%matplotlib inlinereviews_len = [len(x) for x in reviews_int]pd.Series(reviews_len).hist()plt.show()pd.Series(reviews_len).describe()"
},
{
"code": null,
"e": 5917,
"s": 5571,
"text": "Observations : a) Mean review length = 240 b) Some reviews are of 0 length. Keeping this review won’t make any sense for our analysis c) Most of the reviews less than 500 words or more d) There are quite a few reviews that are extremely long, we can manually investigate them to check whether we need to include or exclude them from our analysis"
},
{
"code": null,
"e": 5987,
"s": 5917,
"text": "9) Removing Outliers — Getting rid of extremely long or short reviews"
},
{
"code": null,
"e": 6143,
"s": 5987,
"text": "reviews_int = [ reviews_int[i] for i, l in enumerate(reviews_len) if l>0 ]encoded_labels = [ encoded_labels[i] for i, l in enumerate(reviews_len) if l> 0 ]"
},
{
"code": null,
"e": 6187,
"s": 6143,
"text": "10) Padding / Truncating the remaining data"
},
{
"code": null,
"e": 6402,
"s": 6187,
"text": "To deal with both short and long reviews, we will pad or truncate all our reviews to a specific length. We define this length by Sequence Length. This sequence length is same as number of time steps for LSTM layer."
},
{
"code": null,
"e": 6548,
"s": 6402,
"text": "For reviews shorter than seq_length, we will pad with 0s. For reviews longer than seq_length we will truncate them to the first seq_length words."
},
{
"code": null,
"e": 7136,
"s": 6548,
"text": "def pad_features(reviews_int, seq_length): ''' Return features of review_ints, where each review is padded with 0's or truncated to the input seq_length. ''' features = np.zeros((len(reviews_int), seq_length), dtype = int) for i, review in enumerate(reviews_int): review_len = len(review) if review_len <= seq_length: zeroes = list(np.zeros(seq_length-review_len)) new = zeroes+review elif review_len > seq_length: new = review[0:seq_length] features[i,:] = np.array(new) return features"
},
{
"code": null,
"e": 7250,
"s": 7136,
"text": "Note: We are creating/maintaining a 2D array structure as we created for reviews_int . Output will look like this"
},
{
"code": null,
"e": 7274,
"s": 7250,
"text": "print (features[:10,:])"
},
{
"code": null,
"e": 7319,
"s": 7274,
"text": "11) Training, Validation, Test Dataset Split"
},
{
"code": null,
"e": 7417,
"s": 7319,
"text": "Once we have got our data in nice shape, we will split it into training, validation and test sets"
},
{
"code": null,
"e": 7455,
"s": 7417,
"text": "train= 80% | valid = 10% | test = 10%"
},
{
"code": null,
"e": 7870,
"s": 7455,
"text": "split_frac = 0.8train_x = features[0:int(split_frac*len_feat)]train_y = encoded_labels[0:int(split_frac*len_feat)]remaining_x = features[int(split_frac*len_feat):]remaining_y = encoded_labels[int(split_frac*len_feat):]valid_x = remaining_x[0:int(len(remaining_x)*0.5)]valid_y = remaining_y[0:int(len(remaining_y)*0.5)]test_x = remaining_x[int(len(remaining_x)*0.5):]test_y = remaining_y[int(len(remaining_y)*0.5):]"
},
{
"code": null,
"e": 7899,
"s": 7870,
"text": "12) Dataloaders and Batching"
},
{
"code": null,
"e": 8238,
"s": 7899,
"text": "After creating our training, test and validation data. Next step is to create dataloaders for this data. We can use generator function for batching our data into batches instead we will use a TensorDataset. This is one of a very useful utility in PyTorch for using our data with DataLoaders with exact same ease as of torchvision datasets"
},
{
"code": null,
"e": 8846,
"s": 8238,
"text": "import torchfrom torch.utils.data import DataLoader, TensorDataset# create Tensor datasetstrain_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))valid_data = TensorDataset(torch.from_numpy(valid_x), torch.from_numpy(valid_y))test_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy(test_y))# dataloadersbatch_size = 50# make sure to SHUFFLE your datatrain_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)valid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)test_loader = DataLoader(test_data, shuffle=True, batch_size=batch_size)"
},
{
"code": null,
"e": 8949,
"s": 8846,
"text": "In order to obtain one batch of training data for visualization purpose we will create a data iterator"
},
{
"code": null,
"e": 9255,
"s": 8949,
"text": "# obtain one batch of training datadataiter = iter(train_loader)sample_x, sample_y = dataiter.next()print('Sample input size: ', sample_x.size()) # batch_size, seq_lengthprint('Sample input: \\n', sample_x)print()print('Sample label size: ', sample_y.size()) # batch_sizeprint('Sample label: \\n', sample_y)"
},
{
"code": null,
"e": 9454,
"s": 9255,
"text": "Here, 50 is the batch size and 200 is the sequence length that we have defined. Now our data prep step is complete and next we will look at the LSTM network architecture for start building our model"
},
{
"code": null,
"e": 9495,
"s": 9454,
"text": "13) Define the LSTM Network Architecture"
},
{
"code": null,
"e": 9522,
"s": 9495,
"text": "The layers are as follows:"
},
{
"code": null,
"e": 9641,
"s": 9522,
"text": "0. Tokenize : This is not a layer for LSTM network but a mandatory step of converting our words into tokens (integers)"
},
{
"code": null,
"e": 10046,
"s": 9641,
"text": "Embedding Layer: that converts our word tokens (integers) into embedding of specific sizeLSTM Layer: defined by hidden state dims and number of layersFully Connected Layer: that maps output of LSTM layer to a desired output sizeSigmoid Activation Layer: that turns all output values in a value between 0 and 1Output: Sigmoid output from the last timestep is considered as the final output of this network"
},
{
"code": null,
"e": 10136,
"s": 10046,
"text": "Embedding Layer: that converts our word tokens (integers) into embedding of specific size"
},
{
"code": null,
"e": 10198,
"s": 10136,
"text": "LSTM Layer: defined by hidden state dims and number of layers"
},
{
"code": null,
"e": 10277,
"s": 10198,
"text": "Fully Connected Layer: that maps output of LSTM layer to a desired output size"
},
{
"code": null,
"e": 10359,
"s": 10277,
"text": "Sigmoid Activation Layer: that turns all output values in a value between 0 and 1"
},
{
"code": null,
"e": 10455,
"s": 10359,
"text": "Output: Sigmoid output from the last timestep is considered as the final output of this network"
},
{
"code": null,
"e": 10570,
"s": 10455,
"text": "Note: If you want to understand more about these LSTM layers and get a microscopic view of things. Read this one —"
},
{
"code": null,
"e": 10593,
"s": 10570,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10620,
"s": 10593,
"text": "14) Define the Model Class"
},
{
"code": null,
"e": 10645,
"s": 10620,
"text": "15) Training the Network"
},
{
"code": null,
"e": 10669,
"s": 10645,
"text": "Instantiate the network"
},
{
"code": null,
"e": 11139,
"s": 10669,
"text": "# Instantiate the model w/ hyperparamsvocab_size = len(vocab_to_int)+1 # +1 for the 0 paddingoutput_size = 1embedding_dim = 400hidden_dim = 256n_layers = 2net = SentimentLSTM(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)print(net)SentimentLSTM( (embedding): Embedding(74073, 400) (lstm): LSTM(400, 256, num_layers=2, batch_first=True, dropout=0.5) (dropout): Dropout(p=0.3) (fc): Linear(in_features=256, out_features=1, bias=True) (sig): Sigmoid())"
},
{
"code": null,
"e": 11153,
"s": 11139,
"text": "Training Loop"
},
{
"code": null,
"e": 11318,
"s": 11153,
"text": "Most of the code in training loop is pretty standard Deep Learning training code that you might see often in all the implementations that’s using PyTorch framework."
},
{
"code": null,
"e": 11330,
"s": 11318,
"text": "16) Testing"
},
{
"code": null,
"e": 11343,
"s": 11330,
"text": "On Test Data"
},
{
"code": null,
"e": 11366,
"s": 11343,
"text": "On User-generated Data"
},
{
"code": null,
"e": 11570,
"s": 11366,
"text": "First, we will define a tokenize function that will take care of pre-processing steps and then we will create a predict function that will give us the final output after parsing the user provided review."
},
{
"code": null,
"e": 11759,
"s": 11570,
"text": "test_review = 'This movie had the best acting and the dialogue was so good. I loved it.'seq_length=200 # good to use the length that was trained onpredict(net, test_review_neg, seq_length)"
},
{
"code": null,
"e": 11784,
"s": 11759,
"text": "Positive review detected"
},
{
"code": null,
"e": 11835,
"s": 11784,
"text": "If you enjoyed this, follow me on medium for more."
},
{
"code": null,
"e": 11916,
"s": 11835,
"text": "Your claps are a huge encouragement and help in writing more and writing better."
},
{
"code": null,
"e": 11972,
"s": 11916,
"text": "Interested in collaborating? Let’s connect on Linkedin."
},
{
"code": null,
"e": 12034,
"s": 11972,
"text": "Please feel free to write your thoughts/suggestions/feedback."
}
] |
Counting frequencies of array elements in C++
|
We are given an array of integer elements which contains duplicate values and the task is to calculate the frequencies of the distinct elements present in an array and print the result.
Input − int arr[] = {1, 1, 2, 3, 4, 1, 2, 3}
Output −
frequency of 1 is: 3
frequency of 2 is: 2
frequency of 3 is: 2
Frequency of 4 is: 1
Input − int arr[] = {2, 3, 4, 1, 5}
Output −
frequency of 1 is: 1
frequency of 2 is: 1
frequency of 3 is: 1
Frequency of 4 is: 1
Frequency of 5 is: 1
There can be multiple solutions for this and those can be simpler in coding terms or simpler in complexity terms. So let’s first look at the simpler approach in coding terms
Create an array of integer type variables
Create an array of integer type variables
Calculate the size of an array using size() function.
Calculate the size of an array using size() function.
Create a boolean array let’s say, check of array size
Create a boolean array let’s say, check of array size
Start loop FOR from i to 0 and i less than size
Start loop FOR from i to 0 and i less than size
Inside the loop, set check[i] = 0
Inside the loop, set check[i] = 0
Start loop FOR from i to 0 and i less than size
Start loop FOR from i to 0 and i less than size
Inside the loop, check IF check[i] = 1 then continue
Inside the loop, check IF check[i] = 1 then continue
Declare variable count and initialise it with 1 that will print the frequency count
Declare variable count and initialise it with 1 that will print the frequency count
Start loop FOR j from i+1 till the size
Start loop FOR j from i+1 till the size
Inside the loop, check if arr[i] = arr[j] then set check[j] to 1 and increment the count by 1
Inside the loop, check if arr[i] = arr[j] then set check[j] to 1 and increment the count by 1
Print the value of count.
Print the value of count.
Another solution of it can be −
Create an array of integer type variables
Create an array of integer type variables
Calculate the size of an array using size() function.
Calculate the size of an array using size() function.
Create a variable of type unordered_map let’s say um
Create a variable of type unordered_map let’s say um
Start loop FOR from i to 0 and till size
Start loop FOR from i to 0 and till size
Inside the loop, set um[arr[i]]++
Inside the loop, set um[arr[i]]++
Start another loop for from auto x till um
Start another loop for from auto x till um
Inside the loop, print the frequency.
Inside the loop, print the frequency.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int frequency(int arr[], int size){
bool check[size];
for(int i=0;i<size;i++){
check[i] = 0;
}
for(int i=0; i<size; i++){
if(check[i]== 1){
continue;
}
int count = 1;
for(int j = i+1; j<size; j++){
if (arr[i] == arr[j]){
check[j] = 1;
count++;
}
}
cout<<"frequency of "<<arr[i]<<" is: " << count << endl;
}
}
int main(){
int arr[] = {1, 2, 3, 1, 2, 3};
//calculate the size of an array
int size = sizeof(arr) / sizeof(arr[0]);
//call function to calculate the frequency
frequency(arr, size);
return 0;
}
If we run the above code it will generate the following output −
frequency of 1 is: 2
frequency of 2 is: 2
frequency of 3 is: 2
Live Demo
#include <bits/stdc++.h>
using namespace std;
void frequency(int arr[], int size){
unordered_map<int, int< um;
for (int i = 0; i < size; i++){
um[arr[i]]++;
}
for (auto x : um){
cout<<"frequency of "<<x.first<<" is: "<< x.second<< endl;
}
}
int main(){
int arr[] = {1, 2, 3, 1, 2, 3 };
int size = sizeof(arr) / sizeof(arr[0]);
frequency(arr, size);
return 0;
}
If we run the above code it will generate the following output −
frequency of 3 is: 2
frequency of 1 is: 2
frequency of 2 is: 2
|
[
{
"code": null,
"e": 1248,
"s": 1062,
"text": "We are given an array of integer elements which contains duplicate values and the task is to calculate the frequencies of the distinct elements present in an array and print the result."
},
{
"code": null,
"e": 1293,
"s": 1248,
"text": "Input − int arr[] = {1, 1, 2, 3, 4, 1, 2, 3}"
},
{
"code": null,
"e": 1302,
"s": 1293,
"text": "Output −"
},
{
"code": null,
"e": 1386,
"s": 1302,
"text": "frequency of 1 is: 3\nfrequency of 2 is: 2\nfrequency of 3 is: 2\nFrequency of 4 is: 1"
},
{
"code": null,
"e": 1422,
"s": 1386,
"text": "Input − int arr[] = {2, 3, 4, 1, 5}"
},
{
"code": null,
"e": 1431,
"s": 1422,
"text": "Output −"
},
{
"code": null,
"e": 1536,
"s": 1431,
"text": "frequency of 1 is: 1\nfrequency of 2 is: 1\nfrequency of 3 is: 1\nFrequency of 4 is: 1\nFrequency of 5 is: 1"
},
{
"code": null,
"e": 1710,
"s": 1536,
"text": "There can be multiple solutions for this and those can be simpler in coding terms or simpler in complexity terms. So let’s first look at the simpler approach in coding terms"
},
{
"code": null,
"e": 1752,
"s": 1710,
"text": "Create an array of integer type variables"
},
{
"code": null,
"e": 1794,
"s": 1752,
"text": "Create an array of integer type variables"
},
{
"code": null,
"e": 1848,
"s": 1794,
"text": "Calculate the size of an array using size() function."
},
{
"code": null,
"e": 1902,
"s": 1848,
"text": "Calculate the size of an array using size() function."
},
{
"code": null,
"e": 1956,
"s": 1902,
"text": "Create a boolean array let’s say, check of array size"
},
{
"code": null,
"e": 2010,
"s": 1956,
"text": "Create a boolean array let’s say, check of array size"
},
{
"code": null,
"e": 2058,
"s": 2010,
"text": "Start loop FOR from i to 0 and i less than size"
},
{
"code": null,
"e": 2106,
"s": 2058,
"text": "Start loop FOR from i to 0 and i less than size"
},
{
"code": null,
"e": 2140,
"s": 2106,
"text": "Inside the loop, set check[i] = 0"
},
{
"code": null,
"e": 2174,
"s": 2140,
"text": "Inside the loop, set check[i] = 0"
},
{
"code": null,
"e": 2222,
"s": 2174,
"text": "Start loop FOR from i to 0 and i less than size"
},
{
"code": null,
"e": 2270,
"s": 2222,
"text": "Start loop FOR from i to 0 and i less than size"
},
{
"code": null,
"e": 2323,
"s": 2270,
"text": "Inside the loop, check IF check[i] = 1 then continue"
},
{
"code": null,
"e": 2376,
"s": 2323,
"text": "Inside the loop, check IF check[i] = 1 then continue"
},
{
"code": null,
"e": 2460,
"s": 2376,
"text": "Declare variable count and initialise it with 1 that will print the frequency count"
},
{
"code": null,
"e": 2544,
"s": 2460,
"text": "Declare variable count and initialise it with 1 that will print the frequency count"
},
{
"code": null,
"e": 2584,
"s": 2544,
"text": "Start loop FOR j from i+1 till the size"
},
{
"code": null,
"e": 2624,
"s": 2584,
"text": "Start loop FOR j from i+1 till the size"
},
{
"code": null,
"e": 2718,
"s": 2624,
"text": "Inside the loop, check if arr[i] = arr[j] then set check[j] to 1 and increment the count by 1"
},
{
"code": null,
"e": 2812,
"s": 2718,
"text": "Inside the loop, check if arr[i] = arr[j] then set check[j] to 1 and increment the count by 1"
},
{
"code": null,
"e": 2838,
"s": 2812,
"text": "Print the value of count."
},
{
"code": null,
"e": 2864,
"s": 2838,
"text": "Print the value of count."
},
{
"code": null,
"e": 2896,
"s": 2864,
"text": "Another solution of it can be −"
},
{
"code": null,
"e": 2938,
"s": 2896,
"text": "Create an array of integer type variables"
},
{
"code": null,
"e": 2980,
"s": 2938,
"text": "Create an array of integer type variables"
},
{
"code": null,
"e": 3034,
"s": 2980,
"text": "Calculate the size of an array using size() function."
},
{
"code": null,
"e": 3088,
"s": 3034,
"text": "Calculate the size of an array using size() function."
},
{
"code": null,
"e": 3141,
"s": 3088,
"text": "Create a variable of type unordered_map let’s say um"
},
{
"code": null,
"e": 3194,
"s": 3141,
"text": "Create a variable of type unordered_map let’s say um"
},
{
"code": null,
"e": 3235,
"s": 3194,
"text": "Start loop FOR from i to 0 and till size"
},
{
"code": null,
"e": 3276,
"s": 3235,
"text": "Start loop FOR from i to 0 and till size"
},
{
"code": null,
"e": 3310,
"s": 3276,
"text": "Inside the loop, set um[arr[i]]++"
},
{
"code": null,
"e": 3344,
"s": 3310,
"text": "Inside the loop, set um[arr[i]]++"
},
{
"code": null,
"e": 3387,
"s": 3344,
"text": "Start another loop for from auto x till um"
},
{
"code": null,
"e": 3430,
"s": 3387,
"text": "Start another loop for from auto x till um"
},
{
"code": null,
"e": 3468,
"s": 3430,
"text": "Inside the loop, print the frequency."
},
{
"code": null,
"e": 3506,
"s": 3468,
"text": "Inside the loop, print the frequency."
},
{
"code": null,
"e": 3517,
"s": 3506,
"text": " Live Demo"
},
{
"code": null,
"e": 4193,
"s": 3517,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint frequency(int arr[], int size){\n bool check[size];\n for(int i=0;i<size;i++){\n check[i] = 0;\n }\n for(int i=0; i<size; i++){\n if(check[i]== 1){\n continue;\n }\n int count = 1;\n for(int j = i+1; j<size; j++){\n if (arr[i] == arr[j]){\n check[j] = 1;\n count++;\n }\n }\n cout<<\"frequency of \"<<arr[i]<<\" is: \" << count << endl;\n }\n}\nint main(){\n int arr[] = {1, 2, 3, 1, 2, 3};\n //calculate the size of an array\n int size = sizeof(arr) / sizeof(arr[0]);\n //call function to calculate the frequency\n frequency(arr, size);\n return 0;\n}"
},
{
"code": null,
"e": 4258,
"s": 4193,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4321,
"s": 4258,
"text": "frequency of 1 is: 2\nfrequency of 2 is: 2\nfrequency of 3 is: 2"
},
{
"code": null,
"e": 4332,
"s": 4321,
"text": " Live Demo"
},
{
"code": null,
"e": 4732,
"s": 4332,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid frequency(int arr[], int size){\n unordered_map<int, int< um;\n for (int i = 0; i < size; i++){\n um[arr[i]]++;\n }\n for (auto x : um){\n cout<<\"frequency of \"<<x.first<<\" is: \"<< x.second<< endl;\n }\n}\nint main(){\n int arr[] = {1, 2, 3, 1, 2, 3 };\n int size = sizeof(arr) / sizeof(arr[0]);\n frequency(arr, size);\n return 0;\n}"
},
{
"code": null,
"e": 4797,
"s": 4732,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4860,
"s": 4797,
"text": "frequency of 3 is: 2\nfrequency of 1 is: 2\nfrequency of 2 is: 2"
}
] |
What is the data type for unix_timestamp in MySQL?
|
The best data type for unix_timestamp in MySQL is integer. The integer data type is as follows
int(11);
The integer data type is useful for condition checking like ( > ,<= ) and indexing. The return type of unix_timestamp is an integer.
However, let us see what we get as UNIX Timestamp, when we convert datetime to timestamp.
To understand the above concept, let us first create a table. The query to create a table is as follows
mysql> create table UnixTime
-> (
-> DueTime datetime
-> );
Query OK, 0 rows affected (0.55 sec)
Insert records in the form of date using insert command. The query is as follows
mysql> insert into UnixTime values(now());
Query OK, 1 row affected (0.15 sec)
mysql> insert into UnixTime values('2010-10-14');
Query OK, 1 row affected (0.15 sec)
mysql> insert into UnixTime values('2020-09-24');
Query OK, 1 row affected (0.15 sec)
Let us now display all records from the table using select command. The query is as follows
mysql> select *from UnixTime;
The following is the output
+---------------------+
| DueTime |
+---------------------+
| 2018-12-19 10:07:11 |
| 2010-10-14 00:00:00 |
| 2020-09-24 00:00:00 |
+---------------------+
3 rows in set (0.00 sec)
Let us see the query to convert datetime to UNIX timestamp
mysql> select unix_timestamp(DueTime) as Output from UnixTime;
The following is the output
+------------+
| Output |
+------------+
| 1545194231 |
| 1286994600 |
| 1600885800 |
+------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "The best data type for unix_timestamp in MySQL is integer. The integer data type is as follows"
},
{
"code": null,
"e": 1166,
"s": 1157,
"text": "int(11);"
},
{
"code": null,
"e": 1299,
"s": 1166,
"text": "The integer data type is useful for condition checking like ( > ,<= ) and indexing. The return type of unix_timestamp is an integer."
},
{
"code": null,
"e": 1389,
"s": 1299,
"text": "However, let us see what we get as UNIX Timestamp, when we convert datetime to timestamp."
},
{
"code": null,
"e": 1493,
"s": 1389,
"text": "To understand the above concept, let us first create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1599,
"s": 1493,
"text": "mysql> create table UnixTime\n -> (\n -> DueTime datetime\n -> );\nQuery OK, 0 rows affected (0.55 sec)"
},
{
"code": null,
"e": 1680,
"s": 1599,
"text": "Insert records in the form of date using insert command. The query is as follows"
},
{
"code": null,
"e": 1933,
"s": 1680,
"text": "mysql> insert into UnixTime values(now());\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into UnixTime values('2010-10-14');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into UnixTime values('2020-09-24');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2025,
"s": 1933,
"text": "Let us now display all records from the table using select command. The query is as follows"
},
{
"code": null,
"e": 2055,
"s": 2025,
"text": "mysql> select *from UnixTime;"
},
{
"code": null,
"e": 2083,
"s": 2055,
"text": "The following is the output"
},
{
"code": null,
"e": 2276,
"s": 2083,
"text": "+---------------------+\n| DueTime |\n+---------------------+\n| 2018-12-19 10:07:11 |\n| 2010-10-14 00:00:00 |\n| 2020-09-24 00:00:00 |\n+---------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2335,
"s": 2276,
"text": "Let us see the query to convert datetime to UNIX timestamp"
},
{
"code": null,
"e": 2398,
"s": 2335,
"text": "mysql> select unix_timestamp(DueTime) as Output from UnixTime;"
},
{
"code": null,
"e": 2426,
"s": 2398,
"text": "The following is the output"
},
{
"code": null,
"e": 2556,
"s": 2426,
"text": "+------------+\n| Output |\n+------------+\n| 1545194231 |\n| 1286994600 |\n| 1600885800 |\n+------------+\n3 rows in set (0.00 sec)"
}
] |
Sort Characters By Frequency in C++
|
Suppose we have a string, we have to sort the characters based on the frequency. So if the string is like “abbbacbcc”, then the output will be “bbbbcccaa”
To solve this, we will follow these steps −
create an array of pairs called v, create one map m
for all characters in string,increase value of m[character] by 1
increase value of m[character] by 1
i := first element of map
while map has elementsinsert (i.second, i.first) into vand increase i to point to the next element
insert (i.second, i.first) into v
and increase i to point to the next element
sort the vector v
ans := an empty string
for i := 0 to size of vt := first element of v[i]while t is not 0ans := ans + second part of v[i]decrease t by 1
t := first element of v[i]
while t is not 0ans := ans + second part of v[i]decrease t by 1
ans := ans + second part of v[i]
decrease t by 1
return ans
Let us see the following implementation to get a better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
static bool cmp(pair <int, char> a, pair <int, char> b){
return a.first < b.first;
}
string frequencySort(string s) {
vector < pair <int, char> > v;
map <char, int> m;
for(int i = 0; i < s.size(); i++){
m[s[i]]++;
}
map <char, int> :: iterator i = m.begin();
while(i != m.end()){
v.push_back({i->second, i->first});
i++;
}
sort(v.rbegin(), v.rend(), cmp);
string ans = "";
for(int i = 0; i < v.size(); i++){
int t = v[i].first;
while(t--)ans += v[i].second;
}
return ans;
}
};
main(){
Solution ob;
cout << ob.frequencySort("abbbacbcc");
}
"abbbacbcc"
bbbbcccaa
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "Suppose we have a string, we have to sort the characters based on the frequency. So if the string is like “abbbacbcc”, then the output will be “bbbbcccaa”"
},
{
"code": null,
"e": 1261,
"s": 1217,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1313,
"s": 1261,
"text": "create an array of pairs called v, create one map m"
},
{
"code": null,
"e": 1378,
"s": 1313,
"text": "for all characters in string,increase value of m[character] by 1"
},
{
"code": null,
"e": 1414,
"s": 1378,
"text": "increase value of m[character] by 1"
},
{
"code": null,
"e": 1440,
"s": 1414,
"text": "i := first element of map"
},
{
"code": null,
"e": 1539,
"s": 1440,
"text": "while map has elementsinsert (i.second, i.first) into vand increase i to point to the next element"
},
{
"code": null,
"e": 1573,
"s": 1539,
"text": "insert (i.second, i.first) into v"
},
{
"code": null,
"e": 1617,
"s": 1573,
"text": "and increase i to point to the next element"
},
{
"code": null,
"e": 1635,
"s": 1617,
"text": "sort the vector v"
},
{
"code": null,
"e": 1658,
"s": 1635,
"text": "ans := an empty string"
},
{
"code": null,
"e": 1771,
"s": 1658,
"text": "for i := 0 to size of vt := first element of v[i]while t is not 0ans := ans + second part of v[i]decrease t by 1"
},
{
"code": null,
"e": 1798,
"s": 1771,
"text": "t := first element of v[i]"
},
{
"code": null,
"e": 1862,
"s": 1798,
"text": "while t is not 0ans := ans + second part of v[i]decrease t by 1"
},
{
"code": null,
"e": 1895,
"s": 1862,
"text": "ans := ans + second part of v[i]"
},
{
"code": null,
"e": 1911,
"s": 1895,
"text": "decrease t by 1"
},
{
"code": null,
"e": 1922,
"s": 1911,
"text": "return ans"
},
{
"code": null,
"e": 1994,
"s": 1922,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2005,
"s": 1994,
"text": " Live Demo"
},
{
"code": null,
"e": 2756,
"s": 2005,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n static bool cmp(pair <int, char> a, pair <int, char> b){\n return a.first < b.first;\n }\n string frequencySort(string s) {\n vector < pair <int, char> > v;\n map <char, int> m;\n for(int i = 0; i < s.size(); i++){\n m[s[i]]++;\n }\n map <char, int> :: iterator i = m.begin();\n while(i != m.end()){\n v.push_back({i->second, i->first});\n i++;\n }\n sort(v.rbegin(), v.rend(), cmp);\n string ans = \"\";\n for(int i = 0; i < v.size(); i++){\n int t = v[i].first;\n while(t--)ans += v[i].second;\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n cout << ob.frequencySort(\"abbbacbcc\");\n}"
},
{
"code": null,
"e": 2768,
"s": 2756,
"text": "\"abbbacbcc\""
},
{
"code": null,
"e": 2778,
"s": 2768,
"text": "bbbbcccaa"
}
] |
jQuery - removeAttr( name ) Method
|
The removeAttr( name ) method removes an attribute from each of the matched elements.
Here is the simple syntax to use this method
selector.removeAttr( name )
Here is the description of all the parameters used by this method −
name − The name of the property to be removed.
name − The name of the property to be removed.
Following example would remove border from each table −
<html>
<head>
<title>The Selecter Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("table").removeAttr("border");
});
</script>
</head>
<body>
<table border = "2">
<tr><td>This is first table</td></tr>
</table>
<table border = "3">
<tr><td>This is second table</td></tr>
</table>
<table border = "4">
<tr><td>This is third table</td></tr>
</table>
</body>
</html>
This will produce following result −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2408,
"s": 2322,
"text": "The removeAttr( name ) method removes an attribute from each of the matched elements."
},
{
"code": null,
"e": 2453,
"s": 2408,
"text": "Here is the simple syntax to use this method"
},
{
"code": null,
"e": 2482,
"s": 2453,
"text": "selector.removeAttr( name )\n"
},
{
"code": null,
"e": 2550,
"s": 2482,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2597,
"s": 2550,
"text": "name − The name of the property to be removed."
},
{
"code": null,
"e": 2644,
"s": 2597,
"text": "name − The name of the property to be removed."
},
{
"code": null,
"e": 2700,
"s": 2644,
"text": "Following example would remove border from each table −"
},
{
"code": null,
"e": 3393,
"s": 2700,
"text": "<html>\n <head>\n <title>The Selecter Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"table\").removeAttr(\"border\");\n });\n </script>\n </head>\n\t\n <body>\n <table border = \"2\">\n <tr><td>This is first table</td></tr>\n </table>\n\n <table border = \"3\">\n <tr><td>This is second table</td></tr>\n </table>\n\n <table border = \"4\">\n <tr><td>This is third table</td></tr>\n </table>\t\n </body>\n</html>"
},
{
"code": null,
"e": 3430,
"s": 3393,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3463,
"s": 3430,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3477,
"s": 3463,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 3512,
"s": 3477,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3526,
"s": 3512,
"text": " Pratik Singh"
},
{
"code": null,
"e": 3561,
"s": 3526,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3578,
"s": 3561,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3611,
"s": 3578,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3639,
"s": 3611,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3672,
"s": 3639,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3693,
"s": 3672,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 3725,
"s": 3693,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 3742,
"s": 3725,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 3749,
"s": 3742,
"text": " Print"
},
{
"code": null,
"e": 3760,
"s": 3749,
"text": " Add Notes"
}
] |
Why can't variables be declared in a switch statement in C/C++?
|
Variables can be declared in a switch statement. You'll just need to declare them and use them within a new scope in the switch statement. For example,
#include<iostream>
using namespace std;
int main() {
int i = 10;
switch(i) {
case 2:
//some code
break;
case 10:{
int x = 13;
cout << x;
}
}
return 0;
}
This will give the output:
13
If you try to declare the variable out in the open you might get an error as Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable declaration while you're in the same scope as it and might be using it someplace further in that scope.
|
[
{
"code": null,
"e": 1214,
"s": 1062,
"text": "Variables can be declared in a switch statement. You'll just need to declare them and use them within a new scope in the switch statement. For example,"
},
{
"code": null,
"e": 1428,
"s": 1214,
"text": "#include<iostream>\nusing namespace std;\n\nint main() {\n int i = 10;\n switch(i) {\n case 2:\n //some code\n break;\n case 10:{\n int x = 13;\n cout << x;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 1455,
"s": 1428,
"text": "This will give the output:"
},
{
"code": null,
"e": 1458,
"s": 1455,
"text": "13"
},
{
"code": null,
"e": 1742,
"s": 1458,
"text": "If you try to declare the variable out in the open you might get an error as Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable declaration while you're in the same scope as it and might be using it someplace further in that scope."
}
] |
Display the collapsible content by default with Bootstrap
|
Use the ‘collapse in’ class in Bootstrap to show collapsible content by default −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h2>More Quizzes</h2>
<a href = "#test" class = "btn btn-info" data-toggle = "collapse">More</a>
<div id = "test" class = "collapse in">
We have quizzes on Java, PHP, Ruby, C, C++, etc. as well.
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Use the ‘collapse in’ class in Bootstrap to show collapsible content by default −"
},
{
"code": null,
"e": 1154,
"s": 1144,
"text": "Live Demo"
},
{
"code": null,
"e": 1753,
"s": 1154,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>More Quizzes</h2>\n <a href = \"#test\" class = \"btn btn-info\" data-toggle = \"collapse\">More</a>\n <div id = \"test\" class = \"collapse in\">\n We have quizzes on Java, PHP, Ruby, C, C++, etc. as well.\n </div>\n </div>\n </body>\n</html>"
}
] |
Pascal - Memory Management
|
This chapter explains dynamic memory management in Pascal. Pascal programming language provides several functions for memory allocation and management.
While doing programming, if you are aware about the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go max 100 characters so you can define something as follows −
var
name: array[1..100] of char;
But now, let us consider a situation, where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here, we need to define a pointer to string without defining how much memory is required.
Pascal provides a procedure newto create pointer variables.
program exMemory;
var
name: array[1..100] of char;
description: ^string;
begin
name:= 'Zara Ali';
new(description);
if not assigned(description) then
writeln(' Error - unable to allocate required memory')
else
description^ := 'Zara ali a DPS student in class 10th';
writeln('Name = ', name );
writeln('Description: ', description^ );
end.
When the above code is compiled and executed, it produces the following result −
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
Now, if you need to define a pointer with specific number of bytes to be referred by it later, you should use the getmem function or the getmem procedure, which has the following syntax −
procedure Getmem(
out p: pointer;
Size: PtrUInt
);
function GetMem(
size: PtrUInt
):pointer;
In the previous example, we declared a pointer to a string. A string has a maximum value of 255 bytes. If you really don't need that much space, or a larger space, in terms of bytes, getmem subprogram allows specifying that. Let us rewrite the previous example, using getmem −
program exMemory;
var
name: array[1..100] of char;
description: ^string;
begin
name:= 'Zara Ali';
description := getmem(200);
if not assigned(description) then
writeln(' Error - unable to allocate required memory')
else
description^ := 'Zara ali a DPS student in class 10th';
writeln('Name = ', name );
writeln('Description: ', description^ );
freemem(description);
end.
When the above code is compiled and executed, it produces the following result −
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
So, you have complete control and you can pass any size value while allocating memory unlike arrays, where once you defined the size cannot be changed.
When your program comes out, operating system automatically releases all the memory allocated by your program, but as a good practice when you are not in need of memory anymore, then you should release that memory.
Pascal provides the procedure dispose to free a dynamically created variable using the procedure new. If you have allocated memory using the getmem subprogram, then you need to use the subprogram freemem to free this memory. The freemem subprograms have the following syntax −
procedure Freemem(
p: pointer;
Size: PtrUInt
);
function Freemem(
p: pointer
):PtrUInt;
Alternatively, you can increase or decrease the size of an allocated memory block by calling the function ReAllocMem. Let us check the above program once again and make use of ReAllocMem and freemem subprograms. Following is the syntax for ReAllocMem −
function ReAllocMem(
var p: pointer;
Size: PtrUInt
):pointer;
Following is an example which makes use of ReAllocMem and freemem subprograms −
program exMemory;
var
name: array[1..100] of char;
description: ^string;
desp: string;
begin
name:= 'Zara Ali';
desp := 'Zara ali a DPS student.';
description := getmem(30);
if not assigned(description) then
writeln('Error - unable to allocate required memory')
else
description^ := desp;
(* Suppose you want to store bigger description *)
description := reallocmem(description, 100);
desp := desp + ' She is in class 10th.';
description^:= desp;
writeln('Name = ', name );
writeln('Description: ', description^ );
freemem(description);
end.
When the above code is compiled and executed, it produces the following result −
Name = Zara Ali
Description: Zara ali a DPS student. She is in class 10th
Pascal provides a hoard of memory management functions that is used in implementing various data structures and implementing low-level programming in Pascal. Many of these functions are implementation dependent. Free Pascal provides the following functions and procedures for memory management −
function Addr(X: TAnytype):Pointer;
Returns address of variable
function Assigned(P: Pointer):Boolean;
Checks if a pointer is valid
function CompareByte(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
function CompareChar(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
function CompareDWord(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
function CompareWord(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
function Cseg: Word;
Returns code segment
procedure Dispose(P: Pointer);
Frees dynamically allocated memory
procedure Dispose(P: TypedPointer; Des: TProcedure);
Frees dynamically allocated memory
function Dseg: Word;
Returns data segment
procedure FillByte(var x; count: SizeInt; value: Byte);
Fills memory region with 8-bit pattern
procedure FillChar( var x; count: SizeInt; Value: Byte|Boolean|Char);
Fills memory region with certain character
procedure FillDWord( var x; count: SizeInt; value: DWord);
Fills memory region with 32-bit pattern
procedure FillQWord( var x; count: SizeInt; value: QWord);
Fills memory region with 64-bit pattern
Fills memory region with 16-bit pattern
procedure Freemem( p: pointer; Size: PtrUInt);
Releases allocated memory
procedure Freemem( p: pointer );
Releases allocated memory
procedure Getmem( out p: pointer; Size: PtrUInt);
Allocates new memory
procedure Getmem( out p: pointer);
Allocates new memory
procedure GetMemoryManager( var MemMgr: TMemoryManager);
Returns current memory manager
function High( Arg: TypeOrVariable):TOrdinal;
Returns highest index of open array or enumerated
function IndexByte( const buf; len: SizeInt; b: Byte):SizeInt;
Finds byte-sized value in a memory range
function IndexChar( const buf; len: SizeInt; b: Char):SizeInt;
Finds char-sized value in a memory range
function IndexDWord( const buf; len: SizeInt; b: DWord):SizeInt;
Finds DWord-sized (32-bit) value in a memory range
function IndexQWord( const buf; len: SizeInt; b: QWord):SizeInt;
Finds QWord-sized value in a memory range
function Indexword( const buf; len: SizeInt; b: Word):SizeInt;
Finds word-sized value in a memory range
function IsMemoryManagerSet: Boolean;
Is the memory manager set
function Low( Arg: TypeOrVariable ):TOrdinal;
Returns lowest index of open array or enumerated
procedure Move( const source; var dest; count: SizeInt );
Moves data from one location in memory to another
procedure MoveChar0( const buf1; var buf2; len: SizeInt);
Moves data till first zero character
procedure New( var P: Pointer);
Dynamically allocate memory for variable
procedure New( var P: Pointer; Cons: TProcedure);
Dynamically allocates memory for variable
function Ofs( var X ):LongInt;
Returns offset of variable
function ptr( sel: LongInt; off: LongInt):farpointer;
Combines segment and offset to pointer
function ReAllocMem( var p: pointer; Size: PtrUInt):pointer;
Resizes a memory block on the heap
function Seg( var X):LongInt;
Returns segment
procedure SetMemoryManager( const MemMgr: TMemoryManager );
Sets a memory manager
function Sptr: Pointer;
Returns current stack pointer
function Sseg: Word;
Returns stack segment register value
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2235,
"s": 2083,
"text": "This chapter explains dynamic memory management in Pascal. Pascal programming language provides several functions for memory allocation and management."
},
{
"code": null,
"e": 2470,
"s": 2235,
"text": "While doing programming, if you are aware about the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go max 100 characters so you can define something as follows −"
},
{
"code": null,
"e": 2503,
"s": 2470,
"text": "var\nname: array[1..100] of char;"
},
{
"code": null,
"e": 2772,
"s": 2503,
"text": "But now, let us consider a situation, where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here, we need to define a pointer to string without defining how much memory is required."
},
{
"code": null,
"e": 2832,
"s": 2772,
"text": "Pascal provides a procedure newto create pointer variables."
},
{
"code": null,
"e": 3218,
"s": 2832,
"text": "program exMemory;\nvar\nname: array[1..100] of char;\ndescription: ^string;\n\nbegin\n name:= 'Zara Ali';\n \n new(description);\n if not assigned(description) then\n writeln(' Error - unable to allocate required memory')\n else\n description^ := 'Zara ali a DPS student in class 10th';\n writeln('Name = ', name );\n writeln('Description: ', description^ );\nend."
},
{
"code": null,
"e": 3299,
"s": 3218,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3366,
"s": 3299,
"text": "Name = Zara Ali\nDescription: Zara ali a DPS student in class 10th\n"
},
{
"code": null,
"e": 3554,
"s": 3366,
"text": "Now, if you need to define a pointer with specific number of bytes to be referred by it later, you should use the getmem function or the getmem procedure, which has the following syntax −"
},
{
"code": null,
"e": 3657,
"s": 3554,
"text": "procedure Getmem(\n out p: pointer;\n Size: PtrUInt\n);\n\nfunction GetMem(\n size: PtrUInt\n):pointer;"
},
{
"code": null,
"e": 3934,
"s": 3657,
"text": "In the previous example, we declared a pointer to a string. A string has a maximum value of 255 bytes. If you really don't need that much space, or a larger space, in terms of bytes, getmem subprogram allows specifying that. Let us rewrite the previous example, using getmem −"
},
{
"code": null,
"e": 4359,
"s": 3934,
"text": "program exMemory;\nvar\nname: array[1..100] of char;\ndescription: ^string;\n\nbegin\n name:= 'Zara Ali';\n \n description := getmem(200);\n if not assigned(description) then\n writeln(' Error - unable to allocate required memory')\n else\n description^ := 'Zara ali a DPS student in class 10th';\n writeln('Name = ', name );\n writeln('Description: ', description^ );\n \n freemem(description);\nend."
},
{
"code": null,
"e": 4440,
"s": 4359,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4507,
"s": 4440,
"text": "Name = Zara Ali\nDescription: Zara ali a DPS student in class 10th\n"
},
{
"code": null,
"e": 4659,
"s": 4507,
"text": "So, you have complete control and you can pass any size value while allocating memory unlike arrays, where once you defined the size cannot be changed."
},
{
"code": null,
"e": 4874,
"s": 4659,
"text": "When your program comes out, operating system automatically releases all the memory allocated by your program, but as a good practice when you are not in need of memory anymore, then you should release that memory."
},
{
"code": null,
"e": 5151,
"s": 4874,
"text": "Pascal provides the procedure dispose to free a dynamically created variable using the procedure new. If you have allocated memory using the getmem subprogram, then you need to use the subprogram freemem to free this memory. The freemem subprograms have the following syntax −"
},
{
"code": null,
"e": 5248,
"s": 5151,
"text": "procedure Freemem(\n p: pointer;\n Size: PtrUInt\n);\n\nfunction Freemem(\n p: pointer\n):PtrUInt;"
},
{
"code": null,
"e": 5501,
"s": 5248,
"text": "Alternatively, you can increase or decrease the size of an allocated memory block by calling the function ReAllocMem. Let us check the above program once again and make use of ReAllocMem and freemem subprograms. Following is the syntax for ReAllocMem −"
},
{
"code": null,
"e": 5572,
"s": 5501,
"text": "function ReAllocMem(\n var p: pointer;\n Size: PtrUInt\n):pointer; "
},
{
"code": null,
"e": 5652,
"s": 5572,
"text": "Following is an example which makes use of ReAllocMem and freemem subprograms −"
},
{
"code": null,
"e": 6269,
"s": 5652,
"text": "program exMemory;\nvar\nname: array[1..100] of char;\ndescription: ^string;\ndesp: string;\n\nbegin\n name:= 'Zara Ali';\n desp := 'Zara ali a DPS student.';\n \n description := getmem(30);\n if not assigned(description) then\n writeln('Error - unable to allocate required memory')\n else\n description^ := desp;\n\n (* Suppose you want to store bigger description *)\n description := reallocmem(description, 100);\n desp := desp + ' She is in class 10th.';\n description^:= desp; \n \n writeln('Name = ', name );\n writeln('Description: ', description^ );\n \n freemem(description);\nend."
},
{
"code": null,
"e": 6350,
"s": 6269,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6425,
"s": 6350,
"text": "Name = Zara Ali\nDescription: Zara ali a DPS student. She is in class 10th\n"
},
{
"code": null,
"e": 6721,
"s": 6425,
"text": "Pascal provides a hoard of memory management functions that is used in implementing various data structures and implementing low-level programming in Pascal. Many of these functions are implementation dependent. Free Pascal provides the following functions and procedures for memory management −"
},
{
"code": null,
"e": 6757,
"s": 6721,
"text": "function Addr(X: TAnytype):Pointer;"
},
{
"code": null,
"e": 6785,
"s": 6757,
"text": "Returns address of variable"
},
{
"code": null,
"e": 6824,
"s": 6785,
"text": "function Assigned(P: Pointer):Boolean;"
},
{
"code": null,
"e": 6853,
"s": 6824,
"text": "Checks if a pointer is valid"
},
{
"code": null,
"e": 6921,
"s": 6853,
"text": "function CompareByte(const buf1; const buf2; len: SizeInt):SizeInt;"
},
{
"code": null,
"e": 6961,
"s": 6921,
"text": "Compares 2 memory buffers byte per byte"
},
{
"code": null,
"e": 7029,
"s": 6961,
"text": "function CompareChar(const buf1; const buf2; len: SizeInt):SizeInt;"
},
{
"code": null,
"e": 7069,
"s": 7029,
"text": "Compares 2 memory buffers byte per byte"
},
{
"code": null,
"e": 7138,
"s": 7069,
"text": "function CompareDWord(const buf1; const buf2; len: SizeInt):SizeInt;"
},
{
"code": null,
"e": 7178,
"s": 7138,
"text": "Compares 2 memory buffers byte per byte"
},
{
"code": null,
"e": 7246,
"s": 7178,
"text": "function CompareWord(const buf1; const buf2; len: SizeInt):SizeInt;"
},
{
"code": null,
"e": 7286,
"s": 7246,
"text": "Compares 2 memory buffers byte per byte"
},
{
"code": null,
"e": 7307,
"s": 7286,
"text": "function Cseg: Word;"
},
{
"code": null,
"e": 7328,
"s": 7307,
"text": "Returns code segment"
},
{
"code": null,
"e": 7359,
"s": 7328,
"text": "procedure Dispose(P: Pointer);"
},
{
"code": null,
"e": 7394,
"s": 7359,
"text": "Frees dynamically allocated memory"
},
{
"code": null,
"e": 7447,
"s": 7394,
"text": "procedure Dispose(P: TypedPointer; Des: TProcedure);"
},
{
"code": null,
"e": 7482,
"s": 7447,
"text": "Frees dynamically allocated memory"
},
{
"code": null,
"e": 7503,
"s": 7482,
"text": "function Dseg: Word;"
},
{
"code": null,
"e": 7524,
"s": 7503,
"text": "Returns data segment"
},
{
"code": null,
"e": 7581,
"s": 7524,
"text": "procedure FillByte(var x; count: SizeInt; value: Byte);"
},
{
"code": null,
"e": 7620,
"s": 7581,
"text": "Fills memory region with 8-bit pattern"
},
{
"code": null,
"e": 7692,
"s": 7620,
"text": "procedure FillChar( var x; count: SizeInt; Value: Byte|Boolean|Char);"
},
{
"code": null,
"e": 7735,
"s": 7692,
"text": "Fills memory region with certain character"
},
{
"code": null,
"e": 7794,
"s": 7735,
"text": "procedure FillDWord( var x; count: SizeInt; value: DWord);"
},
{
"code": null,
"e": 7834,
"s": 7794,
"text": "Fills memory region with 32-bit pattern"
},
{
"code": null,
"e": 7895,
"s": 7834,
"text": "procedure FillQWord( var x; count: SizeInt; value: QWord);"
},
{
"code": null,
"e": 7935,
"s": 7895,
"text": "Fills memory region with 64-bit pattern"
},
{
"code": null,
"e": 7975,
"s": 7935,
"text": "Fills memory region with 16-bit pattern"
},
{
"code": null,
"e": 8024,
"s": 7975,
"text": "procedure Freemem( p: pointer; Size: PtrUInt);"
},
{
"code": null,
"e": 8050,
"s": 8024,
"text": "Releases allocated memory"
},
{
"code": null,
"e": 8084,
"s": 8050,
"text": "procedure Freemem( p: pointer );"
},
{
"code": null,
"e": 8110,
"s": 8084,
"text": "Releases allocated memory"
},
{
"code": null,
"e": 8160,
"s": 8110,
"text": "procedure Getmem( out p: pointer; Size: PtrUInt);"
},
{
"code": null,
"e": 8181,
"s": 8160,
"text": "Allocates new memory"
},
{
"code": null,
"e": 8216,
"s": 8181,
"text": "procedure Getmem( out p: pointer);"
},
{
"code": null,
"e": 8237,
"s": 8216,
"text": "Allocates new memory"
},
{
"code": null,
"e": 8295,
"s": 8237,
"text": "procedure GetMemoryManager( var MemMgr: TMemoryManager);"
},
{
"code": null,
"e": 8326,
"s": 8295,
"text": "Returns current memory manager"
},
{
"code": null,
"e": 8373,
"s": 8326,
"text": "function High( Arg: TypeOrVariable):TOrdinal;"
},
{
"code": null,
"e": 8423,
"s": 8373,
"text": "Returns highest index of open array or enumerated"
},
{
"code": null,
"e": 8489,
"s": 8423,
"text": "function IndexByte( const buf; len: SizeInt; b: Byte):SizeInt;"
},
{
"code": null,
"e": 8530,
"s": 8489,
"text": "Finds byte-sized value in a memory range"
},
{
"code": null,
"e": 8596,
"s": 8530,
"text": "function IndexChar( const buf; len: SizeInt; b: Char):SizeInt;"
},
{
"code": null,
"e": 8637,
"s": 8596,
"text": "Finds char-sized value in a memory range"
},
{
"code": null,
"e": 8705,
"s": 8637,
"text": "function IndexDWord( const buf; len: SizeInt; b: DWord):SizeInt;"
},
{
"code": null,
"e": 8756,
"s": 8705,
"text": "Finds DWord-sized (32-bit) value in a memory range"
},
{
"code": null,
"e": 8824,
"s": 8756,
"text": "function IndexQWord( const buf; len: SizeInt; b: QWord):SizeInt;"
},
{
"code": null,
"e": 8866,
"s": 8824,
"text": "Finds QWord-sized value in a memory range"
},
{
"code": null,
"e": 8932,
"s": 8866,
"text": "function Indexword( const buf; len: SizeInt; b: Word):SizeInt;"
},
{
"code": null,
"e": 8973,
"s": 8932,
"text": "Finds word-sized value in a memory range"
},
{
"code": null,
"e": 9011,
"s": 8973,
"text": "function IsMemoryManagerSet: Boolean;"
},
{
"code": null,
"e": 9037,
"s": 9011,
"text": "Is the memory manager set"
},
{
"code": null,
"e": 9084,
"s": 9037,
"text": "function Low( Arg: TypeOrVariable ):TOrdinal;"
},
{
"code": null,
"e": 9133,
"s": 9084,
"text": "Returns lowest index of open array or enumerated"
},
{
"code": null,
"e": 9194,
"s": 9133,
"text": "procedure Move( const source; var dest; count: SizeInt );"
},
{
"code": null,
"e": 9244,
"s": 9194,
"text": "Moves data from one location in memory to another"
},
{
"code": null,
"e": 9305,
"s": 9244,
"text": "procedure MoveChar0( const buf1; var buf2; len: SizeInt);"
},
{
"code": null,
"e": 9342,
"s": 9305,
"text": "Moves data till first zero character"
},
{
"code": null,
"e": 9375,
"s": 9342,
"text": "procedure New( var P: Pointer);"
},
{
"code": null,
"e": 9416,
"s": 9375,
"text": "Dynamically allocate memory for variable"
},
{
"code": null,
"e": 9468,
"s": 9416,
"text": "procedure New( var P: Pointer; Cons: TProcedure);"
},
{
"code": null,
"e": 9510,
"s": 9468,
"text": "Dynamically allocates memory for variable"
},
{
"code": null,
"e": 9542,
"s": 9510,
"text": "function Ofs( var X ):LongInt;"
},
{
"code": null,
"e": 9569,
"s": 9542,
"text": "Returns offset of variable"
},
{
"code": null,
"e": 9625,
"s": 9569,
"text": "function ptr( sel: LongInt; off: LongInt):farpointer;"
},
{
"code": null,
"e": 9664,
"s": 9625,
"text": "Combines segment and offset to pointer"
},
{
"code": null,
"e": 9727,
"s": 9664,
"text": "function ReAllocMem( var p: pointer; Size: PtrUInt):pointer;"
},
{
"code": null,
"e": 9762,
"s": 9727,
"text": "Resizes a memory block on the heap"
},
{
"code": null,
"e": 9793,
"s": 9762,
"text": "function Seg( var X):LongInt;"
},
{
"code": null,
"e": 9809,
"s": 9793,
"text": "Returns segment"
},
{
"code": null,
"e": 9870,
"s": 9809,
"text": "procedure SetMemoryManager( const MemMgr: TMemoryManager );"
},
{
"code": null,
"e": 9892,
"s": 9870,
"text": "Sets a memory manager"
},
{
"code": null,
"e": 9916,
"s": 9892,
"text": "function Sptr: Pointer;"
},
{
"code": null,
"e": 9946,
"s": 9916,
"text": "Returns current stack pointer"
},
{
"code": null,
"e": 9967,
"s": 9946,
"text": "function Sseg: Word;"
},
{
"code": null,
"e": 10004,
"s": 9967,
"text": "Returns stack segment register value"
},
{
"code": null,
"e": 10039,
"s": 10004,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 10062,
"s": 10039,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 10069,
"s": 10062,
"text": " Print"
},
{
"code": null,
"e": 10080,
"s": 10069,
"text": " Add Notes"
}
] |
How to resize Image in Android App using Kotlin?
|
This example demonstrates how to resize Image in an Android App using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="500dp"
android:layout_centerHorizontal="true"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher_foreground" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ivImage"
android:layout_centerHorizontal="true">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:onClick="uploadImage"
android:text="Upload Image" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:onClick="resizeImage"
android:text="Resize Image" />
</LinearLayout>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import java.io.IOException
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
private val pickImage = 1
private lateinit var yourBitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.ivImage)
}
fun uploadImage(view: View) {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, pickImage)
}
fun resizeImage(view: View) {
val resized = Bitmap.createScaledBitmap(yourBitmap, 400, 400, true)
imageView.setImageBitmap(resized)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == pickImage && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return
}
try {
val imageUri: Uri? = data.data
yourBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, imageUri)
imageView.setImageBitmap(yourBitmap)
}
catch (e: IOException) {
e.printStackTrace()
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "This example demonstrates how to resize Image in an Android App using Kotlin."
},
{
"code": null,
"e": 1269,
"s": 1140,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1334,
"s": 1269,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2573,
"s": 1334,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/ivImage\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"500dp\"\n android:layout_centerHorizontal=\"true\"\n android:contentDescription=\"@string/app_name\"\n android:src=\"@drawable/ic_launcher_foreground\" />\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/ivImage\"\n android:layout_centerHorizontal=\"true\">\n <Button\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"8dp\"\n android:layout_weight=\"1\"\n android:onClick=\"uploadImage\"\n android:text=\"Upload Image\" />\n <Button\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"8dp\"\n android:layout_weight=\"1\"\n android:onClick=\"resizeImage\"\n android:text=\"Resize Image\" />\n </LinearLayout>\n</RelativeLayout>"
},
{
"code": null,
"e": 2628,
"s": 2573,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4233,
"s": 2628,
"text": "import android.app.Activity\nimport android.content.Intent\nimport android.graphics.Bitmap\nimport android.net.Uri\nimport android.os.Bundle\nimport android.provider.MediaStore\nimport android.view.View\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\nimport java.io.IOException\nclass MainActivity : AppCompatActivity() {\n lateinit var imageView: ImageView\n private val pickImage = 1\n private lateinit var yourBitmap: Bitmap\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n imageView = findViewById(R.id.ivImage)\n }\n fun uploadImage(view: View) {\n val intent = Intent(Intent.ACTION_GET_CONTENT)\n intent.type = \"image/*\"\n startActivityForResult(intent, pickImage)\n }\n fun resizeImage(view: View) {\n val resized = Bitmap.createScaledBitmap(yourBitmap, 400, 400, true)\n imageView.setImageBitmap(resized)\n }\n override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n super.onActivityResult(requestCode, resultCode, data)\n if (requestCode == pickImage && resultCode == Activity.RESULT_OK) {\n if (data == null) {\n //Display an error\n return\n }\n try {\n val imageUri: Uri? = data.data\n yourBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, imageUri)\n imageView.setImageBitmap(yourBitmap)\n }\n catch (e: IOException) {\n e.printStackTrace()\n }\n }\n }\n}"
},
{
"code": null,
"e": 4288,
"s": 4233,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4963,
"s": 4288,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>\n"
},
{
"code": null,
"e": 5312,
"s": 4963,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
JavaScript Array some() function
|
The some() method of JavaScript is used to check if any of the elements in an array fulfills the condition.
The syntax is as follows −
array.some(function(currentVal, index, arr), val)
Above, the parameters under function(), include currentVal – value of the current element, index – array index, whereas val the array object the current element fits
Let us now implement the some() method in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Ranking Points</h2>
<p>Is any point above 400...</p>
<button onclick="display()">Result</button>
<p id="demo"></p>
<script>
var pointsArr = [50, 100, 200, 300, 400, 500, 600];
function pointsFunc(points) {
return points > 400;
}
function display() {
document.getElementById("demo").innerHTML = pointsArr.some(pointsFunc);
}
</script>
</body></html>
Click the “Result” button −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Ranking Points</h2>
<p>Is any point equal to 550...</p>
<button onclick="display()">Result</button>
<p id="demo"></p>
<script>
var pointsArr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 1000];
function pointsFunc(points) {
return points == 550;
}
function display() {
document.getElementById("demo").innerHTML = pointsArr.some(pointsFunc);
}
</script>
</body></html>
Click the “Result” button −
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "The some() method of JavaScript is used to check if any of the elements in an array fulfills the condition."
},
{
"code": null,
"e": 1197,
"s": 1170,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1247,
"s": 1197,
"text": "array.some(function(currentVal, index, arr), val)"
},
{
"code": null,
"e": 1413,
"s": 1247,
"text": "Above, the parameters under function(), include currentVal – value of the current element, index – array index, whereas val the array object the current element fits"
},
{
"code": null,
"e": 1468,
"s": 1413,
"text": "Let us now implement the some() method in JavaScript −"
},
{
"code": null,
"e": 1479,
"s": 1468,
"text": " Live Demo"
},
{
"code": null,
"e": 1928,
"s": 1479,
"text": "<!DOCTYPE html>\n<html>\n<body>\n <h2>Ranking Points</h2>\n <p>Is any point above 400...</p>\n <button onclick=\"display()\">Result</button>\n <p id=\"demo\"></p>\n <script>\n var pointsArr = [50, 100, 200, 300, 400, 500, 600];\n function pointsFunc(points) {\n return points > 400;\n }\n function display() {\n document.getElementById(\"demo\").innerHTML = pointsArr.some(pointsFunc);\n }\n </script>\n</body></html>"
},
{
"code": null,
"e": 1956,
"s": 1928,
"text": "Click the “Result” button −"
},
{
"code": null,
"e": 1967,
"s": 1956,
"text": " Live Demo"
},
{
"code": null,
"e": 2428,
"s": 1967,
"text": "<!DOCTYPE html>\n<html>\n<body>\n <h2>Ranking Points</h2>\n <p>Is any point equal to 550...</p>\n <button onclick=\"display()\">Result</button>\n <p id=\"demo\"></p>\n <script>\n var pointsArr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 1000];\n function pointsFunc(points) {\n return points == 550;\n }\n function display() {\n document.getElementById(\"demo\").innerHTML = pointsArr.some(pointsFunc);\n }\n </script>\n</body></html>"
},
{
"code": null,
"e": 2456,
"s": 2428,
"text": "Click the “Result” button −"
}
] |
How to train Tensorflow models. Using GPUs | by DeviceHive | Towards Data Science
|
In recent years, there has been significant progress in the field of machine learning. Much of this progress can be attributed to the increasing usage of graphics processing units (GPUs) to accelerate the training of machine learning models. In particular, the extra computational power has lead to the popularization of Deep Learning — the use of complex, multi-level neural networks to create models, capable of feature detection from large amounts of unlabeled training data.
GPUs are so well-suited to deep learning because the type of calculations they were designed to process happens to be the same as those encountered in deep learning. Images, videos, and other graphics are represented as matrices, so that when you perform any operation, such as a zoom in effect or a camera rotation, all you are doing is applying some mathematical transformation to a matrix.
In practice, this means that GPUs, compared to central processing units (CPUs), are more specialized at performing matrix operations and several other types of advanced mathematical transformations. This makes deep learning algorithms run several times faster on a GPU compared to a CPU. Learning times can often be reduced from days to mere hours.
So, how would one approach using GPUs for machine learning tasks? In this post we will explore the setup of a GPU-enabled AWS instance to train a neural network in Tensorflow.
To start, create a new EC2 instance in the AWS control panel.
We will be using Ubuntu Server 16.04 LTS (HVM) as the OS, but the process should be similar on any 64-bit Linux distro.
For the instance type, select g2.2xlarge — these are enabled with NVIDIA GRID GPU. There are also instances with several of these GPUs, but utilizing more than one requires additional setup which will be discussed later in this post.
Finish the setup with your preferred security settings.
Once the setup and creation is done, SSH into your instance.
Python should already be present on the system, so install the required libraries:
sudo apt-get updatesudo apt-get install python-pip python-dev
Next, install Tensorflow with GPU support enabled. The simplest way is:
pip install tensorflow-gpu
However, this might fail for some installations. If this happens, there is an alternative:
export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.1-cp27-none-linux_x86_64.whlsudo pip install --upgrade $TF_BINARY_URL
If you get a locale.Error: unsupported locale setting during TF installations, enter:
export LC_ALL=C
Then, repeat the installation process.
If no further errors occur, the TF installation is over. However, for GPU acceleration to properly work, we still have to install Cuda Toolkit and cuDNN.
First, lets install the Cuda Toolkit.
Before you start, please note that the installation process will download around 3gb of data.
wget "http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_8.0.44-1_amd64.deb"sudo dpkg -i cuda-repo-ubuntu1604_8.0.44-1_amd64.debsudo apt-get updatesudo apt-get install cuda
Once the CUDA Toolkit is installed, download cuDNN Library for Linux (note that you will need to register for the Accelerated Computing Developer Program) and copy it to your EC2 instance.
sudo tar -xvf cudnn-8.0-linux-x64-v5.1.tgz -C /usr/localexport PATH=/usr/local/cuda/bin:$PATHexport LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64"export CUDA_HOME=/usr/local/cuda
Finally, the setup process is over and we can test the installation:
python>>> import tensorflow as tf>>> sess = tf.Session()
You should see Found device 0 with properties: name: GRID K520
>>> hello_world = tf.constant("Hello, world!")>>> print sess.run(hello_world)
Hello, world! will be displayed
>>> print sess.run(tf.constant(123)*tf.constant(456))
56088 is the correct answer.
The system is now ready to utilize a GPU with Tensorflow.
The changes to your Tensorflow code should be minimal. If a TensorFlow operation has both CPU and GPU implementations, the GPU devices will be prioritized when the operation is assigned to a device.
If you would like a particular operation to run on a device of your choice instead of using the defaults, you can use with tf.device to create a device context. This forces all the operations within that context to have the same device assignment.
# Creates a graph.with tf.device('/gpu:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b)# Creates a session with log_device_placement set to True.sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))# Runs the op.print sess.run©
If you would like to run TensorFlow on multiple GPUs, it is possible to construct a model in a multi-tower fashion and assign each tower to a different GPU. For example:
# Creates a graph.c = []for d in ['/gpu:2', '/gpu:3']: with tf.device(d): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2]) c.append(tf.matmul(a, b))with tf.device('/cpu:0'): sum = tf.add_n(c)# Creates a session with log_device_placement set to True.sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))# Runs the op.print sess.run(sum)
For benchmarking purposes we will use a convolutional neural network (CNN) for recognizing images that is provided as part of the Tensorflow tutorials. CIFAR-10 classification is a common benchmark problem in machine learning. The task is to classify RGB 32x32 pixel images across 10 categories.
Let’s compare the performance of training this model on several popular configurations:
As demonstrated by the results, in this specific example it takes the power of 16 CPUs to match the power of 1 GPU. At the time of writing, utilizing a GPU is also 18% cheaper for the same training time.
Written by Nikolay Khabarov, Senior Architect at DataArt.
|
[
{
"code": null,
"e": 651,
"s": 172,
"text": "In recent years, there has been significant progress in the field of machine learning. Much of this progress can be attributed to the increasing usage of graphics processing units (GPUs) to accelerate the training of machine learning models. In particular, the extra computational power has lead to the popularization of Deep Learning — the use of complex, multi-level neural networks to create models, capable of feature detection from large amounts of unlabeled training data."
},
{
"code": null,
"e": 1044,
"s": 651,
"text": "GPUs are so well-suited to deep learning because the type of calculations they were designed to process happens to be the same as those encountered in deep learning. Images, videos, and other graphics are represented as matrices, so that when you perform any operation, such as a zoom in effect or a camera rotation, all you are doing is applying some mathematical transformation to a matrix."
},
{
"code": null,
"e": 1393,
"s": 1044,
"text": "In practice, this means that GPUs, compared to central processing units (CPUs), are more specialized at performing matrix operations and several other types of advanced mathematical transformations. This makes deep learning algorithms run several times faster on a GPU compared to a CPU. Learning times can often be reduced from days to mere hours."
},
{
"code": null,
"e": 1569,
"s": 1393,
"text": "So, how would one approach using GPUs for machine learning tasks? In this post we will explore the setup of a GPU-enabled AWS instance to train a neural network in Tensorflow."
},
{
"code": null,
"e": 1631,
"s": 1569,
"text": "To start, create a new EC2 instance in the AWS control panel."
},
{
"code": null,
"e": 1751,
"s": 1631,
"text": "We will be using Ubuntu Server 16.04 LTS (HVM) as the OS, but the process should be similar on any 64-bit Linux distro."
},
{
"code": null,
"e": 1985,
"s": 1751,
"text": "For the instance type, select g2.2xlarge — these are enabled with NVIDIA GRID GPU. There are also instances with several of these GPUs, but utilizing more than one requires additional setup which will be discussed later in this post."
},
{
"code": null,
"e": 2041,
"s": 1985,
"text": "Finish the setup with your preferred security settings."
},
{
"code": null,
"e": 2102,
"s": 2041,
"text": "Once the setup and creation is done, SSH into your instance."
},
{
"code": null,
"e": 2185,
"s": 2102,
"text": "Python should already be present on the system, so install the required libraries:"
},
{
"code": null,
"e": 2247,
"s": 2185,
"text": "sudo apt-get updatesudo apt-get install python-pip python-dev"
},
{
"code": null,
"e": 2319,
"s": 2247,
"text": "Next, install Tensorflow with GPU support enabled. The simplest way is:"
},
{
"code": null,
"e": 2346,
"s": 2319,
"text": "pip install tensorflow-gpu"
},
{
"code": null,
"e": 2437,
"s": 2346,
"text": "However, this might fail for some installations. If this happens, there is an alternative:"
},
{
"code": null,
"e": 2600,
"s": 2437,
"text": "export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.1-cp27-none-linux_x86_64.whlsudo pip install --upgrade $TF_BINARY_URL"
},
{
"code": null,
"e": 2686,
"s": 2600,
"text": "If you get a locale.Error: unsupported locale setting during TF installations, enter:"
},
{
"code": null,
"e": 2702,
"s": 2686,
"text": "export LC_ALL=C"
},
{
"code": null,
"e": 2741,
"s": 2702,
"text": "Then, repeat the installation process."
},
{
"code": null,
"e": 2895,
"s": 2741,
"text": "If no further errors occur, the TF installation is over. However, for GPU acceleration to properly work, we still have to install Cuda Toolkit and cuDNN."
},
{
"code": null,
"e": 2933,
"s": 2895,
"text": "First, lets install the Cuda Toolkit."
},
{
"code": null,
"e": 3027,
"s": 2933,
"text": "Before you start, please note that the installation process will download around 3gb of data."
},
{
"code": null,
"e": 3244,
"s": 3027,
"text": "wget \"http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_8.0.44-1_amd64.deb\"sudo dpkg -i cuda-repo-ubuntu1604_8.0.44-1_amd64.debsudo apt-get updatesudo apt-get install cuda"
},
{
"code": null,
"e": 3433,
"s": 3244,
"text": "Once the CUDA Toolkit is installed, download cuDNN Library for Linux (note that you will need to register for the Accelerated Computing Developer Program) and copy it to your EC2 instance."
},
{
"code": null,
"e": 3657,
"s": 3433,
"text": "sudo tar -xvf cudnn-8.0-linux-x64-v5.1.tgz -C /usr/localexport PATH=/usr/local/cuda/bin:$PATHexport LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64\"export CUDA_HOME=/usr/local/cuda"
},
{
"code": null,
"e": 3726,
"s": 3657,
"text": "Finally, the setup process is over and we can test the installation:"
},
{
"code": null,
"e": 3783,
"s": 3726,
"text": "python>>> import tensorflow as tf>>> sess = tf.Session()"
},
{
"code": null,
"e": 3846,
"s": 3783,
"text": "You should see Found device 0 with properties: name: GRID K520"
},
{
"code": null,
"e": 3924,
"s": 3846,
"text": ">>> hello_world = tf.constant(\"Hello, world!\")>>> print sess.run(hello_world)"
},
{
"code": null,
"e": 3956,
"s": 3924,
"text": "Hello, world! will be displayed"
},
{
"code": null,
"e": 4010,
"s": 3956,
"text": ">>> print sess.run(tf.constant(123)*tf.constant(456))"
},
{
"code": null,
"e": 4039,
"s": 4010,
"text": "56088 is the correct answer."
},
{
"code": null,
"e": 4097,
"s": 4039,
"text": "The system is now ready to utilize a GPU with Tensorflow."
},
{
"code": null,
"e": 4296,
"s": 4097,
"text": "The changes to your Tensorflow code should be minimal. If a TensorFlow operation has both CPU and GPU implementations, the GPU devices will be prioritized when the operation is assigned to a device."
},
{
"code": null,
"e": 4544,
"s": 4296,
"text": "If you would like a particular operation to run on a device of your choice instead of using the defaults, you can use with tf.device to create a device context. This forces all the operations within that context to have the same device assignment."
},
{
"code": null,
"e": 4906,
"s": 4544,
"text": "# Creates a graph.with tf.device('/gpu:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b)# Creates a session with log_device_placement set to True.sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))# Runs the op.print sess.run©"
},
{
"code": null,
"e": 5076,
"s": 4906,
"text": "If you would like to run TensorFlow on multiple GPUs, it is possible to construct a model in a multi-tower fashion and assign each tower to a different GPU. For example:"
},
{
"code": null,
"e": 5501,
"s": 5076,
"text": "# Creates a graph.c = []for d in ['/gpu:2', '/gpu:3']: with tf.device(d): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2]) c.append(tf.matmul(a, b))with tf.device('/cpu:0'): sum = tf.add_n(c)# Creates a session with log_device_placement set to True.sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))# Runs the op.print sess.run(sum)"
},
{
"code": null,
"e": 5797,
"s": 5501,
"text": "For benchmarking purposes we will use a convolutional neural network (CNN) for recognizing images that is provided as part of the Tensorflow tutorials. CIFAR-10 classification is a common benchmark problem in machine learning. The task is to classify RGB 32x32 pixel images across 10 categories."
},
{
"code": null,
"e": 5885,
"s": 5797,
"text": "Let’s compare the performance of training this model on several popular configurations:"
},
{
"code": null,
"e": 6089,
"s": 5885,
"text": "As demonstrated by the results, in this specific example it takes the power of 16 CPUs to match the power of 1 GPU. At the time of writing, utilizing a GPU is also 18% cheaper for the same training time."
}
] |
Rexx - TRUNC
|
This method truncates a number.
TRUNC(i)
i − This the input number for which the value needs to be truncated.
i − This the input number for which the value needs to be truncated.
Returns the truncated number.
/* Main program */
say TRUNC(12.22)
When we run the above program, we will get the following result.
12
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2371,
"s": 2339,
"text": "This method truncates a number."
},
{
"code": null,
"e": 2382,
"s": 2371,
"text": "TRUNC(i) \n"
},
{
"code": null,
"e": 2451,
"s": 2382,
"text": "i − This the input number for which the value needs to be truncated."
},
{
"code": null,
"e": 2520,
"s": 2451,
"text": "i − This the input number for which the value needs to be truncated."
},
{
"code": null,
"e": 2550,
"s": 2520,
"text": "Returns the truncated number."
},
{
"code": null,
"e": 2589,
"s": 2550,
"text": "/* Main program */ \nsay TRUNC(12.22) "
},
{
"code": null,
"e": 2654,
"s": 2589,
"text": "When we run the above program, we will get the following result."
},
{
"code": null,
"e": 2659,
"s": 2654,
"text": "12 \n"
},
{
"code": null,
"e": 2666,
"s": 2659,
"text": " Print"
},
{
"code": null,
"e": 2677,
"s": 2666,
"text": " Add Notes"
}
] |
How can I convert string to double in C/C++?
|
Here is an example to convert a string to double.
Live Demo
#include <iostream>
using namespace std;
int main() {
char s[20] = "18.2894 is a number";
char *p;
double result;
result = strtod(s, &p);
cout<<"The number after conversion of string : "<<result;
return(0);
}
The number after conversion of string : 18.289400
In the above program, a char type array s[20] is declared which is initialized with a alphanumeric characters. The function strtod() is used to convert that string into a double number.
char s[20] = "18.2894 is a number";
char *p;
double result;
result = strtod(s, &p);
|
[
{
"code": null,
"e": 1112,
"s": 1062,
"text": "Here is an example to convert a string to double."
},
{
"code": null,
"e": 1123,
"s": 1112,
"text": " Live Demo"
},
{
"code": null,
"e": 1350,
"s": 1123,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n char s[20] = \"18.2894 is a number\";\n char *p;\n double result;\n result = strtod(s, &p);\n cout<<\"The number after conversion of string : \"<<result;\n return(0);\n}"
},
{
"code": null,
"e": 1400,
"s": 1350,
"text": "The number after conversion of string : 18.289400"
},
{
"code": null,
"e": 1586,
"s": 1400,
"text": "In the above program, a char type array s[20] is declared which is initialized with a alphanumeric characters. The function strtod() is used to convert that string into a double number."
},
{
"code": null,
"e": 1670,
"s": 1586,
"text": "char s[20] = \"18.2894 is a number\";\nchar *p;\ndouble result;\nresult = strtod(s, &p);"
}
] |
Instruction type RRC in 8085 Microprocessor
|
In 8085 Instruction set, RRC stands for “Rotate Right Accumulator”. With the help of this instruction, we can rotate the Accumulator current content to the right by 1-bit position. The following Fig. will depict the rotation operation.
In this right rotation, the least significant bit will come out from the Accumulator and will be copied to Cy bit in the flag register and also will be copied to the most significant bit position of the Accumulator. Notice that the Cy flag is not involved in the rotation, and it is only 8-bit rotation of Accumulator contents. Only Cy flag is affected by this instruction execution.
This instruction can be used in multiple following operations −
To check the value of the least significant bit value of the Accumulator through the value of the cy bit.
To check the value of the least significant bit value of the Accumulator through the value of the cy bit.
It can be used to perform division by 2. We know that Accumulator’s content will have n-bits right shift if we divide the Accumulator by 2n.
It can be used to perform division by 2. We know that Accumulator’s content will have n-bits right shift if we divide the Accumulator by 2n.
The execution of this instructions has been depicted through following examples −
(A)
(Cy)
8AH ---> 1000 1010
0100 0101 ---> 45H (Last bit 0 is copied to Cy bit)
Note that Accumulator value is halved.
(A)
(Cy)
8AH ---> 1000 1011
1100 0101 --->C5H (Last bit 1 is copied to Cy bit)
Note that Accumulator value is not halved in this case because LS bit of Accumulator was a 1 before rotation.
The timing diagram against this instruction RRC execution is as follows −
Summary − So this instruction RRC requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
|
[
{
"code": null,
"e": 1298,
"s": 1062,
"text": "In 8085 Instruction set, RRC stands for “Rotate Right Accumulator”. With the help of this instruction, we can rotate the Accumulator current content to the right by 1-bit position. The following Fig. will depict the rotation operation."
},
{
"code": null,
"e": 1682,
"s": 1298,
"text": "In this right rotation, the least significant bit will come out from the Accumulator and will be copied to Cy bit in the flag register and also will be copied to the most significant bit position of the Accumulator. Notice that the Cy flag is not involved in the rotation, and it is only 8-bit rotation of Accumulator contents. Only Cy flag is affected by this instruction execution."
},
{
"code": null,
"e": 1746,
"s": 1682,
"text": "This instruction can be used in multiple following operations −"
},
{
"code": null,
"e": 1852,
"s": 1746,
"text": "To check the value of the least significant bit value of the Accumulator through the value of the cy bit."
},
{
"code": null,
"e": 1958,
"s": 1852,
"text": "To check the value of the least significant bit value of the Accumulator through the value of the cy bit."
},
{
"code": null,
"e": 2099,
"s": 1958,
"text": "It can be used to perform division by 2. We know that Accumulator’s content will have n-bits right shift if we divide the Accumulator by 2n."
},
{
"code": null,
"e": 2240,
"s": 2099,
"text": "It can be used to perform division by 2. We know that Accumulator’s content will have n-bits right shift if we divide the Accumulator by 2n."
},
{
"code": null,
"e": 2322,
"s": 2240,
"text": "The execution of this instructions has been depicted through following examples −"
},
{
"code": null,
"e": 2326,
"s": 2322,
"text": "(A)"
},
{
"code": null,
"e": 2331,
"s": 2326,
"text": "(Cy)"
},
{
"code": null,
"e": 2407,
"s": 2331,
"text": "8AH ---> 1000 1010\n 0100 0101 ---> 45H (Last bit 0 is copied to Cy bit)\n"
},
{
"code": null,
"e": 2446,
"s": 2407,
"text": "Note that Accumulator value is halved."
},
{
"code": null,
"e": 2450,
"s": 2446,
"text": "(A)"
},
{
"code": null,
"e": 2455,
"s": 2450,
"text": "(Cy)"
},
{
"code": null,
"e": 2530,
"s": 2455,
"text": "8AH ---> 1000 1011\n 1100 0101 --->C5H (Last bit 1 is copied to Cy bit)\n"
},
{
"code": null,
"e": 2640,
"s": 2530,
"text": "Note that Accumulator value is not halved in this case because LS bit of Accumulator was a 1 before rotation."
},
{
"code": null,
"e": 2714,
"s": 2640,
"text": "The timing diagram against this instruction RRC execution is as follows −"
},
{
"code": null,
"e": 2857,
"s": 2714,
"text": "Summary − So this instruction RRC requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram."
}
] |
A Data Science/Big Data Laboratory — part 2 of 4: Hadoop 3.2.1 and Spark 3.0.0 over Ubuntu 20.04 in a 3-node cluster | by Pier Taranti | Towards Data Science
|
This text can be used to support the installation in any Ubuntu 20.04 server clusters, and this is the beauty of well-designed layered software. Furthermore, if you have more nodes, you can distribute the software as you like. The text assumes you know Linux command line, including ssh, vim, and nano.
I do not recommend starting with less than three Raspberries since you need to set the communication, and both Zookeeper and Kafka requires an odd number of nodes. If you are trying a single node this guide may be used. Still, the performance is likely to be disappointing in a Raspberry — for single node I suggest a virtual machine with a reasonable amount of RAM and processor.
Due to size, I had to divide the tutorial into four parts
Part 1: Introduction, Operational System and Networking
Part 2: Hadoop and Spark
Part 3: PostgreSQL and Hive
Part 4: Kafka and Conclusion
All configuration files are available at [1]:
github.com
Disclaimer: This text is offered to everyone for free to use at your own risk. I took care in citing all my sources, but if you feel that something is missed, please send me a note. Since different software versions may behaviour in a distinct way due to their dependencies, I suggest using the same versions I used in your first try.
The Hadoop and Spark installation considered the instructions from [3, 4] together with other sources.
I have used the updated versions from the Apache website:
hadoop-3.2.1.tar.gz
spark-2.4.5-bin-hadoop2.7.tgz
First: download, and extract the files to /opt. Give access to pi user.
sudo tar -xvf hadoop-3.2.1.tar.gz -C /opt/sudo tar -xvf spark-2.4.5-bin-hadoop2.7.tgz -C /opt/cd /opt/pi@pi1:/opt$ sudo mv hadoop-3.2.1 hadooppi@pi1:/opt$ sudo mv spark-2.4.5-bin-hadoop2.7 sparkpi@pi1:/opt$ sudo chown -R pi:pi /opt/sparkpi@pi1:/opt$ sudo chown -R pi:pi /opt/hadoop
add to /home/pi/.bashrc:
After editing:
source /home/pi/.bashrc
Now you need to configure the Hadoop and Spark
To be clear — we first configure it as a single node and then modify for a cluster. My repository in GitHub contains only the final cluster config files.
Go to folder
/opt/hadoop/etc/hadoop
I had a lot of trouble at this point: I accidentally inserted one blanc line on top of the file header. This blanc line caused parse errors and Hadoop kept failing until I realised the issue.
Edit the file
/opt/hadoop/etc/hadoop/hadoop-env.sh,
adding the following line at the end:
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-arm64
Edit configuration in
/opt/hadoop/etc/hadoop/core-site.xml
Edit configuration in
/opt/hadoop/etc/hadoop/hdfs-site.xml
Now prepare the data area:
$ sudo mkdir -p /opt/hadoop_tmp/hdfs/datanode$ sudo mkdir -p /opt/hadoop_tmp/hdfs/namenodesudo chown -R pi:pi /opt/hadoop_tmp
Edit configuration in
/opt/hadoop/etc/hadoop/mapred-site.xml
Edit configuration in
/opt/hadoop/etc/hadoop/yarn-site.xml
Prepare the data space:
$ hdfs namenode -format -force$ start-dfs.sh$ start-yarn.sh$ hadoop fs -mkdir /tmp$ hadoop fs -ls /Found 1 itemsdrwzr-xr-x - pi supergroup 0 2019-04-09 16:51 /tmp
Use jps to check if all services are on (numbers change..) :
$ jps2736 NameNode2850 DataNode3430 NodeManager3318 ResourceManager3020 SecondaryNameNode
You need these five services on!
For testing the single node, I refer to the tutorial [2]:
Execute the following commands:
pi@pi1:/opt$ hadoop fs -put $SPARK_HOME/README.md /2020-06-24 19:16:02,822 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable2020-06-24 19:16:06,389 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = falsepi@pi1:/opt$ spark-shell2020-06-24 19:16:23,814 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicableSetting default log level to "WARN".To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).Spark context Web UI available at http://pi1:4040Spark context available as 'sc' (master = local[*], app id = local-1593026210941).Spark session available as 'spark'.Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /___/ .__/\_,_/_/ /_/\_\ version 3.0.0 /_/Using Scala version 2.12.10 (OpenJDK 64-Bit Server VM, Java 1.8.0_252)Type in expressions to have them evaluated.Type :help for more information.scala> val textFile = sc.textFile("hdfs://pi1:9000/README.md")textFile: org.apache.spark.rdd.RDD[String] = hdfs://pi1:9000/README.md MapPartitionsRDD[1] at textFile at <console>:24scala> textFile.first()res0: String = # Apache Sparkscala>
At this point, I got stuck, with a repeating message similar to:
INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)
I followed the suggestion from [4] and other sources and changed the following file /opt/hadoop/etc/hadoop/capacity-scheduler.xml.
Parameter yarn.scheduler.capacity.maximum-am-resource-percent should be set if you are running a cluster on a single machine where you have got less resource. This setting indicates the fraction of the resources that are made available to be allocated to application masters, increasing the number of possible concurrent applications. Note that this is dependent on your resources. It worked in my Pi 4 4GB ram.
Edit the file, adding the property:
/opt/hadoop/etc/hadoop/capacity-scheduler.xml
Note — the tutorials usually provide commands to suppress warnings. I do prefer to see these warnings when experimenting. If you would like to remove it refers to the first tutorial.
Now you should have one fully operational installation in a single node. It is time to Hadoop goes to a cluster!
I executed the tutorials but faced a number of problems. This is expected — different environment, software versions.
After some experimenting, I succeed to have a stable environment. The next steps to configure Hadoop to operate with Yarn in cluster are a mix from both [2, 4].
Note — all nodes have the same configuration (p2, p3, ... -> workers), except the node pi1 (pi1 -> master), because of the Spark. Again, my GitHub repository has the configuration available. I have made available the configuration for all nodes.
Creating the folders for all nodes:
$ clustercmd-sudo mkdir -p /opt/hadoop_tmp/hdfs$ clustercmd-sudo chown –R pi:pi /opt/hadoop_tmp$ clustercmd-sudo mkdir -p /opt/hadoop$ clustercmd-sudo chown -R pi:pi /opt/Hadoop
The next will remove all data from Hadoop. Do your backup first if there is something important.
$ clustercmd rm –rf /opt/hadoop_tmp/hdfs/datanode/*$ clustercmd rm –rf /opt/hadoop_tmp/hdfs/namenode/*
Note that Spark will exist only in the master.
Copy Hadoop :
From pi1:
pi@pi1:~$ rsync -vaz /opt/hadoop pi2:/opt/ hadoop pi@pi1:~$ rsync -vaz /opt/hadoop pi3:/opt/ hadoop pi@pi1:~$ rsync -vaz /opt/hadoop pi4:/opt/ hadoop
Do it for all your nodes.
I prefer doing one by one and confirming no abnormal behaviour.
Now, the following files need to be edited, changing the configuration:
/opt/hadoop/etc/hadoop/core-site.xml
/opt/hadoop/etc/hadoop/hdfs-site.xml
Note — The property dfs.replication, indicates how many times data is replicated in the cluster. You can set to have all the data duplicated on the two or more nodes. Don’t enter a value higher than the actual number of worker nodes. I used 1 because one of my noted was using a 16GB micro SD. Some of my parts delayed in the post due to the COVID-19 outbreak. If you misconfigure it your spark applications will get stuck in “accepted” status, due to the lack of resources.
Note — The last property, dfs.permissions.enabled, was set to false to disable permission checking. I use spark from a machine external from the cluster, and this facilitates my access. Obviously I advice do not use this setting in a production environment. I also disabled the safe mode. To do this, after finishing the installation run:
hdfs dfsadmin -safemode leave
how many times data is replicated in the cluster. You can set to have all the data duplicated on the two or more nodes. Don’t enter a value higher than the actual number of worker nodes. I used 1 because one of my noted was using a 16GB micro SD. Some of my parts delayed in the post due to the COVID-19 outbreak. If you misconfigure it your spark applications will get stuck in “accepted” status, due to the lack of resources.
/opt/hadoop/etc/hadoop/mapred-site.xml
/opt/hadoop/etc/hadoop/yarn-site.xml
create two files:
/opt/hadoop/etc/hadoop/master
/opt/hadoop/etc/hadoop/workers
After updating the configuration files at all nodes, it is necessary to format the data space and starting the cluster (you can start from any node):
$ hdfs namenode -format -force$ start-dfs.sh$ start-yarn.sh
Basically, you need to create/edit the following configuration file:
/opt/spark/conf/spark-defaults.conf
These values can be adjusted to your hardware — but they will work with Raspberry Pi 4 4GB.
Set environment variables at:
/opt/spark/conf/spark-env.sh
Install the following packages in all nodes in order to allow the nodes to process jobs prepared in python/pyspark:
sudo apt intall python3 python-is-python3
Reboot all nodes, and restart services:
$ start-dfs.sh$ start-yarn.sh
You can send one application example to test the spark:
$ spark-submit --deploy-mode client --class org.apache.spark.examples.SparkPi /opt/spark/examples/jars/spark-examples_2.12-3.0.0.jar
At the end of the processing, you should receive an approximated calculation for PI value:
Pi is roughly 3.140555702778514
(this PI calculation needs improvement!!!!)
http://pi1:9870/
Initially, I was not able to handle(upload/delete) files online. A workaround is available in:
community.cloudera.com
This workaround is implemented adding the following properties to Hadoop core-site.xml:
http://pi1:8088/
towardsdatascience.com
[1] P. G. Taranti. https://github.com/ptaranti/RaspberryPiCluster
[2] A. W. Watson. Building a Raspberry Pi Hadoop / Spark Cluster (2019)
[3] W. H. Liang. Build Raspberry Pi Hadoop/Spark Cluster from scratch (2019)
[4] F. Houbart. How to Install and Set Up a 3-Node Hadoop Cluster (2019)
|
[
{
"code": null,
"e": 350,
"s": 47,
"text": "This text can be used to support the installation in any Ubuntu 20.04 server clusters, and this is the beauty of well-designed layered software. Furthermore, if you have more nodes, you can distribute the software as you like. The text assumes you know Linux command line, including ssh, vim, and nano."
},
{
"code": null,
"e": 731,
"s": 350,
"text": "I do not recommend starting with less than three Raspberries since you need to set the communication, and both Zookeeper and Kafka requires an odd number of nodes. If you are trying a single node this guide may be used. Still, the performance is likely to be disappointing in a Raspberry — for single node I suggest a virtual machine with a reasonable amount of RAM and processor."
},
{
"code": null,
"e": 789,
"s": 731,
"text": "Due to size, I had to divide the tutorial into four parts"
},
{
"code": null,
"e": 845,
"s": 789,
"text": "Part 1: Introduction, Operational System and Networking"
},
{
"code": null,
"e": 870,
"s": 845,
"text": "Part 2: Hadoop and Spark"
},
{
"code": null,
"e": 898,
"s": 870,
"text": "Part 3: PostgreSQL and Hive"
},
{
"code": null,
"e": 927,
"s": 898,
"text": "Part 4: Kafka and Conclusion"
},
{
"code": null,
"e": 973,
"s": 927,
"text": "All configuration files are available at [1]:"
},
{
"code": null,
"e": 984,
"s": 973,
"text": "github.com"
},
{
"code": null,
"e": 1319,
"s": 984,
"text": "Disclaimer: This text is offered to everyone for free to use at your own risk. I took care in citing all my sources, but if you feel that something is missed, please send me a note. Since different software versions may behaviour in a distinct way due to their dependencies, I suggest using the same versions I used in your first try."
},
{
"code": null,
"e": 1422,
"s": 1319,
"text": "The Hadoop and Spark installation considered the instructions from [3, 4] together with other sources."
},
{
"code": null,
"e": 1480,
"s": 1422,
"text": "I have used the updated versions from the Apache website:"
},
{
"code": null,
"e": 1500,
"s": 1480,
"text": "hadoop-3.2.1.tar.gz"
},
{
"code": null,
"e": 1530,
"s": 1500,
"text": "spark-2.4.5-bin-hadoop2.7.tgz"
},
{
"code": null,
"e": 1602,
"s": 1530,
"text": "First: download, and extract the files to /opt. Give access to pi user."
},
{
"code": null,
"e": 1885,
"s": 1602,
"text": "sudo tar -xvf hadoop-3.2.1.tar.gz -C /opt/sudo tar -xvf spark-2.4.5-bin-hadoop2.7.tgz -C /opt/cd /opt/pi@pi1:/opt$ sudo mv hadoop-3.2.1 hadooppi@pi1:/opt$ sudo mv spark-2.4.5-bin-hadoop2.7 sparkpi@pi1:/opt$ sudo chown -R pi:pi /opt/sparkpi@pi1:/opt$ sudo chown -R pi:pi /opt/hadoop"
},
{
"code": null,
"e": 1910,
"s": 1885,
"text": "add to /home/pi/.bashrc:"
},
{
"code": null,
"e": 1925,
"s": 1910,
"text": "After editing:"
},
{
"code": null,
"e": 1949,
"s": 1925,
"text": "source /home/pi/.bashrc"
},
{
"code": null,
"e": 1996,
"s": 1949,
"text": "Now you need to configure the Hadoop and Spark"
},
{
"code": null,
"e": 2150,
"s": 1996,
"text": "To be clear — we first configure it as a single node and then modify for a cluster. My repository in GitHub contains only the final cluster config files."
},
{
"code": null,
"e": 2163,
"s": 2150,
"text": "Go to folder"
},
{
"code": null,
"e": 2186,
"s": 2163,
"text": "/opt/hadoop/etc/hadoop"
},
{
"code": null,
"e": 2378,
"s": 2186,
"text": "I had a lot of trouble at this point: I accidentally inserted one blanc line on top of the file header. This blanc line caused parse errors and Hadoop kept failing until I realised the issue."
},
{
"code": null,
"e": 2392,
"s": 2378,
"text": "Edit the file"
},
{
"code": null,
"e": 2430,
"s": 2392,
"text": "/opt/hadoop/etc/hadoop/hadoop-env.sh,"
},
{
"code": null,
"e": 2468,
"s": 2430,
"text": "adding the following line at the end:"
},
{
"code": null,
"e": 2519,
"s": 2468,
"text": "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-arm64"
},
{
"code": null,
"e": 2541,
"s": 2519,
"text": "Edit configuration in"
},
{
"code": null,
"e": 2578,
"s": 2541,
"text": "/opt/hadoop/etc/hadoop/core-site.xml"
},
{
"code": null,
"e": 2600,
"s": 2578,
"text": "Edit configuration in"
},
{
"code": null,
"e": 2637,
"s": 2600,
"text": "/opt/hadoop/etc/hadoop/hdfs-site.xml"
},
{
"code": null,
"e": 2664,
"s": 2637,
"text": "Now prepare the data area:"
},
{
"code": null,
"e": 2790,
"s": 2664,
"text": "$ sudo mkdir -p /opt/hadoop_tmp/hdfs/datanode$ sudo mkdir -p /opt/hadoop_tmp/hdfs/namenodesudo chown -R pi:pi /opt/hadoop_tmp"
},
{
"code": null,
"e": 2812,
"s": 2790,
"text": "Edit configuration in"
},
{
"code": null,
"e": 2851,
"s": 2812,
"text": "/opt/hadoop/etc/hadoop/mapred-site.xml"
},
{
"code": null,
"e": 2873,
"s": 2851,
"text": "Edit configuration in"
},
{
"code": null,
"e": 2910,
"s": 2873,
"text": "/opt/hadoop/etc/hadoop/yarn-site.xml"
},
{
"code": null,
"e": 2934,
"s": 2910,
"text": "Prepare the data space:"
},
{
"code": null,
"e": 3108,
"s": 2934,
"text": "$ hdfs namenode -format -force$ start-dfs.sh$ start-yarn.sh$ hadoop fs -mkdir /tmp$ hadoop fs -ls /Found 1 itemsdrwzr-xr-x - pi supergroup 0 2019-04-09 16:51 /tmp"
},
{
"code": null,
"e": 3169,
"s": 3108,
"text": "Use jps to check if all services are on (numbers change..) :"
},
{
"code": null,
"e": 3259,
"s": 3169,
"text": "$ jps2736 NameNode2850 DataNode3430 NodeManager3318 ResourceManager3020 SecondaryNameNode"
},
{
"code": null,
"e": 3292,
"s": 3259,
"text": "You need these five services on!"
},
{
"code": null,
"e": 3350,
"s": 3292,
"text": "For testing the single node, I refer to the tutorial [2]:"
},
{
"code": null,
"e": 3382,
"s": 3350,
"text": "Execute the following commands:"
},
{
"code": null,
"e": 4723,
"s": 3382,
"text": "pi@pi1:/opt$ hadoop fs -put $SPARK_HOME/README.md /2020-06-24 19:16:02,822 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable2020-06-24 19:16:06,389 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = falsepi@pi1:/opt$ spark-shell2020-06-24 19:16:23,814 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicableSetting default log level to \"WARN\".To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).Spark context Web UI available at http://pi1:4040Spark context available as 'sc' (master = local[*], app id = local-1593026210941).Spark session available as 'spark'.Welcome to ____ __ / __/__ ___ _____/ /__ _\\ \\/ _ \\/ _ `/ __/ '_/ /___/ .__/\\_,_/_/ /_/\\_\\ version 3.0.0 /_/Using Scala version 2.12.10 (OpenJDK 64-Bit Server VM, Java 1.8.0_252)Type in expressions to have them evaluated.Type :help for more information.scala> val textFile = sc.textFile(\"hdfs://pi1:9000/README.md\")textFile: org.apache.spark.rdd.RDD[String] = hdfs://pi1:9000/README.md MapPartitionsRDD[1] at textFile at <console>:24scala> textFile.first()res0: String = # Apache Sparkscala>"
},
{
"code": null,
"e": 4788,
"s": 4723,
"text": "At this point, I got stuck, with a repeating message similar to:"
},
{
"code": null,
"e": 4878,
"s": 4788,
"text": "INFO yarn.Client: Application report for application_1434263747091_0023 (state: ACCEPTED)"
},
{
"code": null,
"e": 5009,
"s": 4878,
"text": "I followed the suggestion from [4] and other sources and changed the following file /opt/hadoop/etc/hadoop/capacity-scheduler.xml."
},
{
"code": null,
"e": 5421,
"s": 5009,
"text": "Parameter yarn.scheduler.capacity.maximum-am-resource-percent should be set if you are running a cluster on a single machine where you have got less resource. This setting indicates the fraction of the resources that are made available to be allocated to application masters, increasing the number of possible concurrent applications. Note that this is dependent on your resources. It worked in my Pi 4 4GB ram."
},
{
"code": null,
"e": 5457,
"s": 5421,
"text": "Edit the file, adding the property:"
},
{
"code": null,
"e": 5503,
"s": 5457,
"text": "/opt/hadoop/etc/hadoop/capacity-scheduler.xml"
},
{
"code": null,
"e": 5686,
"s": 5503,
"text": "Note — the tutorials usually provide commands to suppress warnings. I do prefer to see these warnings when experimenting. If you would like to remove it refers to the first tutorial."
},
{
"code": null,
"e": 5799,
"s": 5686,
"text": "Now you should have one fully operational installation in a single node. It is time to Hadoop goes to a cluster!"
},
{
"code": null,
"e": 5917,
"s": 5799,
"text": "I executed the tutorials but faced a number of problems. This is expected — different environment, software versions."
},
{
"code": null,
"e": 6078,
"s": 5917,
"text": "After some experimenting, I succeed to have a stable environment. The next steps to configure Hadoop to operate with Yarn in cluster are a mix from both [2, 4]."
},
{
"code": null,
"e": 6324,
"s": 6078,
"text": "Note — all nodes have the same configuration (p2, p3, ... -> workers), except the node pi1 (pi1 -> master), because of the Spark. Again, my GitHub repository has the configuration available. I have made available the configuration for all nodes."
},
{
"code": null,
"e": 6360,
"s": 6324,
"text": "Creating the folders for all nodes:"
},
{
"code": null,
"e": 6538,
"s": 6360,
"text": "$ clustercmd-sudo mkdir -p /opt/hadoop_tmp/hdfs$ clustercmd-sudo chown –R pi:pi /opt/hadoop_tmp$ clustercmd-sudo mkdir -p /opt/hadoop$ clustercmd-sudo chown -R pi:pi /opt/Hadoop"
},
{
"code": null,
"e": 6635,
"s": 6538,
"text": "The next will remove all data from Hadoop. Do your backup first if there is something important."
},
{
"code": null,
"e": 6738,
"s": 6635,
"text": "$ clustercmd rm –rf /opt/hadoop_tmp/hdfs/datanode/*$ clustercmd rm –rf /opt/hadoop_tmp/hdfs/namenode/*"
},
{
"code": null,
"e": 6785,
"s": 6738,
"text": "Note that Spark will exist only in the master."
},
{
"code": null,
"e": 6799,
"s": 6785,
"text": "Copy Hadoop :"
},
{
"code": null,
"e": 6809,
"s": 6799,
"text": "From pi1:"
},
{
"code": null,
"e": 6975,
"s": 6809,
"text": "pi@pi1:~$ rsync -vaz /opt/hadoop pi2:/opt/ hadoop pi@pi1:~$ rsync -vaz /opt/hadoop pi3:/opt/ hadoop pi@pi1:~$ rsync -vaz /opt/hadoop pi4:/opt/ hadoop"
},
{
"code": null,
"e": 7001,
"s": 6975,
"text": "Do it for all your nodes."
},
{
"code": null,
"e": 7065,
"s": 7001,
"text": "I prefer doing one by one and confirming no abnormal behaviour."
},
{
"code": null,
"e": 7137,
"s": 7065,
"text": "Now, the following files need to be edited, changing the configuration:"
},
{
"code": null,
"e": 7174,
"s": 7137,
"text": "/opt/hadoop/etc/hadoop/core-site.xml"
},
{
"code": null,
"e": 7211,
"s": 7174,
"text": "/opt/hadoop/etc/hadoop/hdfs-site.xml"
},
{
"code": null,
"e": 7686,
"s": 7211,
"text": "Note — The property dfs.replication, indicates how many times data is replicated in the cluster. You can set to have all the data duplicated on the two or more nodes. Don’t enter a value higher than the actual number of worker nodes. I used 1 because one of my noted was using a 16GB micro SD. Some of my parts delayed in the post due to the COVID-19 outbreak. If you misconfigure it your spark applications will get stuck in “accepted” status, due to the lack of resources."
},
{
"code": null,
"e": 8025,
"s": 7686,
"text": "Note — The last property, dfs.permissions.enabled, was set to false to disable permission checking. I use spark from a machine external from the cluster, and this facilitates my access. Obviously I advice do not use this setting in a production environment. I also disabled the safe mode. To do this, after finishing the installation run:"
},
{
"code": null,
"e": 8056,
"s": 8025,
"text": " hdfs dfsadmin -safemode leave"
},
{
"code": null,
"e": 8484,
"s": 8056,
"text": "how many times data is replicated in the cluster. You can set to have all the data duplicated on the two or more nodes. Don’t enter a value higher than the actual number of worker nodes. I used 1 because one of my noted was using a 16GB micro SD. Some of my parts delayed in the post due to the COVID-19 outbreak. If you misconfigure it your spark applications will get stuck in “accepted” status, due to the lack of resources."
},
{
"code": null,
"e": 8523,
"s": 8484,
"text": "/opt/hadoop/etc/hadoop/mapred-site.xml"
},
{
"code": null,
"e": 8560,
"s": 8523,
"text": "/opt/hadoop/etc/hadoop/yarn-site.xml"
},
{
"code": null,
"e": 8578,
"s": 8560,
"text": "create two files:"
},
{
"code": null,
"e": 8608,
"s": 8578,
"text": "/opt/hadoop/etc/hadoop/master"
},
{
"code": null,
"e": 8639,
"s": 8608,
"text": "/opt/hadoop/etc/hadoop/workers"
},
{
"code": null,
"e": 8789,
"s": 8639,
"text": "After updating the configuration files at all nodes, it is necessary to format the data space and starting the cluster (you can start from any node):"
},
{
"code": null,
"e": 8849,
"s": 8789,
"text": "$ hdfs namenode -format -force$ start-dfs.sh$ start-yarn.sh"
},
{
"code": null,
"e": 8918,
"s": 8849,
"text": "Basically, you need to create/edit the following configuration file:"
},
{
"code": null,
"e": 8954,
"s": 8918,
"text": "/opt/spark/conf/spark-defaults.conf"
},
{
"code": null,
"e": 9046,
"s": 8954,
"text": "These values can be adjusted to your hardware — but they will work with Raspberry Pi 4 4GB."
},
{
"code": null,
"e": 9076,
"s": 9046,
"text": "Set environment variables at:"
},
{
"code": null,
"e": 9105,
"s": 9076,
"text": "/opt/spark/conf/spark-env.sh"
},
{
"code": null,
"e": 9221,
"s": 9105,
"text": "Install the following packages in all nodes in order to allow the nodes to process jobs prepared in python/pyspark:"
},
{
"code": null,
"e": 9263,
"s": 9221,
"text": "sudo apt intall python3 python-is-python3"
},
{
"code": null,
"e": 9303,
"s": 9263,
"text": "Reboot all nodes, and restart services:"
},
{
"code": null,
"e": 9333,
"s": 9303,
"text": "$ start-dfs.sh$ start-yarn.sh"
},
{
"code": null,
"e": 9389,
"s": 9333,
"text": "You can send one application example to test the spark:"
},
{
"code": null,
"e": 9522,
"s": 9389,
"text": "$ spark-submit --deploy-mode client --class org.apache.spark.examples.SparkPi /opt/spark/examples/jars/spark-examples_2.12-3.0.0.jar"
},
{
"code": null,
"e": 9613,
"s": 9522,
"text": "At the end of the processing, you should receive an approximated calculation for PI value:"
},
{
"code": null,
"e": 9645,
"s": 9613,
"text": "Pi is roughly 3.140555702778514"
},
{
"code": null,
"e": 9689,
"s": 9645,
"text": "(this PI calculation needs improvement!!!!)"
},
{
"code": null,
"e": 9706,
"s": 9689,
"text": "http://pi1:9870/"
},
{
"code": null,
"e": 9801,
"s": 9706,
"text": "Initially, I was not able to handle(upload/delete) files online. A workaround is available in:"
},
{
"code": null,
"e": 9824,
"s": 9801,
"text": "community.cloudera.com"
},
{
"code": null,
"e": 9912,
"s": 9824,
"text": "This workaround is implemented adding the following properties to Hadoop core-site.xml:"
},
{
"code": null,
"e": 9929,
"s": 9912,
"text": "http://pi1:8088/"
},
{
"code": null,
"e": 9952,
"s": 9929,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10018,
"s": 9952,
"text": "[1] P. G. Taranti. https://github.com/ptaranti/RaspberryPiCluster"
},
{
"code": null,
"e": 10090,
"s": 10018,
"text": "[2] A. W. Watson. Building a Raspberry Pi Hadoop / Spark Cluster (2019)"
},
{
"code": null,
"e": 10167,
"s": 10090,
"text": "[3] W. H. Liang. Build Raspberry Pi Hadoop/Spark Cluster from scratch (2019)"
}
] |
The accept() method in Java Stream.Builder
|
Add an element to the stream using the accept() method of Java Stream.Builder.
The following is the syntax:
void accept(T t)
Here, t is the argument to be inserted.
Import the following package for the Stream.Builder class in Java:
import java.util.stream.Stream;
First, declare a Stream.Builder:
Stream.Builder<String> builder = Stream.builder();
Now, use the accept() method:
builder.accept("Demo");
builder.accept("Text");
The following is an example displaying how to implement accept() method of Stream.Builder in Java:
Live Demo
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args){
Stream.Builder<String> builder = Stream.builder();
builder.accept("Demo");
builder.accept("Text");
Stream<String> str = builder.build();
str.forEach(System.out::println);
}
}
Demo
Text
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "Add an element to the stream using the accept() method of Java Stream.Builder."
},
{
"code": null,
"e": 1170,
"s": 1141,
"text": "The following is the syntax:"
},
{
"code": null,
"e": 1187,
"s": 1170,
"text": "void accept(T t)"
},
{
"code": null,
"e": 1227,
"s": 1187,
"text": "Here, t is the argument to be inserted."
},
{
"code": null,
"e": 1294,
"s": 1227,
"text": "Import the following package for the Stream.Builder class in Java:"
},
{
"code": null,
"e": 1326,
"s": 1294,
"text": "import java.util.stream.Stream;"
},
{
"code": null,
"e": 1359,
"s": 1326,
"text": "First, declare a Stream.Builder:"
},
{
"code": null,
"e": 1410,
"s": 1359,
"text": "Stream.Builder<String> builder = Stream.builder();"
},
{
"code": null,
"e": 1440,
"s": 1410,
"text": "Now, use the accept() method:"
},
{
"code": null,
"e": 1488,
"s": 1440,
"text": "builder.accept(\"Demo\");\nbuilder.accept(\"Text\");"
},
{
"code": null,
"e": 1587,
"s": 1488,
"text": "The following is an example displaying how to implement accept() method of Stream.Builder in Java:"
},
{
"code": null,
"e": 1598,
"s": 1587,
"text": " Live Demo"
},
{
"code": null,
"e": 1902,
"s": 1598,
"text": "import java.util.stream.Stream;\npublic class Demo {\n public static void main(String[] args){\n Stream.Builder<String> builder = Stream.builder();\n builder.accept(\"Demo\");\n builder.accept(\"Text\");\n Stream<String> str = builder.build();\n str.forEach(System.out::println);\n }\n}\n"
},
{
"code": null,
"e": 1912,
"s": 1902,
"text": "Demo\nText"
}
] |
Get the dates of Yesterday, Today, and Tomorrow using NumPy - GeeksforGeeks
|
26 Nov, 2020
In NumPy with the help of NumPy.datetime64(‘today’, ‘D’), we will find today date and if we want some date before today then we will subtract the no-of-date with the help of np.timedelta64() from today. And if we want some date after today then we will add the no of date with the help of np.timedelta64() from today. For yesterday, we will subtract 1 date, for tomorrow we will add 1 date.
Example #1: Get the dates yesterday, today, and tomorrow.
Python3
import numpy as np # for todaytoday = np.datetime64('today', 'D')print("Today: ", today) # for yesterdayyesterday = np.datetime64('today', 'D')- np.timedelta64(1, 'D') print("Yestraday: ", yesterday) # for tomorrowtomorrow = np.datetime64('today', 'D')+ np.timedelta64(1, 'D') print("Tomorrow: ", tomorrow)
Output:
Today: 2020-08-15
Yestraday: 2020-08-14
Tomorrow: 2020-08-16
Example #2: Get the dates in the interval.
Python3
import numpy as np # for todaytoday = np.datetime64('today', 'D')print("Today: ", today) # for before_2_daybefore_2_day = np.datetime64('today', 'D')- np.timedelta64(2, 'D')print("before_2_day : ", before_2_day) # for after_2_dayafter_2_day = np.datetime64('today', 'D')+ np.timedelta64(2, 'D') print("after_2_day :", after_2_day)
Output:
Today: 2020-08-15
before_2_day : 2020-08-13
after_2_day : 2020-08-17
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24292,
"s": 23901,
"text": "In NumPy with the help of NumPy.datetime64(‘today’, ‘D’), we will find today date and if we want some date before today then we will subtract the no-of-date with the help of np.timedelta64() from today. And if we want some date after today then we will add the no of date with the help of np.timedelta64() from today. For yesterday, we will subtract 1 date, for tomorrow we will add 1 date."
},
{
"code": null,
"e": 24350,
"s": 24292,
"text": "Example #1: Get the dates yesterday, today, and tomorrow."
},
{
"code": null,
"e": 24358,
"s": 24350,
"text": "Python3"
},
{
"code": "import numpy as np # for todaytoday = np.datetime64('today', 'D')print(\"Today: \", today) # for yesterdayyesterday = np.datetime64('today', 'D')- np.timedelta64(1, 'D') print(\"Yestraday: \", yesterday) # for tomorrowtomorrow = np.datetime64('today', 'D')+ np.timedelta64(1, 'D') print(\"Tomorrow: \", tomorrow)",
"e": 24670,
"s": 24358,
"text": null
},
{
"code": null,
"e": 24678,
"s": 24670,
"text": "Output:"
},
{
"code": null,
"e": 24743,
"s": 24678,
"text": "Today: 2020-08-15\nYestraday: 2020-08-14\nTomorrow: 2020-08-16\n"
},
{
"code": null,
"e": 24786,
"s": 24743,
"text": "Example #2: Get the dates in the interval."
},
{
"code": null,
"e": 24794,
"s": 24786,
"text": "Python3"
},
{
"code": "import numpy as np # for todaytoday = np.datetime64('today', 'D')print(\"Today: \", today) # for before_2_daybefore_2_day = np.datetime64('today', 'D')- np.timedelta64(2, 'D')print(\"before_2_day : \", before_2_day) # for after_2_dayafter_2_day = np.datetime64('today', 'D')+ np.timedelta64(2, 'D') print(\"after_2_day :\", after_2_day)",
"e": 25129,
"s": 24794,
"text": null
},
{
"code": null,
"e": 25137,
"s": 25129,
"text": "Output:"
},
{
"code": null,
"e": 25209,
"s": 25137,
"text": "Today: 2020-08-15\nbefore_2_day : 2020-08-13\nafter_2_day : 2020-08-17\n"
},
{
"code": null,
"e": 25230,
"s": 25209,
"text": "Python numpy-program"
},
{
"code": null,
"e": 25243,
"s": 25230,
"text": "Python-numpy"
},
{
"code": null,
"e": 25250,
"s": 25243,
"text": "Python"
},
{
"code": null,
"e": 25348,
"s": 25250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25357,
"s": 25348,
"text": "Comments"
},
{
"code": null,
"e": 25370,
"s": 25357,
"text": "Old Comments"
},
{
"code": null,
"e": 25406,
"s": 25370,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 25445,
"s": 25406,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25468,
"s": 25445,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25519,
"s": 25468,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 25551,
"s": 25519,
"text": "Python Dictionary keys() method"
},
{
"code": null,
"e": 25567,
"s": 25551,
"text": "loops in python"
},
{
"code": null,
"e": 25608,
"s": 25567,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 25657,
"s": 25608,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 25690,
"s": 25657,
"text": "Python | Convert set into a list"
}
] |
Different Ways to Add Stacktrace or debug Option when Building Android Studio Project
|
19 Jun, 2021
While developing your favorite app, you might at some point of time arrived upon this strange error,
:GfGapp:processDebugResources FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processDebugResources'.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
Yes, and now you want to run with the –stacktrace option as the error log now shows!
Image 1. That error!
Go forward with this article and you’ll be up and running in no time.
This might be the easiest way to add the Stacktrace option in Android Studio, simply navigate to the files option and then you can add Stacktrace in place of command-line options and you are good to go.
File > Settings > Build, Execution, Deployment > Compiler
Image 2. The Compiler Settings Panel
You will get the same result as stated in method #1 above on a Mac. Only the names of certain settings are different.
Navigate to Android Studio -> Preferences-> Build, Execution, Deployment-> Compiler
The GUI Method
Note: To view the Compiler option in the newest versions of AS (2.2 and 2.3), exit the open project, go to AS begin (where the current projects are shown), and select Configure -> Preferences->Build, Execution,Deployment. Otherwise, the Compiler is hidden.
configurations.all {
resolutionStrategy {
force 'com.android.support:support-v4:27.0.0'
}
}
Adding the Configurations in the Gradle
./gradlew assembleMyBuild --stacktrace
If you’re a fan of the Android Studio terminal then this might turn to be the best one for you as this involves using the terminal to add the Stacktrace option and achieve the required result. Input the above statement in the Android Studio’s terminal and results will start popping.
The Android Studio’s Terminal
Just add this additional flag and you’re good to go!
gradle(
flags: "{--stacktrace}"
)
And that’s how you just managed to run stacktrace option!
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Introduction to Android Development
Activity Lifecycle in Android with Demo App
Fragment Lifecycle in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2021"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "While developing your favorite app, you might at some point of time arrived upon this strange error, "
},
{
"code": null,
"e": 402,
"s": 130,
"text": ":GfGapp:processDebugResources FAILED\n\nFAILURE: Build failed with an exception.\n* What went wrong:\nExecution failed for task ':app:processDebugResources'.\n* Try:\nRun with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output."
},
{
"code": null,
"e": 487,
"s": 402,
"text": "Yes, and now you want to run with the –stacktrace option as the error log now shows!"
},
{
"code": null,
"e": 508,
"s": 487,
"text": "Image 1. That error!"
},
{
"code": null,
"e": 579,
"s": 508,
"text": "Go forward with this article and you’ll be up and running in no time. "
},
{
"code": null,
"e": 782,
"s": 579,
"text": "This might be the easiest way to add the Stacktrace option in Android Studio, simply navigate to the files option and then you can add Stacktrace in place of command-line options and you are good to go."
},
{
"code": null,
"e": 840,
"s": 782,
"text": "File > Settings > Build, Execution, Deployment > Compiler"
},
{
"code": null,
"e": 877,
"s": 840,
"text": "Image 2. The Compiler Settings Panel"
},
{
"code": null,
"e": 995,
"s": 877,
"text": "You will get the same result as stated in method #1 above on a Mac. Only the names of certain settings are different."
},
{
"code": null,
"e": 1079,
"s": 995,
"text": "Navigate to Android Studio -> Preferences-> Build, Execution, Deployment-> Compiler"
},
{
"code": null,
"e": 1094,
"s": 1079,
"text": "The GUI Method"
},
{
"code": null,
"e": 1351,
"s": 1094,
"text": "Note: To view the Compiler option in the newest versions of AS (2.2 and 2.3), exit the open project, go to AS begin (where the current projects are shown), and select Configure -> Preferences->Build, Execution,Deployment. Otherwise, the Compiler is hidden."
},
{
"code": null,
"e": 1459,
"s": 1351,
"text": "configurations.all {\n resolutionStrategy {\n force 'com.android.support:support-v4:27.0.0'\n }\n}"
},
{
"code": null,
"e": 1499,
"s": 1459,
"text": "Adding the Configurations in the Gradle"
},
{
"code": null,
"e": 1538,
"s": 1499,
"text": "./gradlew assembleMyBuild --stacktrace"
},
{
"code": null,
"e": 1822,
"s": 1538,
"text": "If you’re a fan of the Android Studio terminal then this might turn to be the best one for you as this involves using the terminal to add the Stacktrace option and achieve the required result. Input the above statement in the Android Studio’s terminal and results will start popping."
},
{
"code": null,
"e": 1852,
"s": 1822,
"text": "The Android Studio’s Terminal"
},
{
"code": null,
"e": 1905,
"s": 1852,
"text": "Just add this additional flag and you’re good to go!"
},
{
"code": null,
"e": 1942,
"s": 1905,
"text": "gradle(\n flags: \"{--stacktrace}\"\n)"
},
{
"code": null,
"e": 2000,
"s": 1942,
"text": "And that’s how you just managed to run stacktrace option!"
},
{
"code": null,
"e": 2015,
"s": 2000,
"text": "Android-Studio"
},
{
"code": null,
"e": 2022,
"s": 2015,
"text": "Picked"
},
{
"code": null,
"e": 2030,
"s": 2022,
"text": "Android"
},
{
"code": null,
"e": 2038,
"s": 2030,
"text": "Android"
},
{
"code": null,
"e": 2136,
"s": 2038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2205,
"s": 2136,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 2237,
"s": 2205,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 2276,
"s": 2237,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 2325,
"s": 2276,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 2367,
"s": 2325,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 2418,
"s": 2367,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 2441,
"s": 2418,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 2477,
"s": 2441,
"text": "Introduction to Android Development"
},
{
"code": null,
"e": 2521,
"s": 2477,
"text": "Activity Lifecycle in Android with Demo App"
}
] |
Sum of previous numbers that are greater than current number for given array
|
11 Mar, 2022
Given an array A[], for each element in the array, the task is to find the sum of all the previous elements which are strictly greater than the current element.
Examples:
Input: A[] = {2, 6, 4, 1, 7}Output: 0 0 6 12 0Explanation: For 2 and 6 there is no element greater to it on the left.For 4 there is 6.For 1 the sum would be 12.For 7 there is again no element greater to it.
Input: A[] = {7, 3, 6, 2, 1}Output: 0 7 7 16 18Explanation: For 7 there is no element greater to it on the left. For 3 there is 7.For 6 the sum would be 7.For 2 it has to be 7 + 3 + 6 = 16.For 1 the sum would be 7 + 3 + 6 + 2 = 18
Naive Approach: For each element, the idea is to find the elements which are strictly greater than the current element on the left side of it and then find the sum of all those elements.
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; // Max Element of the Arrayconst int maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arrayvoid sumGreater(int ar[], int N){ // Loop to iterate over all // the elements of the array for (int i = 0; i < N; i++) { // Store the answer for // the current element int cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for (int j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element cout << cur_sum << " "; }} // Driver Codeint main(){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; // Size of the array int N = sizeof ar / sizeof ar[0]; // Function call sumGreater(ar, N); return 0;}
// Java program for the above approachclass GFG{ // Max Element of the Arraystatic int maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arraystatic void sumGreater(int ar[], int N){ // Loop to iterate over all // the elements of the array for(int i = 0; i < N; i++) { // Store the answer for // the current element int cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for(int j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element System.out.print(cur_sum + " "); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; // Size of the array int N = ar.length; // Function call sumGreater(ar, N);}} // This code is contributed by amal kumar choubey
# Python3 program for the above approach # Max Element of the Arraymaxn = 1000000; # Function to find the sum of previous# numbers that are greater than the# current number for the given arraydef sumGreater(ar, N): # Loop to iterate over all # the elements of the array for i in range(N): # Store the answer for # the current element cur_sum = 0; # Iterate from (current index - 1) # to 0 and check if ar[j] is greater # than the current element and add # it to the cur_sum if so for j in range(i, -1, -1): if (ar[j] > ar[i]): cur_sum += ar[j]; # Print the answer for # current element print(cur_sum, end = " "); # Driver Codeif __name__ == '__main__': # Given array arr ar = [ 7, 3, 6, 2, 1] ; # Size of the array N = len(ar); # Function call sumGreater(ar, N); # This code is contributed by sapnasingh4991
// C# program for the above approachusing System; class GFG{ // Max Element of the Array//static int maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arraystatic void sumGreater(int []ar, int N){ // Loop to iterate over all // the elements of the array for(int i = 0; i < N; i++) { // Store the answer for // the current element int cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for(int j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element Console.Write(cur_sum + " "); }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []ar = { 7, 3, 6, 2, 1 }; // Size of the array int N = ar.Length; // Function call sumGreater(ar, N);}} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach // Max Element of the Arrayvar maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arrayfunction sumGreater(ar, N){ // Loop to iterate over all // the elements of the array for(i = 0; i < N; i++) { // Store the answer for // the current element var cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for(j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element document.write(cur_sum + " "); }} // Driver Code // Given array arrvar ar = [ 7, 3, 6, 2, 1 ]; // Size of the arrayvar N = ar.length; // Function callsumGreater(ar, N); // This code is contributed by umadevi9616 </script>
0 7 7 16 18
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach the idea is to use Fenwick Tree. Below are the steps:
Traverse the given array and find the sum(say total_sum) of all the elements stored in the Fenwick Tree.Now Consider each element(say arr[i]) as the index of the Fenwick Tree.Now find the sum of all the elements(say curr_sum) which is smaller than the current element using values stored in Tree.The value of total_sum – curr_sum will give the sum of all elements which are strictly greater than the elements on the left side of the current element.Update the current element in the Fenwick Tree.Repeat the above steps for all the elements in the array.
Traverse the given array and find the sum(say total_sum) of all the elements stored in the Fenwick Tree.
Now Consider each element(say arr[i]) as the index of the Fenwick Tree.
Now find the sum of all the elements(say curr_sum) which is smaller than the current element using values stored in Tree.
The value of total_sum – curr_sum will give the sum of all elements which are strictly greater than the elements on the left side of the current element.
Update the current element in the Fenwick Tree.
Repeat the above steps for all the elements in the array.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Max Element of the Arrayconst int maxn = 1000000; // Initializing Fenwick Treeint Bit[maxn + 5]; // Function to calculate the sum of// previous numbers that are greater// than the current number in the arrayvoid sum(int ar[], int N){ // Iterate from 1 to N for (int i = 0; i < N; i++) { int index; int total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } int cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } int ans = total_sum - cur_sum; cout << ans << " "; // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } }} // Driver Codeint main(){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; int N = sizeof ar / sizeof ar[0]; // Function call sum(ar, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Max Element of the Arraystatic int maxn = 1000000; // Initializing Fenwick Treestatic int []Bit = new int[maxn + 5]; // Function to calculate the sum of// previous numbers that are greater// than the current number in the arraystatic void sum(int ar[], int N){ // Iterate from 1 to N for (int i = 0; i < N; i++) { int index; int total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index > 0) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } int cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index > 0) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } int ans = total_sum - cur_sum; System.out.print(ans + " "); // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; int N = ar.length; // Function call sum(ar, N);}} // This code is contributed by Rohit_ranjan
# Python3 program for the above approach # Max Element of the Arraymaxn = 1000000; # Initializing Fenwick TreeBit = [0] * (maxn + 5); # Function to calculate the sum of# previous numbers that are greater# than the current number in the arraydef sum(ar, N): # Iterate from 1 to N for i in range(N): total_sum = 0; index = 100000; # If some greater values has # occurred before current element # then it will be already stored # in Fenwick Tree while (index > 0): # Calculating sum of # all the elements total_sum += Bit[index]; index -= index & -index; cur_sum = 0; # Sum only smaller or equal # elements than current element index = ar[i]; while (index > 0): # If some smaller values has # occurred before it will be # already stored in Tree cur_sum += Bit[index]; index -= (index & -index); ans = total_sum - cur_sum; print(ans, end=" "); # Update the fenwick tree index = ar[i]; while (index <= 100000): # Updating The Fenwick Tree # for future values Bit[index] += ar[i]; index += (index & -index); # Driver Codeif __name__ == '__main__': # Given array arr arr = [7, 3, 6, 2, 1]; N = len(arr); # Function call sum(arr, N); # This code is contributed by sapnasingh4991
// C# program for the above approachusing System;class GFG{ // Max Element of the Arraystatic int maxn = 1000000; // Initializing Fenwick Treestatic int []Bit = new int[maxn + 5]; // Function to calculate the sum of// previous numbers that are greater// than the current number in the arraystatic void sum(int []ar, int N){ // Iterate from 1 to N for (int i = 0; i < N; i++) { int index; int total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index > 0) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } int cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index > 0) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } int ans = total_sum - cur_sum; Console.Write(ans + " "); // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []ar = { 7, 3, 6, 2, 1 }; int N = ar.Length; // Function call sum(ar, N);}} // This code is contributed by Rajput-Ji
<script>// javascript program for the above approach // Max Element of the Array var maxn = 1000000; // Initializing Fenwick Tree var Bit = Array(maxn + 5).fill(0); // Function to calculate the sum of // previous numbers that are greater // than the current number in the array function sum(ar , N) { // Iterate from 1 to N for (i = 0; i < N; i++) { var index; var total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index > 0) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } var cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index > 0) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } var ans = total_sum - cur_sum; document.write(ans + " "); // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } } } // Driver Code // Given array arr var ar = [ 7, 3, 6, 2, 1 ]; var N = ar.length; // Function call sum(ar, N); // This code contributed by aashish1995</script>
0 7 7 16 18
Time Complexity: O(N * log(max_element))Auxiliary Space: O(max_element)
Amal Kumar Choubey
amit143katiyar
Rohit_ranjan
Rajput-Ji
sapnasingh4991
umadevi9616
aashish1995
adnanirshad158
nikhatkhan11
sumitgumber28
Binary Indexed Tree
BIT
Segment-Tree
Arrays
Competitive Programming
Tree
Arrays
Tree
Binary Indexed Tree
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Mar, 2022"
},
{
"code": null,
"e": 189,
"s": 28,
"text": "Given an array A[], for each element in the array, the task is to find the sum of all the previous elements which are strictly greater than the current element."
},
{
"code": null,
"e": 199,
"s": 189,
"text": "Examples:"
},
{
"code": null,
"e": 406,
"s": 199,
"text": "Input: A[] = {2, 6, 4, 1, 7}Output: 0 0 6 12 0Explanation: For 2 and 6 there is no element greater to it on the left.For 4 there is 6.For 1 the sum would be 12.For 7 there is again no element greater to it."
},
{
"code": null,
"e": 637,
"s": 406,
"text": "Input: A[] = {7, 3, 6, 2, 1}Output: 0 7 7 16 18Explanation: For 7 there is no element greater to it on the left. For 3 there is 7.For 6 the sum would be 7.For 2 it has to be 7 + 3 + 6 = 16.For 1 the sum would be 7 + 3 + 6 + 2 = 18"
},
{
"code": null,
"e": 824,
"s": 637,
"text": "Naive Approach: For each element, the idea is to find the elements which are strictly greater than the current element on the left side of it and then find the sum of all those elements."
},
{
"code": null,
"e": 875,
"s": 824,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 879,
"s": 875,
"text": "C++"
},
{
"code": null,
"e": 884,
"s": 879,
"text": "Java"
},
{
"code": null,
"e": 892,
"s": 884,
"text": "Python3"
},
{
"code": null,
"e": 895,
"s": 892,
"text": "C#"
},
{
"code": null,
"e": 906,
"s": 895,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Max Element of the Arrayconst int maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arrayvoid sumGreater(int ar[], int N){ // Loop to iterate over all // the elements of the array for (int i = 0; i < N; i++) { // Store the answer for // the current element int cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for (int j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element cout << cur_sum << \" \"; }} // Driver Codeint main(){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; // Size of the array int N = sizeof ar / sizeof ar[0]; // Function call sumGreater(ar, N); return 0;}",
"e": 1949,
"s": 906,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Max Element of the Arraystatic int maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arraystatic void sumGreater(int ar[], int N){ // Loop to iterate over all // the elements of the array for(int i = 0; i < N; i++) { // Store the answer for // the current element int cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for(int j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element System.out.print(cur_sum + \" \"); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; // Size of the array int N = ar.length; // Function call sumGreater(ar, N);}} // This code is contributed by amal kumar choubey",
"e": 3050,
"s": 1949,
"text": null
},
{
"code": "# Python3 program for the above approach # Max Element of the Arraymaxn = 1000000; # Function to find the sum of previous# numbers that are greater than the# current number for the given arraydef sumGreater(ar, N): # Loop to iterate over all # the elements of the array for i in range(N): # Store the answer for # the current element cur_sum = 0; # Iterate from (current index - 1) # to 0 and check if ar[j] is greater # than the current element and add # it to the cur_sum if so for j in range(i, -1, -1): if (ar[j] > ar[i]): cur_sum += ar[j]; # Print the answer for # current element print(cur_sum, end = \" \"); # Driver Codeif __name__ == '__main__': # Given array arr ar = [ 7, 3, 6, 2, 1] ; # Size of the array N = len(ar); # Function call sumGreater(ar, N); # This code is contributed by sapnasingh4991",
"e": 4007,
"s": 3050,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Max Element of the Array//static int maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arraystatic void sumGreater(int []ar, int N){ // Loop to iterate over all // the elements of the array for(int i = 0; i < N; i++) { // Store the answer for // the current element int cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for(int j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element Console.Write(cur_sum + \" \"); }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []ar = { 7, 3, 6, 2, 1 }; // Size of the array int N = ar.Length; // Function call sumGreater(ar, N);}} // This code is contributed by Amit Katiyar",
"e": 5113,
"s": 4007,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Max Element of the Arrayvar maxn = 1000000; // Function to find the sum of previous// numbers that are greater than the// current number for the given arrayfunction sumGreater(ar, N){ // Loop to iterate over all // the elements of the array for(i = 0; i < N; i++) { // Store the answer for // the current element var cur_sum = 0; // Iterate from (current index - 1) // to 0 and check if ar[j] is greater // than the current element and add // it to the cur_sum if so for(j = i - 1; j >= 0; j--) { if (ar[j] > ar[i]) cur_sum += ar[j]; } // Print the answer for // current element document.write(cur_sum + \" \"); }} // Driver Code // Given array arrvar ar = [ 7, 3, 6, 2, 1 ]; // Size of the arrayvar N = ar.length; // Function callsumGreater(ar, N); // This code is contributed by umadevi9616 </script>",
"e": 6121,
"s": 5113,
"text": null
},
{
"code": null,
"e": 6133,
"s": 6121,
"text": "0 7 7 16 18"
},
{
"code": null,
"e": 6179,
"s": 6135,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6284,
"s": 6179,
"text": "Efficient Approach: To optimize the above approach the idea is to use Fenwick Tree. Below are the steps:"
},
{
"code": null,
"e": 6838,
"s": 6284,
"text": "Traverse the given array and find the sum(say total_sum) of all the elements stored in the Fenwick Tree.Now Consider each element(say arr[i]) as the index of the Fenwick Tree.Now find the sum of all the elements(say curr_sum) which is smaller than the current element using values stored in Tree.The value of total_sum – curr_sum will give the sum of all elements which are strictly greater than the elements on the left side of the current element.Update the current element in the Fenwick Tree.Repeat the above steps for all the elements in the array."
},
{
"code": null,
"e": 6943,
"s": 6838,
"text": "Traverse the given array and find the sum(say total_sum) of all the elements stored in the Fenwick Tree."
},
{
"code": null,
"e": 7015,
"s": 6943,
"text": "Now Consider each element(say arr[i]) as the index of the Fenwick Tree."
},
{
"code": null,
"e": 7137,
"s": 7015,
"text": "Now find the sum of all the elements(say curr_sum) which is smaller than the current element using values stored in Tree."
},
{
"code": null,
"e": 7291,
"s": 7137,
"text": "The value of total_sum – curr_sum will give the sum of all elements which are strictly greater than the elements on the left side of the current element."
},
{
"code": null,
"e": 7339,
"s": 7291,
"text": "Update the current element in the Fenwick Tree."
},
{
"code": null,
"e": 7397,
"s": 7339,
"text": "Repeat the above steps for all the elements in the array."
},
{
"code": null,
"e": 7448,
"s": 7397,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 7452,
"s": 7448,
"text": "C++"
},
{
"code": null,
"e": 7457,
"s": 7452,
"text": "Java"
},
{
"code": null,
"e": 7465,
"s": 7457,
"text": "Python3"
},
{
"code": null,
"e": 7468,
"s": 7465,
"text": "C#"
},
{
"code": null,
"e": 7479,
"s": 7468,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Max Element of the Arrayconst int maxn = 1000000; // Initializing Fenwick Treeint Bit[maxn + 5]; // Function to calculate the sum of// previous numbers that are greater// than the current number in the arrayvoid sum(int ar[], int N){ // Iterate from 1 to N for (int i = 0; i < N; i++) { int index; int total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } int cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } int ans = total_sum - cur_sum; cout << ans << \" \"; // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } }} // Driver Codeint main(){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; int N = sizeof ar / sizeof ar[0]; // Function call sum(ar, N); return 0;}",
"e": 9073,
"s": 7479,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Max Element of the Arraystatic int maxn = 1000000; // Initializing Fenwick Treestatic int []Bit = new int[maxn + 5]; // Function to calculate the sum of// previous numbers that are greater// than the current number in the arraystatic void sum(int ar[], int N){ // Iterate from 1 to N for (int i = 0; i < N; i++) { int index; int total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index > 0) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } int cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index > 0) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } int ans = total_sum - cur_sum; System.out.print(ans + \" \"); // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int ar[] = { 7, 3, 6, 2, 1 }; int N = ar.length; // Function call sum(ar, N);}} // This code is contributed by Rohit_ranjan",
"e": 10766,
"s": 9073,
"text": null
},
{
"code": "# Python3 program for the above approach # Max Element of the Arraymaxn = 1000000; # Initializing Fenwick TreeBit = [0] * (maxn + 5); # Function to calculate the sum of# previous numbers that are greater# than the current number in the arraydef sum(ar, N): # Iterate from 1 to N for i in range(N): total_sum = 0; index = 100000; # If some greater values has # occurred before current element # then it will be already stored # in Fenwick Tree while (index > 0): # Calculating sum of # all the elements total_sum += Bit[index]; index -= index & -index; cur_sum = 0; # Sum only smaller or equal # elements than current element index = ar[i]; while (index > 0): # If some smaller values has # occurred before it will be # already stored in Tree cur_sum += Bit[index]; index -= (index & -index); ans = total_sum - cur_sum; print(ans, end=\" \"); # Update the fenwick tree index = ar[i]; while (index <= 100000): # Updating The Fenwick Tree # for future values Bit[index] += ar[i]; index += (index & -index); # Driver Codeif __name__ == '__main__': # Given array arr arr = [7, 3, 6, 2, 1]; N = len(arr); # Function call sum(arr, N); # This code is contributed by sapnasingh4991",
"e": 12263,
"s": 10766,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Max Element of the Arraystatic int maxn = 1000000; // Initializing Fenwick Treestatic int []Bit = new int[maxn + 5]; // Function to calculate the sum of// previous numbers that are greater// than the current number in the arraystatic void sum(int []ar, int N){ // Iterate from 1 to N for (int i = 0; i < N; i++) { int index; int total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index > 0) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } int cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index > 0) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } int ans = total_sum - cur_sum; Console.Write(ans + \" \"); // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []ar = { 7, 3, 6, 2, 1 }; int N = ar.Length; // Function call sum(ar, N);}} // This code is contributed by Rajput-Ji",
"e": 13942,
"s": 12263,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Max Element of the Array var maxn = 1000000; // Initializing Fenwick Tree var Bit = Array(maxn + 5).fill(0); // Function to calculate the sum of // previous numbers that are greater // than the current number in the array function sum(ar , N) { // Iterate from 1 to N for (i = 0; i < N; i++) { var index; var total_sum = 0; index = 100000; // If some greater values has // occurred before current element // then it will be already stored // in Fenwick Tree while (index > 0) { // Calculating sum of // all the elements total_sum += Bit[index]; index -= index & -index; } var cur_sum = 0; // Sum only smaller or equal // elements than current element index = ar[i]; while (index > 0) { // If some smaller values has // occurred before it will be // already stored in Tree cur_sum += Bit[index]; index -= (index & -index); } var ans = total_sum - cur_sum; document.write(ans + \" \"); // Update the fenwick tree index = ar[i]; while (index <= 100000) { // Updating The Fenwick Tree // for future values Bit[index] += ar[i]; index += (index & -index); } } } // Driver Code // Given array arr var ar = [ 7, 3, 6, 2, 1 ]; var N = ar.length; // Function call sum(ar, N); // This code contributed by aashish1995</script>",
"e": 15743,
"s": 13942,
"text": null
},
{
"code": null,
"e": 15755,
"s": 15743,
"text": "0 7 7 16 18"
},
{
"code": null,
"e": 15829,
"s": 15757,
"text": "Time Complexity: O(N * log(max_element))Auxiliary Space: O(max_element)"
},
{
"code": null,
"e": 15850,
"s": 15831,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 15865,
"s": 15850,
"text": "amit143katiyar"
},
{
"code": null,
"e": 15878,
"s": 15865,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 15888,
"s": 15878,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15903,
"s": 15888,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 15915,
"s": 15903,
"text": "umadevi9616"
},
{
"code": null,
"e": 15927,
"s": 15915,
"text": "aashish1995"
},
{
"code": null,
"e": 15942,
"s": 15927,
"text": "adnanirshad158"
},
{
"code": null,
"e": 15955,
"s": 15942,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 15969,
"s": 15955,
"text": "sumitgumber28"
},
{
"code": null,
"e": 15989,
"s": 15969,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 15993,
"s": 15989,
"text": "BIT"
},
{
"code": null,
"e": 16006,
"s": 15993,
"text": "Segment-Tree"
},
{
"code": null,
"e": 16013,
"s": 16006,
"text": "Arrays"
},
{
"code": null,
"e": 16037,
"s": 16013,
"text": "Competitive Programming"
},
{
"code": null,
"e": 16042,
"s": 16037,
"text": "Tree"
},
{
"code": null,
"e": 16049,
"s": 16042,
"text": "Arrays"
},
{
"code": null,
"e": 16054,
"s": 16049,
"text": "Tree"
},
{
"code": null,
"e": 16074,
"s": 16054,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 16087,
"s": 16074,
"text": "Segment-Tree"
},
{
"code": null,
"e": 16185,
"s": 16087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16253,
"s": 16185,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 16297,
"s": 16253,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 16329,
"s": 16297,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 16377,
"s": 16329,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 16391,
"s": 16377,
"text": "Linear Search"
},
{
"code": null,
"e": 16434,
"s": 16391,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 16477,
"s": 16434,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 16518,
"s": 16477,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 16545,
"s": 16518,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Basics of Python
|
10 Jun, 2022
Introduction to Python has been dealt with in this article. Now, let us begin with learning python.
Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing a python code and running it. Please make sure that python is installed on the system you are working on. If it is not installed, download it from here. We will be using python 2.7.
Making a Python file: Python files are stored with the extension “.py”. Open a text editor and save a file with the name “hello.py”. Open it and write the following code:
Python3
print ("Hello World")# Notice that NO semi-colon is to be used
Reading the file contents: Linux System – Move to the directory from the terminal where the created file (hello.py) is stored by using the ‘cd’ command and then type the following in the terminal :
python hello.py
Windows system – Open command prompt and move to the directory where the file is stored by using the ‘cd’ command and then run the file by writing the file name as a command.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Variables in Python Variables need not be declared first in python. They can be used directly. Variables in python are case-sensitive as most of the other programming languages.
Example:
Python3
a = 3A = 4print (a)print (A)
The output is :
3
4
Expressions in Python Arithmetic operations in python can be performed by using arithmetic operators and some of the in-built functions.
Python3
a = 2b = 3c = a + bprint (c)d = a * bprint (d)
The output is :
5
6
Conditions in Python Conditional output in python can be obtained by using if-else and elif (else if) statements.
Python3
a = 3b = 9if b % a == 0 : print ("b is divisible by a")elif b + 1 == 10: print ("Increment in b produces 10")else: print ("You are in else statement")
The output is :
b is divisible by a
Functions in Python A function in python is declared by the keyword ‘def’ before the name of the function. The return type of the function need not be specified explicitly in python. The function can be invoked by writing the function name followed by the parameter list in the brackets.
Python3
# Function for checking the divisibility# Notice the indentation after function declaration# and if and else statementsdef checkDivisibility(a, b): if a % b == 0 : print ("a is divisible by b") else: print ("a is not divisible by b")#Driver program to test the above functioncheckDivisibility(4, 2)
The output is :
a is divisible by b
So, python is a very simplified and less cumbersome language to code in. This easiness of python is itself promoting its wide use.
https://www.youtube.com/watch?v=gzDPuWKjmGQ
Next Article- Python Data Types
Quiz – Functions in Python
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
amartyaghoshgfg
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Interfaces in Java
Object Oriented Programming in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 152,
"s": 52,
"text": "Introduction to Python has been dealt with in this article. Now, let us begin with learning python."
},
{
"code": null,
"e": 459,
"s": 152,
"text": "Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing a python code and running it. Please make sure that python is installed on the system you are working on. If it is not installed, download it from here. We will be using python 2.7."
},
{
"code": null,
"e": 630,
"s": 459,
"text": "Making a Python file: Python files are stored with the extension “.py”. Open a text editor and save a file with the name “hello.py”. Open it and write the following code:"
},
{
"code": null,
"e": 638,
"s": 630,
"text": "Python3"
},
{
"code": "print (\"Hello World\")# Notice that NO semi-colon is to be used",
"e": 701,
"s": 638,
"text": null
},
{
"code": null,
"e": 900,
"s": 701,
"text": "Reading the file contents: Linux System – Move to the directory from the terminal where the created file (hello.py) is stored by using the ‘cd’ command and then type the following in the terminal : "
},
{
"code": null,
"e": 916,
"s": 900,
"text": "python hello.py"
},
{
"code": null,
"e": 1091,
"s": 916,
"text": "Windows system – Open command prompt and move to the directory where the file is stored by using the ‘cd’ command and then run the file by writing the file name as a command."
},
{
"code": null,
"e": 1100,
"s": 1091,
"text": "Chapters"
},
{
"code": null,
"e": 1127,
"s": 1100,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1177,
"s": 1127,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1200,
"s": 1177,
"text": "captions off, selected"
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "English"
},
{
"code": null,
"e": 1232,
"s": 1208,
"text": "This is a modal window."
},
{
"code": null,
"e": 1301,
"s": 1232,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1323,
"s": 1301,
"text": "End of dialog window."
},
{
"code": null,
"e": 1502,
"s": 1323,
"text": "Variables in Python Variables need not be declared first in python. They can be used directly. Variables in python are case-sensitive as most of the other programming languages. "
},
{
"code": null,
"e": 1512,
"s": 1502,
"text": "Example: "
},
{
"code": null,
"e": 1520,
"s": 1512,
"text": "Python3"
},
{
"code": "a = 3A = 4print (a)print (A)",
"e": 1549,
"s": 1520,
"text": null
},
{
"code": null,
"e": 1566,
"s": 1549,
"text": "The output is : "
},
{
"code": null,
"e": 1570,
"s": 1566,
"text": "3\n4"
},
{
"code": null,
"e": 1708,
"s": 1570,
"text": "Expressions in Python Arithmetic operations in python can be performed by using arithmetic operators and some of the in-built functions. "
},
{
"code": null,
"e": 1716,
"s": 1708,
"text": "Python3"
},
{
"code": "a = 2b = 3c = a + bprint (c)d = a * bprint (d)",
"e": 1763,
"s": 1716,
"text": null
},
{
"code": null,
"e": 1780,
"s": 1763,
"text": "The output is : "
},
{
"code": null,
"e": 1784,
"s": 1780,
"text": "5\n6"
},
{
"code": null,
"e": 1899,
"s": 1784,
"text": "Conditions in Python Conditional output in python can be obtained by using if-else and elif (else if) statements. "
},
{
"code": null,
"e": 1907,
"s": 1899,
"text": "Python3"
},
{
"code": "a = 3b = 9if b % a == 0 : print (\"b is divisible by a\")elif b + 1 == 10: print (\"Increment in b produces 10\")else: print (\"You are in else statement\")",
"e": 2067,
"s": 1907,
"text": null
},
{
"code": null,
"e": 2084,
"s": 2067,
"text": "The output is : "
},
{
"code": null,
"e": 2104,
"s": 2084,
"text": "b is divisible by a"
},
{
"code": null,
"e": 2393,
"s": 2104,
"text": "Functions in Python A function in python is declared by the keyword ‘def’ before the name of the function. The return type of the function need not be specified explicitly in python. The function can be invoked by writing the function name followed by the parameter list in the brackets. "
},
{
"code": null,
"e": 2401,
"s": 2393,
"text": "Python3"
},
{
"code": "# Function for checking the divisibility# Notice the indentation after function declaration# and if and else statementsdef checkDivisibility(a, b): if a % b == 0 : print (\"a is divisible by b\") else: print (\"a is not divisible by b\")#Driver program to test the above functioncheckDivisibility(4, 2)",
"e": 2720,
"s": 2401,
"text": null
},
{
"code": null,
"e": 2737,
"s": 2720,
"text": "The output is : "
},
{
"code": null,
"e": 2757,
"s": 2737,
"text": "a is divisible by b"
},
{
"code": null,
"e": 2888,
"s": 2757,
"text": "So, python is a very simplified and less cumbersome language to code in. This easiness of python is itself promoting its wide use."
},
{
"code": null,
"e": 2932,
"s": 2888,
"text": "https://www.youtube.com/watch?v=gzDPuWKjmGQ"
},
{
"code": null,
"e": 2964,
"s": 2932,
"text": "Next Article- Python Data Types"
},
{
"code": null,
"e": 2991,
"s": 2964,
"text": "Quiz – Functions in Python"
},
{
"code": null,
"e": 3032,
"s": 2991,
"text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g"
},
{
"code": null,
"e": 3048,
"s": 3032,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 3055,
"s": 3048,
"text": "Python"
},
{
"code": null,
"e": 3074,
"s": 3055,
"text": "School Programming"
},
{
"code": null,
"e": 3172,
"s": 3074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3200,
"s": 3172,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3222,
"s": 3200,
"text": "Python map() function"
},
{
"code": null,
"e": 3272,
"s": 3222,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3290,
"s": 3272,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3334,
"s": 3290,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3352,
"s": 3334,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3377,
"s": 3352,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3393,
"s": 3377,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 3412,
"s": 3393,
"text": "Interfaces in Java"
}
] |
Remove comments from a given C/C++ program
|
23 Jun, 2022
Given a C/C++ program, remove comments from it.
We strongly recommend to minimize your browser and try this yourself first.
The idea is to maintain two flag variables, one to indicate that a single line comment is started, another to indicate that a multiline comment is started. When a flag is set, we look for the end of comment and ignore all characters between start and end.
Following is C++ implementation of above idea.
C++
// C++ program to remove comments from a C/C++ program#include <iostream>using namespace std; string removeComments(string prgm){ int n = prgm.length(); string res; // Flags to indicate that single line and multiple line comments // have started or not. bool s_cmt = false; bool m_cmt = false; // Traverse the given program for (int i=0; i<n; i++) { // If single line comment flag is on, then check for end of it if (s_cmt == true && prgm[i] == '\n') s_cmt = false; // If multiple line comment is on, then check for end of it else if (m_cmt == true && prgm[i] == '*' && prgm[i+1] == '/') m_cmt = false, i++; // If this character is in a comment, ignore it else if (s_cmt || m_cmt) continue; // Check for beginning of comments and set the appropriate flags else if (prgm[i] == '/' && prgm[i+1] == '/') s_cmt = true, i++; else if (prgm[i] == '/' && prgm[i+1] == '*') m_cmt = true, i++; // If current character is a non-comment character, append it to res else res += prgm[i]; } return res;} // Driver program to test above functionsint main(){ string prgm = " /* Test program */ \n" " int main() \n" " { \n" " // variable declaration \n" " int a, b, c; \n" " /* This is a test \n" " multiline \n" " comment for \n" " testing */ \n" " a = b + c; \n" " } \n"; cout << "Given Program \n"; cout << prgm << endl; cout << " Modified Program "; cout << removeComments(prgm); return 0;}
Given Program
/* Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
Modified Program
int main()
{
int a, b, c;
a = b + c;
}
simranarora5sos
hardikkoriintern
BrowserStack
C++
Strings
BrowserStack
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 101,
"s": 52,
"text": "Given a C/C++ program, remove comments from it. "
},
{
"code": null,
"e": 177,
"s": 101,
"text": "We strongly recommend to minimize your browser and try this yourself first."
},
{
"code": null,
"e": 433,
"s": 177,
"text": "The idea is to maintain two flag variables, one to indicate that a single line comment is started, another to indicate that a multiline comment is started. When a flag is set, we look for the end of comment and ignore all characters between start and end."
},
{
"code": null,
"e": 480,
"s": 433,
"text": "Following is C++ implementation of above idea."
},
{
"code": null,
"e": 484,
"s": 480,
"text": "C++"
},
{
"code": "// C++ program to remove comments from a C/C++ program#include <iostream>using namespace std; string removeComments(string prgm){ int n = prgm.length(); string res; // Flags to indicate that single line and multiple line comments // have started or not. bool s_cmt = false; bool m_cmt = false; // Traverse the given program for (int i=0; i<n; i++) { // If single line comment flag is on, then check for end of it if (s_cmt == true && prgm[i] == '\\n') s_cmt = false; // If multiple line comment is on, then check for end of it else if (m_cmt == true && prgm[i] == '*' && prgm[i+1] == '/') m_cmt = false, i++; // If this character is in a comment, ignore it else if (s_cmt || m_cmt) continue; // Check for beginning of comments and set the appropriate flags else if (prgm[i] == '/' && prgm[i+1] == '/') s_cmt = true, i++; else if (prgm[i] == '/' && prgm[i+1] == '*') m_cmt = true, i++; // If current character is a non-comment character, append it to res else res += prgm[i]; } return res;} // Driver program to test above functionsint main(){ string prgm = \" /* Test program */ \\n\" \" int main() \\n\" \" { \\n\" \" // variable declaration \\n\" \" int a, b, c; \\n\" \" /* This is a test \\n\" \" multiline \\n\" \" comment for \\n\" \" testing */ \\n\" \" a = b + c; \\n\" \" } \\n\"; cout << \"Given Program \\n\"; cout << prgm << endl; cout << \" Modified Program \"; cout << removeComments(prgm); return 0;}",
"e": 2322,
"s": 484,
"text": null
},
{
"code": null,
"e": 2728,
"s": 2322,
"text": "Given Program \n /* Test program */ \n int main() \n { \n // variable declaration \n int a, b, c; \n /* This is a test \n multiline \n comment for \n testing */ \n a = b + c; \n } \n\n Modified Program \n int main() \n { \n int a, b, c; \n \n a = b + c; \n } \n"
},
{
"code": null,
"e": 2744,
"s": 2728,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2761,
"s": 2744,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 2774,
"s": 2761,
"text": "BrowserStack"
},
{
"code": null,
"e": 2778,
"s": 2774,
"text": "C++"
},
{
"code": null,
"e": 2786,
"s": 2778,
"text": "Strings"
},
{
"code": null,
"e": 2799,
"s": 2786,
"text": "BrowserStack"
},
{
"code": null,
"e": 2807,
"s": 2799,
"text": "Strings"
},
{
"code": null,
"e": 2811,
"s": 2807,
"text": "CPP"
},
{
"code": null,
"e": 2909,
"s": 2811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2963,
"s": 2909,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3006,
"s": 2963,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3040,
"s": 3006,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 3057,
"s": 3040,
"text": "Substring in C++"
},
{
"code": null,
"e": 3082,
"s": 3057,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 3128,
"s": 3082,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 3153,
"s": 3128,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 3213,
"s": 3153,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 3228,
"s": 3213,
"text": "C++ Data Types"
}
] |
Print Longest substring without repeating characters
|
05 Jul, 2021
Given a string, print the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. The desired time complexity is O(n) where n is the length of the string.Prerequisite: Length of longest substring without repeating charactersExamples:
Input : GEEKSFORGEEKS
Output : EKSFORG
Input : ABDEFGABEF
Output : BDEFGA
Approach: The idea is to traverse the string and for each already visited character store its last occurrence in a hash table(Here unordered_map is used as a hash with key as character and value as its last position). The variable st stores the starting point of the current substring, maxlen stores the length of maximum length substring, and start stores the starting index of maximum length substring. While traversing the string, check whether the current character is present in the hash table or not. If it is not present, then store the current character in the hash table with value as the current index. If it is already present in the hash table, this means the current character could repeat in the current substring. For this check, if the previous occurrence of character is before or after the starting point st of the current substring. If it is before st, then only update the value in the hash table. If it is after st, then find the length of current substring currlen as i-st, where i is the current index. Compare currlen with maxlen. If maxlen is less than currlen, then update maxlen as currlen and start as st. After complete traversal of the string, the required the longest substring without repeating characters is from s[start] to s[start+maxlen-1]. Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find and print longest// substring without repeating characters.#include <bits/stdc++.h> using namespace std; // Function to find and print longest// substring without repeating characters.string findLongestSubstring(string str){ int i; int n = str.length(); // starting point of current substring. int st = 0; // length of current substring. int currlen; // maximum length substring without repeating // characters. int maxlen = 0; // starting index of maximum length substring. int start; // Hash Map to store last occurrence of each // already visited character. unordered_map<char, int> pos; // Last occurrence of first character is index 0; pos[str[0]] = 0; for (i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (pos.find(str[i]) == pos.end()) pos[str[i]] = i; else { // If this character is present in hash then // this character has previous occurrence, // check if that occurrence is before or after // starting point of current substring. if (pos[str[i]] >= st) { // find length of current substring and // update maxlen and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start after the last // occurrence of current character to avoid // its repetition. st = pos[str[i]] + 1; } // Update last occurrence of // current character. pos[str[i]] = i; } } // Compare length of last substring with maxlen and // update maxlen and start accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest substring without // repeating characters is from str[start] // to str[start+maxlen-1]. return str.substr(start, maxlen);} // Driver functionint main(){ string str = "GEEKSFORGEEKS"; cout << findLongestSubstring(str); return 0;}
// Java program to find// and print longest substring// without repeating characters.import java.util.*;class GFG{ // Function to find and print longest// substring without repeating characters.public static String findLongestSubstring(String str){ int i; int n = str.length(); // Starting point // of current substring. int st = 0; // length of // current substring. int currlen = 0; // maximum length // substring without // repeating characters. int maxlen = 0; // starting index of // maximum length substring. int start = 0; // Hash Map to store last // occurrence of each // already visited character. HashMap<Character, Integer> pos = new HashMap<Character, Integer>(); // Last occurrence of first // character is index 0; pos.put(str.charAt(0), 0); for (i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (!pos.containsKey(str.charAt(i))) { pos.put(str.charAt(i), i); } else { // If this character is present // in hash then this character // has previous occurrence, // check if that occurrence // is before or after starting // point of current substring. if (pos.get(str.charAt(i)) >= st) { // find length of current // substring and update maxlen // and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start // after the last occurrence // of current character to avoid // its repetition. st = pos.get(str.charAt(i)) + 1; } // Update last occurrence of // current character. pos.replace(str.charAt(i), i); } } // Compare length of last // substring with maxlen and // update maxlen and start // accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest // substring without // repeating characters // is from str[start] // to str[start+maxlen-1]. return str.substring(start, start + maxlen);} // Driver Codepublic static void main(String[] args){ String str = "GEEKSFORGEEKS"; System.out.print(findLongestSubstring(str));}} // This code is contributed by divyeshrabadiya07
# Python3 program to find and print longest# substring without repeating characters. # Function to find and print longest# substring without repeating characters.def findLongestSubstring(string): n = len(string) # starting point of current substring. st = 0 # maximum length substring without # repeating characters. maxlen = 0 # starting index of maximum # length substring. start = 0 # Hash Map to store last occurrence # of each already visited character. pos = {} # Last occurrence of first # character is index 0 pos[string[0]] = 0 for i in range(1, n): # If this character is not present in hash, # then this is first occurrence of this # character, store this in hash. if string[i] not in pos: pos[string[i]] = i else: # If this character is present in hash then # this character has previous occurrence, # check if that occurrence is before or after # starting point of current substring. if pos[string[i]] >= st: # find length of current substring and # update maxlen and start accordingly. currlen = i - st if maxlen < currlen: maxlen = currlen start = st # Next substring will start after the last # occurrence of current character to avoid # its repetition. st = pos[string[i]] + 1 # Update last occurrence of # current character. pos[string[i]] = i # Compare length of last substring with maxlen # and update maxlen and start accordingly. if maxlen < i - st: maxlen = i - st start = st # The required longest substring without # repeating characters is from string[start] # to string[start+maxlen-1]. return string[start : start + maxlen] # Driver Codeif __name__ == "__main__": string = "GEEKSFORGEEKS" print(findLongestSubstring(string)) # This code is contributed by Rituraj Jain
// C# program to find// and print longest substring// without repeating characters.using System;using System.Collections.Generic;class GFG{ // Function to find and// print longest substring// without repeating characters.public static String findlongestSubstring(String str){ int i; int n = str.Length; // Starting point // of current substring. int st = 0; // length of // current substring. int currlen = 0; // maximum length // substring without // repeating characters. int maxlen = 0; // starting index of // maximum length substring. int start = 0; // Hash Map to store last // occurrence of each // already visited character. Dictionary<char, int> pos = new Dictionary<char, int>(); // Last occurrence of first // character is index 0; pos.Add(str[0], 0); for (i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (!pos.ContainsKey(str[i])) { pos.Add(str[i], i); } else { // If this character is present // in hash then this character // has previous occurrence, // check if that occurrence // is before or after starting // point of current substring. if (pos[str[i]] >= st) { // find length of current // substring and update maxlen // and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start // after the last occurrence // of current character to avoid // its repetition. st = pos[str[i]] + 1; } // Update last occurrence of // current character. pos[str[i]] = i; } } // Compare length of last // substring with maxlen and // update maxlen and start // accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest // substring without // repeating characters // is from str[start] // to str[start+maxlen-1]. return str.Substring(start, maxlen);} // Driver Codepublic static void Main(String[] args){ String str = "GEEKSFORGEEKS"; Console.Write(findlongestSubstring(str));}} // This code is contributed by shikhasingrajput
<script> // JavaScript program for the above approach // Function to find and print longest// substring without repeating characters.function findLongestSubstring(str){ var i; var n = str.length; // starting point of current substring. var st = 0; // length of current substring. var currlen; // maximum length substring without repeating // characters. var maxlen = 0; // starting index of maximum length substring. var start; // Hash Map to store last occurrence of each // already visited character. var pos = new Map(); // Last occurrence of first character is index 0; pos.set(str[0], 0); for (var i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (!pos.has(str[i])) pos.set(str[i],i) ; else { // If this character is present in hash then // this character has previous occurrence, // check if that occurrence is before or after // starting point of current substring. if (pos.get(str[i]) >= st) { // find length of current substring and // update maxlen and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start after the last // occurrence of current character to avoid // its repetition. st = pos.get(str[i]) + 1; } // Update last occurrence of // current character. pos.set(str[i], i); } } // Compare length of last substring with maxlen and // update maxlen and start accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest substring without // repeating characters is from str[start] // to str[start+maxlen-1]. return str.substr(start,maxlen);} var str = "GEEKSFORGEEKS";document.write(findLongestSubstring(str)); // This code is contributed by SoumikMondal </script>
Output:
EKSFORG
Time Complexity: O(n) Auxiliary Space: O(n)
rituraj_jain
divyeshrabadiya07
shikhasingrajput
SoumikMondal
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Jul, 2021"
},
{
"code": null,
"e": 461,
"s": 54,
"text": "Given a string, print the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1. The desired time complexity is O(n) where n is the length of the string.Prerequisite: Length of longest substring without repeating charactersExamples: "
},
{
"code": null,
"e": 540,
"s": 461,
"text": "Input : GEEKSFORGEEKS\nOutput : EKSFORG\n\nInput : ABDEFGABEF\nOutput : BDEFGA\n\n\n "
},
{
"code": null,
"e": 1835,
"s": 540,
"text": "Approach: The idea is to traverse the string and for each already visited character store its last occurrence in a hash table(Here unordered_map is used as a hash with key as character and value as its last position). The variable st stores the starting point of the current substring, maxlen stores the length of maximum length substring, and start stores the starting index of maximum length substring. While traversing the string, check whether the current character is present in the hash table or not. If it is not present, then store the current character in the hash table with value as the current index. If it is already present in the hash table, this means the current character could repeat in the current substring. For this check, if the previous occurrence of character is before or after the starting point st of the current substring. If it is before st, then only update the value in the hash table. If it is after st, then find the length of current substring currlen as i-st, where i is the current index. Compare currlen with maxlen. If maxlen is less than currlen, then update maxlen as currlen and start as st. After complete traversal of the string, the required the longest substring without repeating characters is from s[start] to s[start+maxlen-1]. Implementation: "
},
{
"code": null,
"e": 1839,
"s": 1835,
"text": "C++"
},
{
"code": null,
"e": 1844,
"s": 1839,
"text": "Java"
},
{
"code": null,
"e": 1852,
"s": 1844,
"text": "Python3"
},
{
"code": null,
"e": 1855,
"s": 1852,
"text": "C#"
},
{
"code": null,
"e": 1866,
"s": 1855,
"text": "Javascript"
},
{
"code": "// C++ program to find and print longest// substring without repeating characters.#include <bits/stdc++.h> using namespace std; // Function to find and print longest// substring without repeating characters.string findLongestSubstring(string str){ int i; int n = str.length(); // starting point of current substring. int st = 0; // length of current substring. int currlen; // maximum length substring without repeating // characters. int maxlen = 0; // starting index of maximum length substring. int start; // Hash Map to store last occurrence of each // already visited character. unordered_map<char, int> pos; // Last occurrence of first character is index 0; pos[str[0]] = 0; for (i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (pos.find(str[i]) == pos.end()) pos[str[i]] = i; else { // If this character is present in hash then // this character has previous occurrence, // check if that occurrence is before or after // starting point of current substring. if (pos[str[i]] >= st) { // find length of current substring and // update maxlen and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start after the last // occurrence of current character to avoid // its repetition. st = pos[str[i]] + 1; } // Update last occurrence of // current character. pos[str[i]] = i; } } // Compare length of last substring with maxlen and // update maxlen and start accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest substring without // repeating characters is from str[start] // to str[start+maxlen-1]. return str.substr(start, maxlen);} // Driver functionint main(){ string str = \"GEEKSFORGEEKS\"; cout << findLongestSubstring(str); return 0;}",
"e": 4148,
"s": 1866,
"text": null
},
{
"code": "// Java program to find// and print longest substring// without repeating characters.import java.util.*;class GFG{ // Function to find and print longest// substring without repeating characters.public static String findLongestSubstring(String str){ int i; int n = str.length(); // Starting point // of current substring. int st = 0; // length of // current substring. int currlen = 0; // maximum length // substring without // repeating characters. int maxlen = 0; // starting index of // maximum length substring. int start = 0; // Hash Map to store last // occurrence of each // already visited character. HashMap<Character, Integer> pos = new HashMap<Character, Integer>(); // Last occurrence of first // character is index 0; pos.put(str.charAt(0), 0); for (i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (!pos.containsKey(str.charAt(i))) { pos.put(str.charAt(i), i); } else { // If this character is present // in hash then this character // has previous occurrence, // check if that occurrence // is before or after starting // point of current substring. if (pos.get(str.charAt(i)) >= st) { // find length of current // substring and update maxlen // and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start // after the last occurrence // of current character to avoid // its repetition. st = pos.get(str.charAt(i)) + 1; } // Update last occurrence of // current character. pos.replace(str.charAt(i), i); } } // Compare length of last // substring with maxlen and // update maxlen and start // accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest // substring without // repeating characters // is from str[start] // to str[start+maxlen-1]. return str.substring(start, start + maxlen);} // Driver Codepublic static void main(String[] args){ String str = \"GEEKSFORGEEKS\"; System.out.print(findLongestSubstring(str));}} // This code is contributed by divyeshrabadiya07",
"e": 6943,
"s": 4148,
"text": null
},
{
"code": "# Python3 program to find and print longest# substring without repeating characters. # Function to find and print longest# substring without repeating characters.def findLongestSubstring(string): n = len(string) # starting point of current substring. st = 0 # maximum length substring without # repeating characters. maxlen = 0 # starting index of maximum # length substring. start = 0 # Hash Map to store last occurrence # of each already visited character. pos = {} # Last occurrence of first # character is index 0 pos[string[0]] = 0 for i in range(1, n): # If this character is not present in hash, # then this is first occurrence of this # character, store this in hash. if string[i] not in pos: pos[string[i]] = i else: # If this character is present in hash then # this character has previous occurrence, # check if that occurrence is before or after # starting point of current substring. if pos[string[i]] >= st: # find length of current substring and # update maxlen and start accordingly. currlen = i - st if maxlen < currlen: maxlen = currlen start = st # Next substring will start after the last # occurrence of current character to avoid # its repetition. st = pos[string[i]] + 1 # Update last occurrence of # current character. pos[string[i]] = i # Compare length of last substring with maxlen # and update maxlen and start accordingly. if maxlen < i - st: maxlen = i - st start = st # The required longest substring without # repeating characters is from string[start] # to string[start+maxlen-1]. return string[start : start + maxlen] # Driver Codeif __name__ == \"__main__\": string = \"GEEKSFORGEEKS\" print(findLongestSubstring(string)) # This code is contributed by Rituraj Jain",
"e": 9059,
"s": 6943,
"text": null
},
{
"code": "// C# program to find// and print longest substring// without repeating characters.using System;using System.Collections.Generic;class GFG{ // Function to find and// print longest substring// without repeating characters.public static String findlongestSubstring(String str){ int i; int n = str.Length; // Starting point // of current substring. int st = 0; // length of // current substring. int currlen = 0; // maximum length // substring without // repeating characters. int maxlen = 0; // starting index of // maximum length substring. int start = 0; // Hash Map to store last // occurrence of each // already visited character. Dictionary<char, int> pos = new Dictionary<char, int>(); // Last occurrence of first // character is index 0; pos.Add(str[0], 0); for (i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (!pos.ContainsKey(str[i])) { pos.Add(str[i], i); } else { // If this character is present // in hash then this character // has previous occurrence, // check if that occurrence // is before or after starting // point of current substring. if (pos[str[i]] >= st) { // find length of current // substring and update maxlen // and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start // after the last occurrence // of current character to avoid // its repetition. st = pos[str[i]] + 1; } // Update last occurrence of // current character. pos[str[i]] = i; } } // Compare length of last // substring with maxlen and // update maxlen and start // accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest // substring without // repeating characters // is from str[start] // to str[start+maxlen-1]. return str.Substring(start, maxlen);} // Driver Codepublic static void Main(String[] args){ String str = \"GEEKSFORGEEKS\"; Console.Write(findlongestSubstring(str));}} // This code is contributed by shikhasingrajput",
"e": 11407,
"s": 9059,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find and print longest// substring without repeating characters.function findLongestSubstring(str){ var i; var n = str.length; // starting point of current substring. var st = 0; // length of current substring. var currlen; // maximum length substring without repeating // characters. var maxlen = 0; // starting index of maximum length substring. var start; // Hash Map to store last occurrence of each // already visited character. var pos = new Map(); // Last occurrence of first character is index 0; pos.set(str[0], 0); for (var i = 1; i < n; i++) { // If this character is not present in hash, // then this is first occurrence of this // character, store this in hash. if (!pos.has(str[i])) pos.set(str[i],i) ; else { // If this character is present in hash then // this character has previous occurrence, // check if that occurrence is before or after // starting point of current substring. if (pos.get(str[i]) >= st) { // find length of current substring and // update maxlen and start accordingly. currlen = i - st; if (maxlen < currlen) { maxlen = currlen; start = st; } // Next substring will start after the last // occurrence of current character to avoid // its repetition. st = pos.get(str[i]) + 1; } // Update last occurrence of // current character. pos.set(str[i], i); } } // Compare length of last substring with maxlen and // update maxlen and start accordingly. if (maxlen < i - st) { maxlen = i - st; start = st; } // The required longest substring without // repeating characters is from str[start] // to str[start+maxlen-1]. return str.substr(start,maxlen);} var str = \"GEEKSFORGEEKS\";document.write(findLongestSubstring(str)); // This code is contributed by SoumikMondal </script>",
"e": 13619,
"s": 11407,
"text": null
},
{
"code": null,
"e": 13629,
"s": 13619,
"text": "Output: "
},
{
"code": null,
"e": 13638,
"s": 13629,
"text": "EKSFORG "
},
{
"code": null,
"e": 13682,
"s": 13638,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 13695,
"s": 13682,
"text": "rituraj_jain"
},
{
"code": null,
"e": 13713,
"s": 13695,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 13730,
"s": 13713,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 13743,
"s": 13730,
"text": "SoumikMondal"
},
{
"code": null,
"e": 13748,
"s": 13743,
"text": "Hash"
},
{
"code": null,
"e": 13756,
"s": 13748,
"text": "Strings"
},
{
"code": null,
"e": 13761,
"s": 13756,
"text": "Hash"
},
{
"code": null,
"e": 13769,
"s": 13761,
"text": "Strings"
}
] |
Group all co-prime numbers from 1 to N
|
08 Nov, 2021
Given an integer N, the task is to group numbers such that each group is mutually co-prime together with the total grouping is minimum.
Examples:
Input: N = 8 Output: 1 2 3 4 5 6 7 8
Input: N = 5 Output: 1 2 3 4 5
Approach: The key observation in this problem is two consecutive numbers are always co-prime. That is GCD(a, a+1) = 1. Another important observation is even numbers can’t be listed in one group. Because they will lead to the greatest common divisor of 2. Therefore, every consecutive even and odd numbers can be grouped into one group and 1 can be in any group because the greatest common divisor of numbers with 1 is always 1.
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ implementation to group// mutually coprime numbers into// one group with minimum group possible#include<bits/stdc++.h>using namespace std; // Function to group the mutually// co-prime numbers into one groupvoid mutually_coprime(int n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(int j = 1; j <= n; j++) { cout << j << " "; } cout << "\n"; } else { // Integers 1, 2 and 3 can be // grouped into one group cout << "1 2 3\n"; for(int j = 4; j < n; j += 2) { // Consecutive even and // odd numbers cout << j << " " << j + 1 << "\n"; } if(n % 2 == 0) cout << n << "\n"; }} // Driver Code int main(){ int n = 9; // Function call mutually_coprime(n);} // This code is contributed by yatinagg
// Java implementation to group// mutually coprime numbers into// one group with minimum group possibleclass GFG{ // Function to group the mutually// co-prime numbers into one groupstatic void mutually_coprime(int n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(int j = 1; j < n + 1; j++) System.out.print(j + " "); System.out.println(); } else { // Integers 1, 2 and 3 can be // grouped into one group System.out.println("1 2 3"); for(int j = 4; j < n; j += 2) { // Consecutive even and // odd numbers System.out.println(j + " " + (j + 1)); if (n % 2 == 0) System.out.println(n); } }} // Driver Codepublic static void main(String[] args){ int n = 9; // Function Call mutually_coprime(n);}} // This code is contributed by sapnasingh4991
# Python3 implementation to group# mutually coprime numbers into# one group with minimum group possible # Function to group the mutually# co-prime numbers into one groupdef mutually_coprime (n): if ( n <= 3): # Loop for the numbers less # than the 4 for j in range (1, n + 1): print (j, end =" ") print () else: # Integers 1, 2 and 3 can be # grouped into one group print (1, 2, 3) for j in range ( 4, n, 2 ): # Consecutive even and # odd numbers print (j, ( j + 1 )) if(n % 2 == 0): print (n) # Driver Code if __name__ == "__main__": n = 9 # Function Call mutually_coprime (n)
// C# implementation to group// mutually coprime numbers into// one group with minimum group possibleusing System; class GFG{ // Function to group the mutually// co-prime numbers into one groupstatic void mutually_coprime(int n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(int j = 1; j < n + 1; j++) Console.Write(j + " "); Console.WriteLine(); } else { // ints 1, 2 and 3 can be // grouped into one group Console.WriteLine("1 2 3"); for(int j = 4; j < n; j += 2) { // Consecutive even and // odd numbers Console.WriteLine(j + " " + (j + 1)); if (n % 2 == 0) Console.WriteLine(n); } }} // Driver Codepublic static void Main(String[] args){ int n = 9; // Function Call mutually_coprime(n);}}// This code is contributed by sapnasingh4991
<script> // Javascript implementation to group// mutually coprime numbers into// one group with minimum group possible // Function to group the mutually// co-prime numbers into one groupfunction mutually_coprime(n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(let j = 1; j < n + 1; j++) document.write(j + " " + "<br/>"); document.write("<br/>"); } else { // Integers 1, 2 and 3 can be // grouped into one group document.write("1 2 3" + "<br/>"); for(let j = 4; j < n; j += 2) { // Consecutive even and // odd numbers document.write(j + " " + (j + 1) + "<br/>"); if (n % 2 == 0) document.write(n + "<br/>"); } }} // Driver Code let n = 9; // Function Call mutually_coprime(n); </script>
1 2 3
4 5
6 7
8 9
Time Complexity: O(n)
Auxiliary Space: O(1)
sapnasingh4991
yatinagg
code_hunt
khushboogoyal499
simranarora5sos
subham348
Prime Number
Analysis
Mathematical
Write From Home
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 190,
"s": 54,
"text": "Given an integer N, the task is to group numbers such that each group is mutually co-prime together with the total grouping is minimum."
},
{
"code": null,
"e": 200,
"s": 190,
"text": "Examples:"
},
{
"code": null,
"e": 237,
"s": 200,
"text": "Input: N = 8 Output: 1 2 3 4 5 6 7 8"
},
{
"code": null,
"e": 268,
"s": 237,
"text": "Input: N = 5 Output: 1 2 3 4 5"
},
{
"code": null,
"e": 696,
"s": 268,
"text": "Approach: The key observation in this problem is two consecutive numbers are always co-prime. That is GCD(a, a+1) = 1. Another important observation is even numbers can’t be listed in one group. Because they will lead to the greatest common divisor of 2. Therefore, every consecutive even and odd numbers can be grouped into one group and 1 can be in any group because the greatest common divisor of numbers with 1 is always 1."
},
{
"code": null,
"e": 748,
"s": 696,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 752,
"s": 748,
"text": "C++"
},
{
"code": null,
"e": 757,
"s": 752,
"text": "Java"
},
{
"code": null,
"e": 765,
"s": 757,
"text": "Python3"
},
{
"code": null,
"e": 768,
"s": 765,
"text": "C#"
},
{
"code": null,
"e": 779,
"s": 768,
"text": "Javascript"
},
{
"code": "// C++ implementation to group// mutually coprime numbers into// one group with minimum group possible#include<bits/stdc++.h>using namespace std; // Function to group the mutually// co-prime numbers into one groupvoid mutually_coprime(int n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(int j = 1; j <= n; j++) { cout << j << \" \"; } cout << \"\\n\"; } else { // Integers 1, 2 and 3 can be // grouped into one group cout << \"1 2 3\\n\"; for(int j = 4; j < n; j += 2) { // Consecutive even and // odd numbers cout << j << \" \" << j + 1 << \"\\n\"; } if(n % 2 == 0) cout << n << \"\\n\"; }} // Driver Code int main(){ int n = 9; // Function call mutually_coprime(n);} // This code is contributed by yatinagg",
"e": 1714,
"s": 779,
"text": null
},
{
"code": "// Java implementation to group// mutually coprime numbers into// one group with minimum group possibleclass GFG{ // Function to group the mutually// co-prime numbers into one groupstatic void mutually_coprime(int n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(int j = 1; j < n + 1; j++) System.out.print(j + \" \"); System.out.println(); } else { // Integers 1, 2 and 3 can be // grouped into one group System.out.println(\"1 2 3\"); for(int j = 4; j < n; j += 2) { // Consecutive even and // odd numbers System.out.println(j + \" \" + (j + 1)); if (n % 2 == 0) System.out.println(n); } }} // Driver Codepublic static void main(String[] args){ int n = 9; // Function Call mutually_coprime(n);}} // This code is contributed by sapnasingh4991",
"e": 2649,
"s": 1714,
"text": null
},
{
"code": "# Python3 implementation to group# mutually coprime numbers into# one group with minimum group possible # Function to group the mutually# co-prime numbers into one groupdef mutually_coprime (n): if ( n <= 3): # Loop for the numbers less # than the 4 for j in range (1, n + 1): print (j, end =\" \") print () else: # Integers 1, 2 and 3 can be # grouped into one group print (1, 2, 3) for j in range ( 4, n, 2 ): # Consecutive even and # odd numbers print (j, ( j + 1 )) if(n % 2 == 0): print (n) # Driver Code if __name__ == \"__main__\": n = 9 # Function Call mutually_coprime (n)",
"e": 3399,
"s": 2649,
"text": null
},
{
"code": "// C# implementation to group// mutually coprime numbers into// one group with minimum group possibleusing System; class GFG{ // Function to group the mutually// co-prime numbers into one groupstatic void mutually_coprime(int n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(int j = 1; j < n + 1; j++) Console.Write(j + \" \"); Console.WriteLine(); } else { // ints 1, 2 and 3 can be // grouped into one group Console.WriteLine(\"1 2 3\"); for(int j = 4; j < n; j += 2) { // Consecutive even and // odd numbers Console.WriteLine(j + \" \" + (j + 1)); if (n % 2 == 0) Console.WriteLine(n); } }} // Driver Codepublic static void Main(String[] args){ int n = 9; // Function Call mutually_coprime(n);}}// This code is contributed by sapnasingh4991",
"e": 4362,
"s": 3399,
"text": null
},
{
"code": "<script> // Javascript implementation to group// mutually coprime numbers into// one group with minimum group possible // Function to group the mutually// co-prime numbers into one groupfunction mutually_coprime(n){ if (n <= 3) { // Loop for the numbers less // than the 4 for(let j = 1; j < n + 1; j++) document.write(j + \" \" + \"<br/>\"); document.write(\"<br/>\"); } else { // Integers 1, 2 and 3 can be // grouped into one group document.write(\"1 2 3\" + \"<br/>\"); for(let j = 4; j < n; j += 2) { // Consecutive even and // odd numbers document.write(j + \" \" + (j + 1) + \"<br/>\"); if (n % 2 == 0) document.write(n + \"<br/>\"); } }} // Driver Code let n = 9; // Function Call mutually_coprime(n); </script>",
"e": 5265,
"s": 4362,
"text": null
},
{
"code": null,
"e": 5292,
"s": 5265,
"text": "1 2 3\n4 5\n6 7\n8 9 "
},
{
"code": null,
"e": 5316,
"s": 5294,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 5338,
"s": 5316,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5353,
"s": 5338,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 5362,
"s": 5353,
"text": "yatinagg"
},
{
"code": null,
"e": 5372,
"s": 5362,
"text": "code_hunt"
},
{
"code": null,
"e": 5389,
"s": 5372,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 5405,
"s": 5389,
"text": "simranarora5sos"
},
{
"code": null,
"e": 5415,
"s": 5405,
"text": "subham348"
},
{
"code": null,
"e": 5428,
"s": 5415,
"text": "Prime Number"
},
{
"code": null,
"e": 5437,
"s": 5428,
"text": "Analysis"
},
{
"code": null,
"e": 5450,
"s": 5437,
"text": "Mathematical"
},
{
"code": null,
"e": 5466,
"s": 5450,
"text": "Write From Home"
},
{
"code": null,
"e": 5479,
"s": 5466,
"text": "Mathematical"
},
{
"code": null,
"e": 5492,
"s": 5479,
"text": "Prime Number"
}
] |
Python Program To Add Two Numbers Represented By Linked Lists- Set 1 - GeeksforGeeks
|
21 Dec, 2021
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers.
Example:
Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405
Input: List1: 7->5->9->4->6 // represents number 75946List2: 8->4 // represents number 84Output: Resultant list: 7->6->0->3->0// represents number 76030Explanation: 75946+84=76030
Approach: Traverse both lists and One by one pick nodes of both lists and add the values. If the sum is more than 10 then make carry as 1 and reduce sum. If one list has more elements than the other then consider the remaining values of this list as 0.
The steps are:
Traverse the two linked lists from start to endAdd the two digits each from respective linked lists.If one of the lists has reached the end then take 0 as its digit.Continue it until both the end of the lists.If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10
Traverse the two linked lists from start to end
Add the two digits each from respective linked lists.
If one of the lists has reached the end then take 0 as its digit.
Continue it until both the end of the lists.
If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10
Below is the implementation of this approach.
Python
# Python program to add two numbers # represented by linked list # Node classclass Node: # Constructor to initialize the # node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at # the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Add contents of two linked lists and # return the head node of resultant list def addTwoLists(self, first, second): prev = None temp = None carry = 0 # While both list exists while(first is not None or second is not None): # Calculate the value of next digit # in resultant list # The next digit is sum of following # things # (i) Carry # (ii) Next digit of first list (if # there is a next digit) # (iii) Next digit of second list (if # there is a next digit) fdata = 0 if first is None else first.data sdata = 0 if second is None else second.data Sum = carry + fdata + sdata # Update carry for next calculation carry = 1 if Sum >= 10 else 0 # Update sum if it is greater than 10 Sum = Sum if Sum < 10 else Sum % 10 # Create a new node with sum as data temp = Node(Sum) # if this is the first node then set # it as head of resultant list if self.head is None: self.head = temp else: prev.next = temp # Set prev for next insertion prev = temp # Move first and second pointers to # next nodes if first is not None: first = first.next if second is not None: second = second.next if carry > 0: temp.next = Node(carry) # Utility function to print the # linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver codefirst = LinkedList()second = LinkedList() # Create first listfirst.push(6)first.push(4)first.push(9)first.push(5)first.push(7)print "First List is ",first.printList() # Create second listsecond.push(4)second.push(8)print "Second List is ",second.printList() # Add the two lists and see resultres = LinkedList()res.addTwoLists(first.head, second.head)print "Resultant list is ",res.printList()# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
First List is 7 5 9 4 6
Second List is 8 4
Resultant list is 5 0 0 5 6
Complexity Analysis:
Time Complexity: O(m + n), where m and n are numbers of nodes in first and second lists respectively. The lists need to be traversed only once.
Space Complexity: O(m + n). A temporary linked list is needed to store the output number
Related Article: Add two numbers represented by linked lists | Set 2
Please refer complete article on Add two numbers represented by linked lists | Set 1 for more details!
Accolite
Amazon
Flipkart
MakeMyTrip
Microsoft
Qualcomm
Snapdeal
Linked List
Python Programs
Flipkart
Accolite
Amazon
Microsoft
Snapdeal
MakeMyTrip
Qualcomm
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
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": 26179,
"s": 26151,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 26343,
"s": 26179,
"text": "Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers."
},
{
"code": null,
"e": 26352,
"s": 26343,
"text": "Example:"
},
{
"code": null,
"e": 26712,
"s": 26352,
"text": "Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405\n\nInput: List1: 7->5->9->4->6 // represents number 75946List2: 8->4 // represents number 84Output: Resultant list: 7->6->0->3->0// represents number 76030Explanation: 75946+84=76030\n"
},
{
"code": null,
"e": 26966,
"s": 26712,
"text": "Approach: Traverse both lists and One by one pick nodes of both lists and add the values. If the sum is more than 10 then make carry as 1 and reduce sum. If one list has more elements than the other then consider the remaining values of this list as 0. "
},
{
"code": null,
"e": 26982,
"s": 26966,
"text": "The steps are: "
},
{
"code": null,
"e": 27288,
"s": 26982,
"text": "Traverse the two linked lists from start to endAdd the two digits each from respective linked lists.If one of the lists has reached the end then take 0 as its digit.Continue it until both the end of the lists.If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10"
},
{
"code": null,
"e": 27336,
"s": 27288,
"text": "Traverse the two linked lists from start to end"
},
{
"code": null,
"e": 27390,
"s": 27336,
"text": "Add the two digits each from respective linked lists."
},
{
"code": null,
"e": 27456,
"s": 27390,
"text": "If one of the lists has reached the end then take 0 as its digit."
},
{
"code": null,
"e": 27501,
"s": 27456,
"text": "Continue it until both the end of the lists."
},
{
"code": null,
"e": 27598,
"s": 27501,
"text": "If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10"
},
{
"code": null,
"e": 27645,
"s": 27598,
"text": "Below is the implementation of this approach. "
},
{
"code": null,
"e": 27652,
"s": 27645,
"text": "Python"
},
{
"code": "# Python program to add two numbers # represented by linked list # Node classclass Node: # Constructor to initialize the # node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at # the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Add contents of two linked lists and # return the head node of resultant list def addTwoLists(self, first, second): prev = None temp = None carry = 0 # While both list exists while(first is not None or second is not None): # Calculate the value of next digit # in resultant list # The next digit is sum of following # things # (i) Carry # (ii) Next digit of first list (if # there is a next digit) # (iii) Next digit of second list (if # there is a next digit) fdata = 0 if first is None else first.data sdata = 0 if second is None else second.data Sum = carry + fdata + sdata # Update carry for next calculation carry = 1 if Sum >= 10 else 0 # Update sum if it is greater than 10 Sum = Sum if Sum < 10 else Sum % 10 # Create a new node with sum as data temp = Node(Sum) # if this is the first node then set # it as head of resultant list if self.head is None: self.head = temp else: prev.next = temp # Set prev for next insertion prev = temp # Move first and second pointers to # next nodes if first is not None: first = first.next if second is not None: second = second.next if carry > 0: temp.next = Node(carry) # Utility function to print the # linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver codefirst = LinkedList()second = LinkedList() # Create first listfirst.push(6)first.push(4)first.push(9)first.push(5)first.push(7)print \"First List is \",first.printList() # Create second listsecond.push(4)second.push(8)print \"Second List is \",second.printList() # Add the two lists and see resultres = LinkedList()res.addTwoLists(first.head, second.head)print \"Resultant list is \",res.printList()# This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 30407,
"s": 27652,
"text": null
},
{
"code": null,
"e": 30415,
"s": 30407,
"text": "Output:"
},
{
"code": null,
"e": 30489,
"s": 30415,
"text": "First List is 7 5 9 4 6 \nSecond List is 8 4 \nResultant list is 5 0 0 5 6 "
},
{
"code": null,
"e": 30511,
"s": 30489,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 30655,
"s": 30511,
"text": "Time Complexity: O(m + n), where m and n are numbers of nodes in first and second lists respectively. The lists need to be traversed only once."
},
{
"code": null,
"e": 30744,
"s": 30655,
"text": "Space Complexity: O(m + n). A temporary linked list is needed to store the output number"
},
{
"code": null,
"e": 30813,
"s": 30744,
"text": "Related Article: Add two numbers represented by linked lists | Set 2"
},
{
"code": null,
"e": 30916,
"s": 30813,
"text": "Please refer complete article on Add two numbers represented by linked lists | Set 1 for more details!"
},
{
"code": null,
"e": 30925,
"s": 30916,
"text": "Accolite"
},
{
"code": null,
"e": 30932,
"s": 30925,
"text": "Amazon"
},
{
"code": null,
"e": 30941,
"s": 30932,
"text": "Flipkart"
},
{
"code": null,
"e": 30952,
"s": 30941,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 30962,
"s": 30952,
"text": "Microsoft"
},
{
"code": null,
"e": 30971,
"s": 30962,
"text": "Qualcomm"
},
{
"code": null,
"e": 30980,
"s": 30971,
"text": "Snapdeal"
},
{
"code": null,
"e": 30992,
"s": 30980,
"text": "Linked List"
},
{
"code": null,
"e": 31008,
"s": 30992,
"text": "Python Programs"
},
{
"code": null,
"e": 31017,
"s": 31008,
"text": "Flipkart"
},
{
"code": null,
"e": 31026,
"s": 31017,
"text": "Accolite"
},
{
"code": null,
"e": 31033,
"s": 31026,
"text": "Amazon"
},
{
"code": null,
"e": 31043,
"s": 31033,
"text": "Microsoft"
},
{
"code": null,
"e": 31052,
"s": 31043,
"text": "Snapdeal"
},
{
"code": null,
"e": 31063,
"s": 31052,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 31072,
"s": 31063,
"text": "Qualcomm"
},
{
"code": null,
"e": 31084,
"s": 31072,
"text": "Linked List"
},
{
"code": null,
"e": 31182,
"s": 31084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31223,
"s": 31182,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 31273,
"s": 31223,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 31332,
"s": 31273,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 31372,
"s": 31332,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 31443,
"s": 31372,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 31486,
"s": 31443,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 31508,
"s": 31486,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31547,
"s": 31508,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 31593,
"s": 31547,
"text": "Python | Split string into list of characters"
}
] |
Monitor vs Semaphore - GeeksforGeeks
|
16 Mar, 2020
Both semaphores and monitors are used to solve the critical section problem (as they allow processes to access the shared resources in mutual exclusion) and to achieve process synchronization in the multiprocessing environment.
Monitor:A Monitor type high-level synchronization construct. It is an abstract data type. The Monitor type contains shared variables and the set of procedures that operate on the shared variable.
When any process wishes to access the shared variables in the monitor, it needs to access it through the procedures. These processes line up in a queue and are only provided access when the previous process release the shared variables. Only one process can be active in a monitor at a time. Monitor has condition variables.
Syntax:
monitor {
//shared variable declarations
data variables;
Procedure P1() { ... }
Procedure P2() { ... }
.
.
.
Procedure Pn() { ... }
}
Semaphore:A Semaphore is a lower-level object. A semaphore is a non-negative integer variable. The value of Semaphore indicates the number of shared resources available in the system. The value of semaphore can be modified only by two functions, namely wait() and signal() operations (apart from the initialization).
When any process accesses the shared resources, it performs the wait() operation on the semaphore and when the process releases the shared resources, it performs the signal() operation on the semaphore. Semaphore does not have condition variables. When a process is modifying the value of the semaphore, no other process can simultaneously modify the value of the semaphore.
The Semaphore is further divided into 2 categories:
Binary semaphoreCounting semaphore
Binary semaphore
Counting semaphore
Syntax:
// Wait Operation
wait(Semaphore S) {
while (S<=0);
S--;
}
// Signal Operation
signal(Semaphore S) {
S++;
}
Advantages of Monitors:
Monitors are easy to implement than semaphores.
Mutual exclusion in monitors is automatic while in semaphores, mutual exclusion needs to be implemented explicitly.
Monitors can overcome the timing errors that occur while using semaphores.
Shared variables are global to all processes in the monitor while shared variables are hidden in semaphores.
Advantages of Semaphores:
Semaphores are machine independent (because they are implemented in the kernel services).
Semaphores permit more than one thread to access the critical section, unlike monitors.
In semaphores there is no spinning, hence no waste of resources due to no busy waiting.
Process Synchronization
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Introduction of Process Synchronization
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Introduction of Deadlock in Operating System
Program for Round Robin scheduling | Set 1
|
[
{
"code": null,
"e": 25627,
"s": 25599,
"text": "\n16 Mar, 2020"
},
{
"code": null,
"e": 25855,
"s": 25627,
"text": "Both semaphores and monitors are used to solve the critical section problem (as they allow processes to access the shared resources in mutual exclusion) and to achieve process synchronization in the multiprocessing environment."
},
{
"code": null,
"e": 26051,
"s": 25855,
"text": "Monitor:A Monitor type high-level synchronization construct. It is an abstract data type. The Monitor type contains shared variables and the set of procedures that operate on the shared variable."
},
{
"code": null,
"e": 26376,
"s": 26051,
"text": "When any process wishes to access the shared variables in the monitor, it needs to access it through the procedures. These processes line up in a queue and are only provided access when the previous process release the shared variables. Only one process can be active in a monitor at a time. Monitor has condition variables."
},
{
"code": null,
"e": 26384,
"s": 26376,
"text": "Syntax:"
},
{
"code": null,
"e": 26558,
"s": 26384,
"text": "monitor {\n \n //shared variable declarations\n data variables;\n Procedure P1() { ... }\n Procedure P2() { ... }\n .\n .\n .\n Procedure Pn() { ... }\n\n} "
},
{
"code": null,
"e": 26875,
"s": 26558,
"text": "Semaphore:A Semaphore is a lower-level object. A semaphore is a non-negative integer variable. The value of Semaphore indicates the number of shared resources available in the system. The value of semaphore can be modified only by two functions, namely wait() and signal() operations (apart from the initialization)."
},
{
"code": null,
"e": 27250,
"s": 26875,
"text": "When any process accesses the shared resources, it performs the wait() operation on the semaphore and when the process releases the shared resources, it performs the signal() operation on the semaphore. Semaphore does not have condition variables. When a process is modifying the value of the semaphore, no other process can simultaneously modify the value of the semaphore."
},
{
"code": null,
"e": 27302,
"s": 27250,
"text": "The Semaphore is further divided into 2 categories:"
},
{
"code": null,
"e": 27337,
"s": 27302,
"text": "Binary semaphoreCounting semaphore"
},
{
"code": null,
"e": 27354,
"s": 27337,
"text": "Binary semaphore"
},
{
"code": null,
"e": 27373,
"s": 27354,
"text": "Counting semaphore"
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Syntax:"
},
{
"code": null,
"e": 27545,
"s": 27381,
"text": " // Wait Operation\n wait(Semaphore S) { \n while (S<=0);\n S--;\n }\n // Signal Operation\n signal(Semaphore S) {\n S++;\n } "
},
{
"code": null,
"e": 27569,
"s": 27545,
"text": "Advantages of Monitors:"
},
{
"code": null,
"e": 27617,
"s": 27569,
"text": "Monitors are easy to implement than semaphores."
},
{
"code": null,
"e": 27733,
"s": 27617,
"text": "Mutual exclusion in monitors is automatic while in semaphores, mutual exclusion needs to be implemented explicitly."
},
{
"code": null,
"e": 27808,
"s": 27733,
"text": "Monitors can overcome the timing errors that occur while using semaphores."
},
{
"code": null,
"e": 27917,
"s": 27808,
"text": "Shared variables are global to all processes in the monitor while shared variables are hidden in semaphores."
},
{
"code": null,
"e": 27943,
"s": 27917,
"text": "Advantages of Semaphores:"
},
{
"code": null,
"e": 28033,
"s": 27943,
"text": "Semaphores are machine independent (because they are implemented in the kernel services)."
},
{
"code": null,
"e": 28121,
"s": 28033,
"text": "Semaphores permit more than one thread to access the critical section, unlike monitors."
},
{
"code": null,
"e": 28209,
"s": 28121,
"text": "In semaphores there is no spinning, hence no waste of resources due to no busy waiting."
},
{
"code": null,
"e": 28233,
"s": 28209,
"text": "Process Synchronization"
},
{
"code": null,
"e": 28241,
"s": 28233,
"text": "GATE CS"
},
{
"code": null,
"e": 28259,
"s": 28241,
"text": "Operating Systems"
},
{
"code": null,
"e": 28277,
"s": 28259,
"text": "Operating Systems"
},
{
"code": null,
"e": 28375,
"s": 28277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28409,
"s": 28375,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 28450,
"s": 28409,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 28503,
"s": 28450,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28524,
"s": 28503,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 28564,
"s": 28524,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 28603,
"s": 28564,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 28643,
"s": 28603,
"text": "Program for FCFS CPU Scheduling | Set 1"
},
{
"code": null,
"e": 28670,
"s": 28643,
"text": "Paging in Operating System"
},
{
"code": null,
"e": 28715,
"s": 28670,
"text": "Introduction of Deadlock in Operating System"
}
] |
init command in Linux with examples - GeeksforGeeks
|
26 Aug, 2020
init is parent of all Linux processes with PID or process ID of 1. It is the first process to start when a computer boots up and runs until the system shuts down. init stands for initialization. In simple words the role of init is to create processes from script stored in the file /etc/inittab which is a configuration file which is to be used by initialization system. It is the last step of the kernel boot sequence.
/etc/inittab Specifies the init command control file.
init script initializes the service. So, it responsible for initializing the system.
Init scripts are also called rc scripts (run command scripts)
Init script is also used in UNIX.
Syntax
init [OPTIONS...] {COMMAND}
Run Levels
Run Levels is the state of init where a group of processes are defined to start at the startup of OS. The process spawned by init for each of this run levels are defined in the file /etc/inittab. Each runlevel has a certain number of services stopped or started. Conventionally seven runlevel exist numbers from zero to six.
Runlevel
Does not configure network interfaces, start daemons,
or allow non-root logins
By default most of the LINUX based system boots to runlevel 3 or runlevel 5. In addition to the standard runlevels, users can modify the preset runlevels or even create new ones according to the requirement. Runlevels 2 and 4 are used for user defined runlevels and runlevel 0 and 6 are used for halting and rebooting the system.
akashpatil242000
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n26 Aug, 2020"
},
{
"code": null,
"e": 26071,
"s": 25651,
"text": "init is parent of all Linux processes with PID or process ID of 1. It is the first process to start when a computer boots up and runs until the system shuts down. init stands for initialization. In simple words the role of init is to create processes from script stored in the file /etc/inittab which is a configuration file which is to be used by initialization system. It is the last step of the kernel boot sequence."
},
{
"code": null,
"e": 26126,
"s": 26071,
"text": "/etc/inittab Specifies the init command control file.\n"
},
{
"code": null,
"e": 26211,
"s": 26126,
"text": "init script initializes the service. So, it responsible for initializing the system."
},
{
"code": null,
"e": 26273,
"s": 26211,
"text": "Init scripts are also called rc scripts (run command scripts)"
},
{
"code": null,
"e": 26307,
"s": 26273,
"text": "Init script is also used in UNIX."
},
{
"code": null,
"e": 26314,
"s": 26307,
"text": "Syntax"
},
{
"code": null,
"e": 26343,
"s": 26314,
"text": "init [OPTIONS...] {COMMAND}\n"
},
{
"code": null,
"e": 26354,
"s": 26343,
"text": "Run Levels"
},
{
"code": null,
"e": 26679,
"s": 26354,
"text": "Run Levels is the state of init where a group of processes are defined to start at the startup of OS. The process spawned by init for each of this run levels are defined in the file /etc/inittab. Each runlevel has a certain number of services stopped or started. Conventionally seven runlevel exist numbers from zero to six."
},
{
"code": null,
"e": 26688,
"s": 26679,
"text": "Runlevel"
},
{
"code": null,
"e": 26743,
"s": 26688,
"text": "Does not configure network interfaces, start daemons, "
},
{
"code": null,
"e": 26768,
"s": 26743,
"text": "or allow non-root logins"
},
{
"code": null,
"e": 27098,
"s": 26768,
"text": "By default most of the LINUX based system boots to runlevel 3 or runlevel 5. In addition to the standard runlevels, users can modify the preset runlevels or even create new ones according to the requirement. Runlevels 2 and 4 are used for user defined runlevels and runlevel 0 and 6 are used for halting and rebooting the system."
},
{
"code": null,
"e": 27117,
"s": 27100,
"text": "akashpatil242000"
},
{
"code": null,
"e": 27131,
"s": 27117,
"text": "linux-command"
},
{
"code": null,
"e": 27153,
"s": 27131,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 27160,
"s": 27153,
"text": "Picked"
},
{
"code": null,
"e": 27171,
"s": 27160,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27269,
"s": 27171,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27304,
"s": 27269,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27338,
"s": 27304,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27364,
"s": 27338,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27393,
"s": 27364,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27430,
"s": 27393,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27467,
"s": 27430,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27509,
"s": 27467,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27535,
"s": 27509,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27571,
"s": 27535,
"text": "uniq Command in LINUX with examples"
}
] |
Ways to place K bishops on an N×N chessboard so that no two attack - GeeksforGeeks
|
06 May, 2021
Given two integers N and K, the task is to find the number of ways to place K bishops on an N × N chessboard so that no two bishops attack each other.
Here is an example for a 5×5 chessboard.
Examples:
Input: N = 2, K = 2 Output: 4 The different ways to place 2 bishops in a 2 * 2 chessboard are :
Input: N = 4, K = 3 Output: 232
Approach: This problem can be solved using dynamic programming.
Let dp[i][j] denote the number of ways to place j bishops on diagonals with indices up to i which have the same color as diagonal i. Then i = 1...2N-1 and j = 0...K.
We can calculate dp[i][j] using only values of dp[i-2] (we subtract 2 because we only consider diagonals of the same color as i). There are two ways to get dp[i][j]. Either we place all j bishops on previous diagonals: then there are dp[i-2][j] ways to achieve this. Or we place one bishop on diagonal i and j-1 bishops on previous diagonals. The number of ways to do this equals the number of squares in diagonal i – (j – 1), because each of j-1 bishops placed on previous diagonals will block one square on the current diagonal.
The base case is simple: dp[i][0] = 1, dp[1][1] = 1.
Once we have calculated all values of dp[i][j], the answer can be obtained as follows: consider all possible numbers of bishops placed on black diagonals i=0...K, with corresponding numbers of bishops on white diagonals K-i. The bishops placed on black and white diagonals never attack each other, so the placements can be done independently. The index of the last black diagonal is 2N-1, the last white one is 2N-2. For each i we add dp[2N-1][i] * dp[2N-2][K-i] to the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // returns the number of squares in diagonal iint squares(int i){ if ((i & 1) == 1) return i / 4 * 2 + 1; else return (i - 1) / 4 * 2 + 2;} // returns the number of ways to fill a// n * n chessboard with k bishops so// that no two bishops attack each other.long bishop_placements(int n, int k){ // return 0 if the number of valid places to be // filled is less than the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values long dp[n * 2][k + 1]; // Setting the base conditions for(int i = 0; i < n * 2; i++) { for(int j = 0; j < k + 1; j++) { dp[i][j] = 0; } } for (int i = 0; i < n * 2; i++) dp[i][0] = 1; dp[1][1] = 1; // calculate the required number of ways for (int i = 2; i < n * 2; i++) { for (int j = 1; j <= k; j++) { dp[i][j] = dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1); } } // stores the answer long ans = 0; for (int i = 0; i <= k; i++) { ans += dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]; } return ans;} // Driver codeint main(){ int n = 2; int k = 2; long ans = bishop_placements(n, k); cout << (ans);} // This code is contributed by Rajput-Ji
// Java implementation of the approach class GFG { // returns the number of squares in diagonal i static int squares(int i) { if ((i & 1) == 1) return i / 4 * 2 + 1; else return (i - 1) / 4 * 2 + 2; } // returns the number of ways to fill a // n * n chessboard with k bishops so // that no two bishops attack each other. static long bishop_placements(int n, int k) { // return 0 if the number of valid places to be // filled is less than the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values long[][] dp = new long[n * 2][k + 1]; // Setting the base conditions for (int i = 0; i < n * 2; i++) dp[i][0] = 1; dp[1][1] = 1; // calculate the required number of ways for (int i = 2; i < n * 2; i++) { for (int j = 1; j <= k; j++) dp[i][j] = dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1); } // stores the answer long ans = 0; for (int i = 0; i <= k; i++) { ans += dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]; } return ans; } // Driver code public static void main(String[] args) { int n = 2; int k = 2; long ans = bishop_placements(n, k); System.out.println(ans); }}
# Python 3 implementation of the approach # returns the number of squares in# diagonal idef squares(i): if ((i & 1) == 1): return int(i / 4) * 2 + 1 else: return int((i - 1) / 4) * 2 + 2 # returns the number of ways to fill a# n * n chessboard with k bishops so# that no two bishops attack each other.def bishop_placements(n, k): # return 0 if the number of valid places # to be filled is less than the number # of bishops if (k > 2 * n - 1): return 0 # dp table to store the values dp = [[0 for i in range(k + 1)] for i in range(n * 2)] # Setting the base conditions for i in range(n * 2): dp[i][0] = 1 dp[1][1] = 1 # calculate the required number of ways for i in range(2, n * 2, 1): for j in range(1, k + 1, 1): dp[i][j] = (dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1)) # stores the answer ans = 0 for i in range(0, k + 1, 1): ans += (dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]) return ans # Driver codeif __name__ == '__main__': n = 2 k = 2 ans = bishop_placements(n, k) print(ans) # This code is contributed by# Sanjit_Prasad
// C# implementation of the approachusing System; class GFG{ // returns the number of squares// in diagonal istatic int squares(int i){ if ((i & 1) == 1) return i / 4 * 2 + 1; else return (i - 1) / 4 * 2 + 2;} // returns the number of ways to fill a// n * n chessboard with k bishops so// that no two bishops attack each other.static long bishop_placements(int n, int k){ // return 0 if the number of valid // places to be filled is less than // the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values long[,] dp = new long[n * 2, k + 1]; // Setting the base conditions for (int i = 0; i < n * 2; i++) dp[i, 0] = 1; dp[1, 1] = 1; // calculate the required // number of ways for (int i = 2; i < n * 2; i++) { for (int j = 1; j <= k; j++) dp[i, j] = dp[i - 2, j] + dp[i - 2, j - 1] * (squares(i) - j + 1); } // stores the answer long ans = 0; for (int i = 0; i <= k; i++) { ans += dp[n * 2 - 1, i] * dp[n * 2 - 2, k - i]; } return ans;} // Driver codestatic public void Main (){ int n = 2; int k = 2; long ans = bishop_placements(n, k); Console.WriteLine(ans);}} // This code is contributed by akt_mit
<?php// PHP implementation of the approach // returns the number of squares// in diagonal ifunction squares($i){ if (($i & 1) == 1) return intval($i / 4) * 2 + 1; else return intval(($i - 1) / 4) * 2 + 2;} // returns the number of ways to fill a// n * n chessboard with k bishops so// that no two bishops attack each other.function bishop_placements($n, $k){ // return 0 if the number of valid // places to be filled is less than // the number of bishops if ($k > 2 * $n - 1) return 0; // dp table to store the values $dp = array_fill(0, $n * 2, array_fill(0, $k + 1, NULL)); // Setting the base conditions for ($i = 0; $i < $n * 2; $i++) $dp[$i][0] = 1; $dp[1][1] = 1; // calculate the required number of ways for ($i = 2; $i < $n * 2; $i++) { for ($j = 1; $j <= $k; $j++) $dp[$i][$j] = $dp[$i - 2][$j] + $dp[$i - 2][$j - 1] * (squares($i) - $j + 1); } // stores the answer $ans = 0; for ($i = 0; $i <= $k; $i++) { $ans += $dp[$n * 2 - 1][$i] * $dp[$n * 2 - 2][$k - $i]; } return $ans;} // Driver code$n = 2;$k = 2;$ans = bishop_placements($n, $k);echo $ans; // This code is contributed by ita_c?>
<script> // Javascript implementation of the approach // returns the number of squares // in diagonal i function squares(i) { if ((i & 1) == 1) return parseInt(i / 4, 10) * 2 + 1; else return parseInt((i - 1) / 4, 10) * 2 + 2; } // returns the number of ways to fill a // n * n chessboard with k bishops so // that no two bishops attack each other. function bishop_placements(n, k) { // return 0 if the number of valid // places to be filled is less than // the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values let dp = new Array(n * 2); // Setting the base conditions for (let i = 0; i < n * 2; i++) { dp[i] = new Array(k + 1); for(let j = 0; j < k + 1; j++) { dp[i][j] = 0; } dp[i][0] = 1; } dp[1][1] = 1; // calculate the required // number of ways for (let i = 2; i < n * 2; i++) { for (let j = 1; j <= k; j++) dp[i][j] = dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1); } // stores the answer let ans = 0; for (let i = 0; i <= k; i++) { ans += dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]; } return ans; } let n = 2; let k = 2; let ans = bishop_placements(n, k); document.write(ans); </script>
4
jit_t
Sanjit_Prasad
ukasp
Rajput-Ji
divyesh072019
Technical Scripter 2018
Dynamic Programming
Technical Scripter
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Greedy approach vs Dynamic programming
Maximum sum such that no two elements are adjacent
Word Break Problem | DP-32
3 Different ways to print Fibonacci series in Java
Top 50 Dynamic Programming Coding Problems for Interviews
|
[
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 26094,
"s": 25941,
"text": "Given two integers N and K, the task is to find the number of ways to place K bishops on an N × N chessboard so that no two bishops attack each other. "
},
{
"code": null,
"e": 26137,
"s": 26094,
"text": "Here is an example for a 5×5 chessboard. "
},
{
"code": null,
"e": 26151,
"s": 26139,
"text": "Examples: "
},
{
"code": null,
"e": 26249,
"s": 26151,
"text": "Input: N = 2, K = 2 Output: 4 The different ways to place 2 bishops in a 2 * 2 chessboard are : "
},
{
"code": null,
"e": 26283,
"s": 26249,
"text": "Input: N = 4, K = 3 Output: 232 "
},
{
"code": null,
"e": 26351,
"s": 26285,
"text": "Approach: This problem can be solved using dynamic programming. "
},
{
"code": null,
"e": 26517,
"s": 26351,
"text": "Let dp[i][j] denote the number of ways to place j bishops on diagonals with indices up to i which have the same color as diagonal i. Then i = 1...2N-1 and j = 0...K."
},
{
"code": null,
"e": 27048,
"s": 26517,
"text": "We can calculate dp[i][j] using only values of dp[i-2] (we subtract 2 because we only consider diagonals of the same color as i). There are two ways to get dp[i][j]. Either we place all j bishops on previous diagonals: then there are dp[i-2][j] ways to achieve this. Or we place one bishop on diagonal i and j-1 bishops on previous diagonals. The number of ways to do this equals the number of squares in diagonal i – (j – 1), because each of j-1 bishops placed on previous diagonals will block one square on the current diagonal."
},
{
"code": null,
"e": 27101,
"s": 27048,
"text": "The base case is simple: dp[i][0] = 1, dp[1][1] = 1."
},
{
"code": null,
"e": 27579,
"s": 27101,
"text": "Once we have calculated all values of dp[i][j], the answer can be obtained as follows: consider all possible numbers of bishops placed on black diagonals i=0...K, with corresponding numbers of bishops on white diagonals K-i. The bishops placed on black and white diagonals never attack each other, so the placements can be done independently. The index of the last black diagonal is 2N-1, the last white one is 2N-2. For each i we add dp[2N-1][i] * dp[2N-2][K-i] to the answer."
},
{
"code": null,
"e": 27632,
"s": 27579,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27636,
"s": 27632,
"text": "C++"
},
{
"code": null,
"e": 27641,
"s": 27636,
"text": "Java"
},
{
"code": null,
"e": 27649,
"s": 27641,
"text": "Python3"
},
{
"code": null,
"e": 27652,
"s": 27649,
"text": "C#"
},
{
"code": null,
"e": 27656,
"s": 27652,
"text": "PHP"
},
{
"code": null,
"e": 27667,
"s": 27656,
"text": "Javascript"
},
{
"code": "// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // returns the number of squares in diagonal iint squares(int i){ if ((i & 1) == 1) return i / 4 * 2 + 1; else return (i - 1) / 4 * 2 + 2;} // returns the number of ways to fill a// n * n chessboard with k bishops so// that no two bishops attack each other.long bishop_placements(int n, int k){ // return 0 if the number of valid places to be // filled is less than the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values long dp[n * 2][k + 1]; // Setting the base conditions for(int i = 0; i < n * 2; i++) { for(int j = 0; j < k + 1; j++) { dp[i][j] = 0; } } for (int i = 0; i < n * 2; i++) dp[i][0] = 1; dp[1][1] = 1; // calculate the required number of ways for (int i = 2; i < n * 2; i++) { for (int j = 1; j <= k; j++) { dp[i][j] = dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1); } } // stores the answer long ans = 0; for (int i = 0; i <= k; i++) { ans += dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]; } return ans;} // Driver codeint main(){ int n = 2; int k = 2; long ans = bishop_placements(n, k); cout << (ans);} // This code is contributed by Rajput-Ji",
"e": 29057,
"s": 27667,
"text": null
},
{
"code": "// Java implementation of the approach class GFG { // returns the number of squares in diagonal i static int squares(int i) { if ((i & 1) == 1) return i / 4 * 2 + 1; else return (i - 1) / 4 * 2 + 2; } // returns the number of ways to fill a // n * n chessboard with k bishops so // that no two bishops attack each other. static long bishop_placements(int n, int k) { // return 0 if the number of valid places to be // filled is less than the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values long[][] dp = new long[n * 2][k + 1]; // Setting the base conditions for (int i = 0; i < n * 2; i++) dp[i][0] = 1; dp[1][1] = 1; // calculate the required number of ways for (int i = 2; i < n * 2; i++) { for (int j = 1; j <= k; j++) dp[i][j] = dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1); } // stores the answer long ans = 0; for (int i = 0; i <= k; i++) { ans += dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]; } return ans; } // Driver code public static void main(String[] args) { int n = 2; int k = 2; long ans = bishop_placements(n, k); System.out.println(ans); }}",
"e": 30479,
"s": 29057,
"text": null
},
{
"code": "# Python 3 implementation of the approach # returns the number of squares in# diagonal idef squares(i): if ((i & 1) == 1): return int(i / 4) * 2 + 1 else: return int((i - 1) / 4) * 2 + 2 # returns the number of ways to fill a# n * n chessboard with k bishops so# that no two bishops attack each other.def bishop_placements(n, k): # return 0 if the number of valid places # to be filled is less than the number # of bishops if (k > 2 * n - 1): return 0 # dp table to store the values dp = [[0 for i in range(k + 1)] for i in range(n * 2)] # Setting the base conditions for i in range(n * 2): dp[i][0] = 1 dp[1][1] = 1 # calculate the required number of ways for i in range(2, n * 2, 1): for j in range(1, k + 1, 1): dp[i][j] = (dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1)) # stores the answer ans = 0 for i in range(0, k + 1, 1): ans += (dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]) return ans # Driver codeif __name__ == '__main__': n = 2 k = 2 ans = bishop_placements(n, k) print(ans) # This code is contributed by# Sanjit_Prasad",
"e": 31724,
"s": 30479,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // returns the number of squares// in diagonal istatic int squares(int i){ if ((i & 1) == 1) return i / 4 * 2 + 1; else return (i - 1) / 4 * 2 + 2;} // returns the number of ways to fill a// n * n chessboard with k bishops so// that no two bishops attack each other.static long bishop_placements(int n, int k){ // return 0 if the number of valid // places to be filled is less than // the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values long[,] dp = new long[n * 2, k + 1]; // Setting the base conditions for (int i = 0; i < n * 2; i++) dp[i, 0] = 1; dp[1, 1] = 1; // calculate the required // number of ways for (int i = 2; i < n * 2; i++) { for (int j = 1; j <= k; j++) dp[i, j] = dp[i - 2, j] + dp[i - 2, j - 1] * (squares(i) - j + 1); } // stores the answer long ans = 0; for (int i = 0; i <= k; i++) { ans += dp[n * 2 - 1, i] * dp[n * 2 - 2, k - i]; } return ans;} // Driver codestatic public void Main (){ int n = 2; int k = 2; long ans = bishop_placements(n, k); Console.WriteLine(ans);}} // This code is contributed by akt_mit",
"e": 33046,
"s": 31724,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // returns the number of squares// in diagonal ifunction squares($i){ if (($i & 1) == 1) return intval($i / 4) * 2 + 1; else return intval(($i - 1) / 4) * 2 + 2;} // returns the number of ways to fill a// n * n chessboard with k bishops so// that no two bishops attack each other.function bishop_placements($n, $k){ // return 0 if the number of valid // places to be filled is less than // the number of bishops if ($k > 2 * $n - 1) return 0; // dp table to store the values $dp = array_fill(0, $n * 2, array_fill(0, $k + 1, NULL)); // Setting the base conditions for ($i = 0; $i < $n * 2; $i++) $dp[$i][0] = 1; $dp[1][1] = 1; // calculate the required number of ways for ($i = 2; $i < $n * 2; $i++) { for ($j = 1; $j <= $k; $j++) $dp[$i][$j] = $dp[$i - 2][$j] + $dp[$i - 2][$j - 1] * (squares($i) - $j + 1); } // stores the answer $ans = 0; for ($i = 0; $i <= $k; $i++) { $ans += $dp[$n * 2 - 1][$i] * $dp[$n * 2 - 2][$k - $i]; } return $ans;} // Driver code$n = 2;$k = 2;$ans = bishop_placements($n, $k);echo $ans; // This code is contributed by ita_c?>",
"e": 34343,
"s": 33046,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // returns the number of squares // in diagonal i function squares(i) { if ((i & 1) == 1) return parseInt(i / 4, 10) * 2 + 1; else return parseInt((i - 1) / 4, 10) * 2 + 2; } // returns the number of ways to fill a // n * n chessboard with k bishops so // that no two bishops attack each other. function bishop_placements(n, k) { // return 0 if the number of valid // places to be filled is less than // the number of bishops if (k > 2 * n - 1) return 0; // dp table to store the values let dp = new Array(n * 2); // Setting the base conditions for (let i = 0; i < n * 2; i++) { dp[i] = new Array(k + 1); for(let j = 0; j < k + 1; j++) { dp[i][j] = 0; } dp[i][0] = 1; } dp[1][1] = 1; // calculate the required // number of ways for (let i = 2; i < n * 2; i++) { for (let j = 1; j <= k; j++) dp[i][j] = dp[i - 2][j] + dp[i - 2][j - 1] * (squares(i) - j + 1); } // stores the answer let ans = 0; for (let i = 0; i <= k; i++) { ans += dp[n * 2 - 1][i] * dp[n * 2 - 2][k - i]; } return ans; } let n = 2; let k = 2; let ans = bishop_placements(n, k); document.write(ans); </script>",
"e": 35911,
"s": 34343,
"text": null
},
{
"code": null,
"e": 35913,
"s": 35911,
"text": "4"
},
{
"code": null,
"e": 35921,
"s": 35915,
"text": "jit_t"
},
{
"code": null,
"e": 35935,
"s": 35921,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 35941,
"s": 35935,
"text": "ukasp"
},
{
"code": null,
"e": 35951,
"s": 35941,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35965,
"s": 35951,
"text": "divyesh072019"
},
{
"code": null,
"e": 35989,
"s": 35965,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 36009,
"s": 35989,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36028,
"s": 36009,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36048,
"s": 36028,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36146,
"s": 36048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36189,
"s": 36146,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 36249,
"s": 36189,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 36284,
"s": 36249,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 36305,
"s": 36284,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 36361,
"s": 36305,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 36400,
"s": 36361,
"text": "Greedy approach vs Dynamic programming"
},
{
"code": null,
"e": 36451,
"s": 36400,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 36478,
"s": 36451,
"text": "Word Break Problem | DP-32"
},
{
"code": null,
"e": 36529,
"s": 36478,
"text": "3 Different ways to print Fibonacci series in Java"
}
] |
Permissions in Linux - GeeksforGeeks
|
26 Apr, 2022
Linux is a multi-user operating system, so it has security to prevent people from accessing each other’s confidential files.
When you execute an “ls” command, you are not given any information about the security of the files, because by default “ls” only lists the names of files. You can get more information by using an “option” with the “ls” command. All options start with a ‘-‘. For example, to execute “ls” with the “long listing” option, you would type ls -l
When you do so, each file will be listed on a separate line in long format. There is an example in the window below.
There’s a lot of information in those lines.
The first character will almost always be either a ‘-‘, which means it’s a file, or a ‘d’, which means it’s a directory.The next nine characters (rw-r–r–) show the security; we’ll talk about them later.The next column shows the owner of the file. In this case it is me, my userID is “aditya314”.The next column shows the group owner of the file. In my case I want to give the “aditya314” group of people special access to these files.The next column shows the size of the file in bytes.The next column shows the date and time the file was last modified.And, of course, the final column gives the filename.
The first character will almost always be either a ‘-‘, which means it’s a file, or a ‘d’, which means it’s a directory.
The next nine characters (rw-r–r–) show the security; we’ll talk about them later.
The next column shows the owner of the file. In this case it is me, my userID is “aditya314”.
The next column shows the group owner of the file. In my case I want to give the “aditya314” group of people special access to these files.
The next column shows the size of the file in bytes.
The next column shows the date and time the file was last modified.
And, of course, the final column gives the filename.
Deciphering the security characters will take a bit more work.
First, you must think of those nine characters as three sets of three characters (see the box at the bottom). Each of the three “rwx” characters refers to a different operation you can perform on the file.
--- --- ---
rwx rwx rwx
user group other
The ‘r’ means you can “read” the file’s contents. The ‘w’ means you can “write”, or modify, the file’s contents. The ‘x’ means you can “execute” the file. This permission is given only if the file is a program. If any of the “rwx” characters is replaced by a ‘-‘, then that permission has been revoked.
user – The user permissions apply only the owner of the file or directory, they will not impact the actions of other users. group – The group permissions apply only to the group that has been assigned to the file or directory, they will not effect the actions of other users. others – The others permissions apply to all other users on the system, this is the permission group that you want to watch the most.
For example, consider that the user’s permissions for some files is “rw-” as the first three characters. This means that the owner of the file (“aditya314”, i.e. me) can “read” it (look at its contents) and “write” it (modify its contents). I cannot execute it because it is not a program; it is a text file.
If “r-x” is the second set of 3 characters it means that the members of the group “aditya314” can only read and execute the files.
The final three characters show the permissions allowed to anyone who has a UserID on this Linux system. Let us say we have the permission (“r–“). This means anyone in our Linux world can read, but they cannot modify the contents of the files or execute it.
The command you use to change the security permissions on files is called “chmod”, which stands for “change mode”, because the nine security characters are collectively called the security “mode” of the file.
The first argument you give to the “chmod” command is ‘u’, ‘g’, ‘o’. We use: u for user g for group o for others, you can also use a combination of them (u,g,o). This specifies which of the three groups you want to modify. After this use a ‘+’ for adding a ‘-‘ for removing and a “=” for assigning a permission.Then specify the permission r,w or x you want to change. Here also you can use a combination of r,w,x. This specifies which of the three permissions “rwx” you want to modifyuse can use commas to modify more permissionsFinally, the name of the file whose permission you are changing
The first argument you give to the “chmod” command is ‘u’, ‘g’, ‘o’. We use: u for user g for group o for others, you can also use a combination of them (u,g,o). This specifies which of the three groups you want to modify.
After this use a ‘+’ for adding a ‘-‘ for removing and a “=” for assigning a permission.
Then specify the permission r,w or x you want to change. Here also you can use a combination of r,w,x. This specifies which of the three permissions “rwx” you want to modify
use can use commas to modify more permissions
Finally, the name of the file whose permission you are changing
An example will make this clearer. For example, if you want to give “execute” permission to the world (“other”) for file “xyz.txt”, you would start by typing
chmod o
Now you would type a ‘+’ to say that you are “adding” a permission.
chmod o+
Then you would type an ‘x’ to say that you are adding “execute” permission.
chmod o+x
Finally, specify which file you are changing.
chmod o+x xyz.txt
You can see the change in the picture below.
You can also change multiple permissions at once. For example, if you want to take all permissions away from everyone, you would type
chmod ugo-rwx xyz.txt
The code above revokes all the read(r), write(w) and execute(x) permission from all user(u), group(g) and others(o) for the file xyz.txt which results to this.
Another example can be this:
chmod ug+rw,o-x abc.mp4
The code above adds read(r) and write(w) permission to both user(u) and group(g) and revoke execute(x) permission from others(o) for the file abc.mp4.
Something like this:
chmod ug=rx,o+r abc.c
assigns read(r) and execute(x) permission to both user(u) and group(g) and add read permission to others for the file abc.c.
There can be numerous combinations of file permissions you can invoke, revoke and assign. You can try some in your linux system.
You can also use octal notations like this.
Using the octal notations table instead of ‘r’, ‘w’ and ‘x’. Each digit octal notation can be used of either of the group ‘u’,’g’,’o’.
So, the following work the same.
chmod ugo+rwx [file_name]
chmod 777 [file_name]
Both of them provides full read write and execute permission (code=7) to all the group.
Same is the case with this..
chmod u=r,g=wx,o=rx [file_name]
chmod 435 [file_name]
Both the codes give read (code=4) permission to user, write and execute (code=3) for group and read and execute (code=5) for others.
And even this...
chmod 775 [file_name]
chmod ug+rwx,o=rx [file_name]
Both the commands give all permissions (code=7) to user and group, read and execute (code=5) for others.
The default Linux security model is a bit inflexible. To give special access (such as modification privileges) to a group of people, you have to get your system administrator to create a group with those people in it. Furthermore, if you would like to give a different set of access privileges (such as read access) to another group of people, you can’t do it because you can only assign one group owner per file or directory. To solve this problem, you can use ACLs (Access Control Lists). You can learn more about them from this link: ACLs
References: askubuntu linuxcommand.org
This article is contributed by Aditya Nihal Kumar 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 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.
sumitgumber28
surinderdawra388
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
|
[
{
"code": null,
"e": 25813,
"s": 25785,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 25939,
"s": 25813,
"text": "Linux is a multi-user operating system, so it has security to prevent people from accessing each other’s confidential files. "
},
{
"code": null,
"e": 26283,
"s": 25941,
"text": "When you execute an “ls” command, you are not given any information about the security of the files, because by default “ls” only lists the names of files. You can get more information by using an “option” with the “ls” command. All options start with a ‘-‘. For example, to execute “ls” with the “long listing” option, you would type ls -l "
},
{
"code": null,
"e": 26402,
"s": 26283,
"text": "When you do so, each file will be listed on a separate line in long format. There is an example in the window below. "
},
{
"code": null,
"e": 26449,
"s": 26402,
"text": "There’s a lot of information in those lines. "
},
{
"code": null,
"e": 27055,
"s": 26449,
"text": "The first character will almost always be either a ‘-‘, which means it’s a file, or a ‘d’, which means it’s a directory.The next nine characters (rw-r–r–) show the security; we’ll talk about them later.The next column shows the owner of the file. In this case it is me, my userID is “aditya314”.The next column shows the group owner of the file. In my case I want to give the “aditya314” group of people special access to these files.The next column shows the size of the file in bytes.The next column shows the date and time the file was last modified.And, of course, the final column gives the filename."
},
{
"code": null,
"e": 27176,
"s": 27055,
"text": "The first character will almost always be either a ‘-‘, which means it’s a file, or a ‘d’, which means it’s a directory."
},
{
"code": null,
"e": 27259,
"s": 27176,
"text": "The next nine characters (rw-r–r–) show the security; we’ll talk about them later."
},
{
"code": null,
"e": 27353,
"s": 27259,
"text": "The next column shows the owner of the file. In this case it is me, my userID is “aditya314”."
},
{
"code": null,
"e": 27493,
"s": 27353,
"text": "The next column shows the group owner of the file. In my case I want to give the “aditya314” group of people special access to these files."
},
{
"code": null,
"e": 27546,
"s": 27493,
"text": "The next column shows the size of the file in bytes."
},
{
"code": null,
"e": 27614,
"s": 27546,
"text": "The next column shows the date and time the file was last modified."
},
{
"code": null,
"e": 27667,
"s": 27614,
"text": "And, of course, the final column gives the filename."
},
{
"code": null,
"e": 27731,
"s": 27667,
"text": "Deciphering the security characters will take a bit more work. "
},
{
"code": null,
"e": 27941,
"s": 27733,
"text": "First, you must think of those nine characters as three sets of three characters (see the box at the bottom). Each of the three “rwx” characters refers to a different operation you can perform on the file. "
},
{
"code": null,
"e": 28003,
"s": 27941,
"text": "--- --- ---\nrwx rwx rwx\nuser group other"
},
{
"code": null,
"e": 28309,
"s": 28005,
"text": "The ‘r’ means you can “read” the file’s contents. The ‘w’ means you can “write”, or modify, the file’s contents. The ‘x’ means you can “execute” the file. This permission is given only if the file is a program. If any of the “rwx” characters is replaced by a ‘-‘, then that permission has been revoked. "
},
{
"code": null,
"e": 28722,
"s": 28311,
"text": "user – The user permissions apply only the owner of the file or directory, they will not impact the actions of other users. group – The group permissions apply only to the group that has been assigned to the file or directory, they will not effect the actions of other users. others – The others permissions apply to all other users on the system, this is the permission group that you want to watch the most. "
},
{
"code": null,
"e": 29034,
"s": 28724,
"text": "For example, consider that the user’s permissions for some files is “rw-” as the first three characters. This means that the owner of the file (“aditya314”, i.e. me) can “read” it (look at its contents) and “write” it (modify its contents). I cannot execute it because it is not a program; it is a text file. "
},
{
"code": null,
"e": 29166,
"s": 29034,
"text": "If “r-x” is the second set of 3 characters it means that the members of the group “aditya314” can only read and execute the files. "
},
{
"code": null,
"e": 29425,
"s": 29166,
"text": "The final three characters show the permissions allowed to anyone who has a UserID on this Linux system. Let us say we have the permission (“r–“). This means anyone in our Linux world can read, but they cannot modify the contents of the files or execute it. "
},
{
"code": null,
"e": 29637,
"s": 29427,
"text": "The command you use to change the security permissions on files is called “chmod”, which stands for “change mode”, because the nine security characters are collectively called the security “mode” of the file. "
},
{
"code": null,
"e": 30233,
"s": 29639,
"text": "The first argument you give to the “chmod” command is ‘u’, ‘g’, ‘o’. We use: u for user g for group o for others, you can also use a combination of them (u,g,o). This specifies which of the three groups you want to modify. After this use a ‘+’ for adding a ‘-‘ for removing and a “=” for assigning a permission.Then specify the permission r,w or x you want to change. Here also you can use a combination of r,w,x. This specifies which of the three permissions “rwx” you want to modifyuse can use commas to modify more permissionsFinally, the name of the file whose permission you are changing"
},
{
"code": null,
"e": 30458,
"s": 30233,
"text": "The first argument you give to the “chmod” command is ‘u’, ‘g’, ‘o’. We use: u for user g for group o for others, you can also use a combination of them (u,g,o). This specifies which of the three groups you want to modify. "
},
{
"code": null,
"e": 30547,
"s": 30458,
"text": "After this use a ‘+’ for adding a ‘-‘ for removing and a “=” for assigning a permission."
},
{
"code": null,
"e": 30721,
"s": 30547,
"text": "Then specify the permission r,w or x you want to change. Here also you can use a combination of r,w,x. This specifies which of the three permissions “rwx” you want to modify"
},
{
"code": null,
"e": 30767,
"s": 30721,
"text": "use can use commas to modify more permissions"
},
{
"code": null,
"e": 30831,
"s": 30767,
"text": "Finally, the name of the file whose permission you are changing"
},
{
"code": null,
"e": 30991,
"s": 30831,
"text": "An example will make this clearer. For example, if you want to give “execute” permission to the world (“other”) for file “xyz.txt”, you would start by typing "
},
{
"code": null,
"e": 30999,
"s": 30991,
"text": "chmod o"
},
{
"code": null,
"e": 31069,
"s": 30999,
"text": "Now you would type a ‘+’ to say that you are “adding” a permission. "
},
{
"code": null,
"e": 31078,
"s": 31069,
"text": "chmod o+"
},
{
"code": null,
"e": 31156,
"s": 31078,
"text": "Then you would type an ‘x’ to say that you are adding “execute” permission. "
},
{
"code": null,
"e": 31166,
"s": 31156,
"text": "chmod o+x"
},
{
"code": null,
"e": 31214,
"s": 31166,
"text": "Finally, specify which file you are changing. "
},
{
"code": null,
"e": 31232,
"s": 31214,
"text": "chmod o+x xyz.txt"
},
{
"code": null,
"e": 31279,
"s": 31232,
"text": "You can see the change in the picture below. "
},
{
"code": null,
"e": 31415,
"s": 31279,
"text": "You can also change multiple permissions at once. For example, if you want to take all permissions away from everyone, you would type "
},
{
"code": null,
"e": 31437,
"s": 31415,
"text": "chmod ugo-rwx xyz.txt"
},
{
"code": null,
"e": 31599,
"s": 31437,
"text": "The code above revokes all the read(r), write(w) and execute(x) permission from all user(u), group(g) and others(o) for the file xyz.txt which results to this. "
},
{
"code": null,
"e": 31630,
"s": 31599,
"text": "Another example can be this: "
},
{
"code": null,
"e": 31654,
"s": 31630,
"text": "chmod ug+rw,o-x abc.mp4"
},
{
"code": null,
"e": 31806,
"s": 31654,
"text": "The code above adds read(r) and write(w) permission to both user(u) and group(g) and revoke execute(x) permission from others(o) for the file abc.mp4. "
},
{
"code": null,
"e": 31829,
"s": 31806,
"text": "Something like this: "
},
{
"code": null,
"e": 31851,
"s": 31829,
"text": "chmod ug=rx,o+r abc.c"
},
{
"code": null,
"e": 31977,
"s": 31851,
"text": "assigns read(r) and execute(x) permission to both user(u) and group(g) and add read permission to others for the file abc.c. "
},
{
"code": null,
"e": 32107,
"s": 31977,
"text": "There can be numerous combinations of file permissions you can invoke, revoke and assign. You can try some in your linux system. "
},
{
"code": null,
"e": 32155,
"s": 32109,
"text": "You can also use octal notations like this. "
},
{
"code": null,
"e": 32291,
"s": 32155,
"text": "Using the octal notations table instead of ‘r’, ‘w’ and ‘x’. Each digit octal notation can be used of either of the group ‘u’,’g’,’o’. "
},
{
"code": null,
"e": 32326,
"s": 32291,
"text": "So, the following work the same. "
},
{
"code": null,
"e": 32374,
"s": 32326,
"text": "chmod ugo+rwx [file_name]\nchmod 777 [file_name]"
},
{
"code": null,
"e": 32463,
"s": 32374,
"text": "Both of them provides full read write and execute permission (code=7) to all the group. "
},
{
"code": null,
"e": 32494,
"s": 32463,
"text": "Same is the case with this.. "
},
{
"code": null,
"e": 32548,
"s": 32494,
"text": "chmod u=r,g=wx,o=rx [file_name]\nchmod 435 [file_name]"
},
{
"code": null,
"e": 32682,
"s": 32548,
"text": "Both the codes give read (code=4) permission to user, write and execute (code=3) for group and read and execute (code=5) for others. "
},
{
"code": null,
"e": 32701,
"s": 32682,
"text": "And even this... "
},
{
"code": null,
"e": 32753,
"s": 32701,
"text": "chmod 775 [file_name]\nchmod ug+rwx,o=rx [file_name]"
},
{
"code": null,
"e": 32859,
"s": 32753,
"text": "Both the commands give all permissions (code=7) to user and group, read and execute (code=5) for others. "
},
{
"code": null,
"e": 33404,
"s": 32861,
"text": "The default Linux security model is a bit inflexible. To give special access (such as modification privileges) to a group of people, you have to get your system administrator to create a group with those people in it. Furthermore, if you would like to give a different set of access privileges (such as read access) to another group of people, you can’t do it because you can only assign one group owner per file or directory. To solve this problem, you can use ACLs (Access Control Lists). You can learn more about them from this link: ACLs "
},
{
"code": null,
"e": 33444,
"s": 33404,
"text": "References: askubuntu linuxcommand.org "
},
{
"code": null,
"e": 33753,
"s": 33444,
"text": "This article is contributed by Aditya Nihal Kumar 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 33879,
"s": 33753,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33893,
"s": 33879,
"text": "sumitgumber28"
},
{
"code": null,
"e": 33910,
"s": 33893,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33924,
"s": 33910,
"text": "linux-command"
},
{
"code": null,
"e": 33935,
"s": 33924,
"text": "Linux-Unix"
},
{
"code": null,
"e": 34033,
"s": 33935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34068,
"s": 34033,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 34104,
"s": 34068,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 34142,
"s": 34104,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 34175,
"s": 34142,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 34211,
"s": 34175,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 34247,
"s": 34211,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 34285,
"s": 34247,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 34320,
"s": 34285,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 34357,
"s": 34320,
"text": "touch command in Linux with Examples"
}
] |
C# | Check if HashSet and the specified collection contain the same elements - GeeksforGeeks
|
01 Feb, 2019
A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.SetEquals(IEnumerable) Method is used to check if a HashSet and the specified collection contain the same elements or not.
Syntax:
mySet1.SetEquals(mySet2);
Here, mySet1 and mySet2 are HashSets objects.
Return Type: This method return True if the mySet1 is equal to mySet2 else returns False.
Exception: This method will give ArgumentNullException if the HashSet is null.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to check if HashSet and the specified// collection contain the same elements.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet1 = new HashSet<string>(); // Inserting elements in HashSet mySet1.Add("Geeks"); mySet1.Add("GeeksforGeeks"); mySet1.Add("GeeksClasses"); mySet1.Add("GeeksQuiz"); // Creating a HashSet of strings HashSet<string> mySet2 = new HashSet<string>(); // Inserting elements in HashSet mySet2.Add("Geeks"); mySet2.Add("GeeksforGeeks"); mySet2.Add("GeeksClasses"); mySet2.Add("GeeksQuiz"); // Check if both HashSets contains same elements Console.WriteLine(mySet1.SetEquals(mySet2)); }}
True
Example 2:
// C# code to check if HashSet and the specified// collection contain the same elements.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Inserting elements in HashSet mySet1.Add(4); mySet1.Add(8); mySet1.Add(12); mySet1.Add(16); // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting elements in HashSet mySet2.Add(5); mySet2.Add(10); mySet2.Add(15); mySet2.Add(20); // Check if both HashSets contains same elements Console.WriteLine(mySet1.SetEquals(mySet2)); }}
False
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.setequals?view=netframework-4.7.2
CSharp-Generic-HashSet
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types
C# | Arrays
|
[
{
"code": null,
"e": 25919,
"s": 25891,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 26341,
"s": 25919,
"text": "A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.SetEquals(IEnumerable) Method is used to check if a HashSet and the specified collection contain the same elements or not."
},
{
"code": null,
"e": 26349,
"s": 26341,
"text": "Syntax:"
},
{
"code": null,
"e": 26376,
"s": 26349,
"text": "mySet1.SetEquals(mySet2);\n"
},
{
"code": null,
"e": 26422,
"s": 26376,
"text": "Here, mySet1 and mySet2 are HashSets objects."
},
{
"code": null,
"e": 26512,
"s": 26422,
"text": "Return Type: This method return True if the mySet1 is equal to mySet2 else returns False."
},
{
"code": null,
"e": 26591,
"s": 26512,
"text": "Exception: This method will give ArgumentNullException if the HashSet is null."
},
{
"code": null,
"e": 26671,
"s": 26591,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 26682,
"s": 26671,
"text": "Example 1:"
},
{
"code": "// C# code to check if HashSet and the specified// collection contain the same elements.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet1 = new HashSet<string>(); // Inserting elements in HashSet mySet1.Add(\"Geeks\"); mySet1.Add(\"GeeksforGeeks\"); mySet1.Add(\"GeeksClasses\"); mySet1.Add(\"GeeksQuiz\"); // Creating a HashSet of strings HashSet<string> mySet2 = new HashSet<string>(); // Inserting elements in HashSet mySet2.Add(\"Geeks\"); mySet2.Add(\"GeeksforGeeks\"); mySet2.Add(\"GeeksClasses\"); mySet2.Add(\"GeeksQuiz\"); // Check if both HashSets contains same elements Console.WriteLine(mySet1.SetEquals(mySet2)); }}",
"e": 27540,
"s": 26682,
"text": null
},
{
"code": null,
"e": 27546,
"s": 27540,
"text": "True\n"
},
{
"code": null,
"e": 27557,
"s": 27546,
"text": "Example 2:"
},
{
"code": "// C# code to check if HashSet and the specified// collection contain the same elements.using System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet1 = new HashSet<int>(); // Inserting elements in HashSet mySet1.Add(4); mySet1.Add(8); mySet1.Add(12); mySet1.Add(16); // Creating a HashSet of integers HashSet<int> mySet2 = new HashSet<int>(); // Inserting elements in HashSet mySet2.Add(5); mySet2.Add(10); mySet2.Add(15); mySet2.Add(20); // Check if both HashSets contains same elements Console.WriteLine(mySet1.SetEquals(mySet2)); }}",
"e": 28324,
"s": 27557,
"text": null
},
{
"code": null,
"e": 28331,
"s": 28324,
"text": "False\n"
},
{
"code": null,
"e": 28342,
"s": 28331,
"text": "Reference:"
},
{
"code": null,
"e": 28457,
"s": 28342,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.setequals?view=netframework-4.7.2"
},
{
"code": null,
"e": 28480,
"s": 28457,
"text": "CSharp-Generic-HashSet"
},
{
"code": null,
"e": 28505,
"s": 28480,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 28519,
"s": 28505,
"text": "CSharp-method"
},
{
"code": null,
"e": 28522,
"s": 28519,
"text": "C#"
},
{
"code": null,
"e": 28620,
"s": 28522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28635,
"s": 28620,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28657,
"s": 28635,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28680,
"s": 28657,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28702,
"s": 28680,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28720,
"s": 28702,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28760,
"s": 28720,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28782,
"s": 28760,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 28813,
"s": 28782,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28829,
"s": 28813,
"text": "C# | Data Types"
}
] |
Java Program to Read a Grade & Display the Equivalent Description - GeeksforGeeks
|
31 Jul, 2021
Problem Statement: Numbers on a scale of 1 to 100 are randomly given the grade as the input from the user and then match the input grade of the user against the given cases to generate the desired output.
Real life Example
Consider a number on a scale of 1 to 100 are written on a piece of paper slips. Now person starts picking slips one by one and starts organizing them in such a manner that he starts putting slips in 10 different boxes prior deciding making 10 different pots in such a manner slips numbering 1-10 in ‘pot A’, 11-20 in ‘pot B’ and so on till labeling and inserting slips till all the slips are organized in labeled pots. He did this in order to easily figure out numbers written on slips.
So in technical terms In these ways machine get
Take input from the user
Match the grade using equal to the operator (==)
Generate the equivalent description as the output
There are several methods starting from brute force(naive) to most optimal. Few are discussed below :
Using the If-Else MethodSwitch case Method
Using the If-Else Method
Switch case Method
The grades are assigned using the following
Approach 1: If-Else Statement
Below is the implementation of the above approach
Java
// Java Program to Read Grade & Displaying Equivalent Desc // Importing Classes/Filesimport java.util.*; public class GFG { // Main Driver Method public static void main(String[] args) { // User is supposed to enter grade among them System.out.println( "Enter Grade varying from S,A,B,C,D"); String grade = "A"; // Checking whether grade == "S" or not if (grade == "S") { System.out.println( "Student has scored between 90 to 100"); } // Checking whether grade == "A" or not else if (grade == "A") { System.out.println( "Student has scored between 80 to 90"); } // Checking whether grade == "B" or not else if (grade == "B") { System.out.println( "Student has scored between 70 to 80"); } // Checking whether grade == "C" or not else if (grade == "C") { System.out.println( "Student has scored between 60 to 70"); } // Checking whether grade == "D" or not else if (grade == "D") { System.out.println( "Student has scored between 50 to 60"); } else { // Printing message-user pressed some other key System.out.println( "The grade you entered is not valid!"); } }}
Enter Grade varying from S,A,B,C,D
Student has scored between 80 to 90
Approach 2: Switch Case
Below is the implementation of the above approach
Java
// Java Program to Read a Grade & Display the Equivalent // Importing Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String args[]) { // Random grade taken for consideration String grade = "W"; // Using Switch-Case. switch (grade) { // Checking whether grade == "S" or not. case "S": System.out.println( "Student has scored between 90 to 100"); break; // Checking whether grade == "A" or not. case "A": System.out.println( "Student has scored between 80 to 90"); break; // Checking whether grade == "B" or not. case "B": System.out.println( "Student has scored between 70 to 80"); break; // Checking whether grade == "C" or not. case "C": System.out.println( "Student has scored between 60 to 70"); break; // Checking whether grade == "D" or not. case "D": System.out.println( "Student has scored between 50 to 60"); break; default: System.out.println( "The grade you entered is not valid!"); } }}
The grade you entered is not valid!
varshagumber28
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 25430,
"s": 25225,
"text": "Problem Statement: Numbers on a scale of 1 to 100 are randomly given the grade as the input from the user and then match the input grade of the user against the given cases to generate the desired output."
},
{
"code": null,
"e": 25448,
"s": 25430,
"text": "Real life Example"
},
{
"code": null,
"e": 25936,
"s": 25448,
"text": "Consider a number on a scale of 1 to 100 are written on a piece of paper slips. Now person starts picking slips one by one and starts organizing them in such a manner that he starts putting slips in 10 different boxes prior deciding making 10 different pots in such a manner slips numbering 1-10 in ‘pot A’, 11-20 in ‘pot B’ and so on till labeling and inserting slips till all the slips are organized in labeled pots. He did this in order to easily figure out numbers written on slips. "
},
{
"code": null,
"e": 25984,
"s": 25936,
"text": "So in technical terms In these ways machine get"
},
{
"code": null,
"e": 26009,
"s": 25984,
"text": "Take input from the user"
},
{
"code": null,
"e": 26058,
"s": 26009,
"text": "Match the grade using equal to the operator (==)"
},
{
"code": null,
"e": 26108,
"s": 26058,
"text": "Generate the equivalent description as the output"
},
{
"code": null,
"e": 26210,
"s": 26108,
"text": "There are several methods starting from brute force(naive) to most optimal. Few are discussed below :"
},
{
"code": null,
"e": 26254,
"s": 26210,
"text": " Using the If-Else MethodSwitch case Method"
},
{
"code": null,
"e": 26280,
"s": 26254,
"text": " Using the If-Else Method"
},
{
"code": null,
"e": 26299,
"s": 26280,
"text": "Switch case Method"
},
{
"code": null,
"e": 26344,
"s": 26299,
"text": "The grades are assigned using the following "
},
{
"code": null,
"e": 26374,
"s": 26344,
"text": "Approach 1: If-Else Statement"
},
{
"code": null,
"e": 26424,
"s": 26374,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 26429,
"s": 26424,
"text": "Java"
},
{
"code": "// Java Program to Read Grade & Displaying Equivalent Desc // Importing Classes/Filesimport java.util.*; public class GFG { // Main Driver Method public static void main(String[] args) { // User is supposed to enter grade among them System.out.println( \"Enter Grade varying from S,A,B,C,D\"); String grade = \"A\"; // Checking whether grade == \"S\" or not if (grade == \"S\") { System.out.println( \"Student has scored between 90 to 100\"); } // Checking whether grade == \"A\" or not else if (grade == \"A\") { System.out.println( \"Student has scored between 80 to 90\"); } // Checking whether grade == \"B\" or not else if (grade == \"B\") { System.out.println( \"Student has scored between 70 to 80\"); } // Checking whether grade == \"C\" or not else if (grade == \"C\") { System.out.println( \"Student has scored between 60 to 70\"); } // Checking whether grade == \"D\" or not else if (grade == \"D\") { System.out.println( \"Student has scored between 50 to 60\"); } else { // Printing message-user pressed some other key System.out.println( \"The grade you entered is not valid!\"); } }}",
"e": 27826,
"s": 26429,
"text": null
},
{
"code": null,
"e": 27897,
"s": 27826,
"text": "Enter Grade varying from S,A,B,C,D\nStudent has scored between 80 to 90"
},
{
"code": null,
"e": 27921,
"s": 27897,
"text": "Approach 2: Switch Case"
},
{
"code": null,
"e": 27972,
"s": 27921,
"text": "Below is the implementation of the above approach "
},
{
"code": null,
"e": 27977,
"s": 27972,
"text": "Java"
},
{
"code": "// Java Program to Read a Grade & Display the Equivalent // Importing Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String args[]) { // Random grade taken for consideration String grade = \"W\"; // Using Switch-Case. switch (grade) { // Checking whether grade == \"S\" or not. case \"S\": System.out.println( \"Student has scored between 90 to 100\"); break; // Checking whether grade == \"A\" or not. case \"A\": System.out.println( \"Student has scored between 80 to 90\"); break; // Checking whether grade == \"B\" or not. case \"B\": System.out.println( \"Student has scored between 70 to 80\"); break; // Checking whether grade == \"C\" or not. case \"C\": System.out.println( \"Student has scored between 60 to 70\"); break; // Checking whether grade == \"D\" or not. case \"D\": System.out.println( \"Student has scored between 50 to 60\"); break; default: System.out.println( \"The grade you entered is not valid!\"); } }}",
"e": 29291,
"s": 27977,
"text": null
},
{
"code": null,
"e": 29327,
"s": 29291,
"text": "The grade you entered is not valid!"
},
{
"code": null,
"e": 29346,
"s": 29331,
"text": "varshagumber28"
},
{
"code": null,
"e": 29351,
"s": 29346,
"text": "Java"
},
{
"code": null,
"e": 29365,
"s": 29351,
"text": "Java Programs"
},
{
"code": null,
"e": 29370,
"s": 29365,
"text": "Java"
},
{
"code": null,
"e": 29468,
"s": 29370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29483,
"s": 29468,
"text": "Stream In Java"
},
{
"code": null,
"e": 29504,
"s": 29483,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29523,
"s": 29504,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29553,
"s": 29523,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29599,
"s": 29553,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29625,
"s": 29599,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29659,
"s": 29625,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29706,
"s": 29659,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29738,
"s": 29706,
"text": "How to Iterate HashMap in Java?"
}
] |
How to create a simple editable canvas textbox using Fabric.js? - GeeksforGeeks
|
08 Feb, 2022
In this article, we are going to create a canvas textbox using Fabric.js. The canvas means text written in the Textbox is movable and can be stretched according to requirement. Further, the text itself can be edited into anything else too because it is a textbox.Creating structure: To make this possible we are going to use a JavaScript library called FabricJS and create a basic canvas structure.
Including FabricJS library: Importing the library using CDN
<script src=”https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js”></script>
HTML code to create canvas structure: We will create a canvas block in the body tag which will contain our textbox. After this, we will initialize instances of Canvas and Textbox provided by FabricJS and render the Canvas on the Textbox as given in the example below.
HTML
<!DOCTYPE html><html> <head> </head> <body> <center> <h1>GeeksforGeeks</h1> <b>Creating canvas-type textbox</b> <canvas id="canvas" width="600" height="200"> </canvas> </center> </body></html>
Design structure: In this section we will design the pre-created structure, and also add the functionality to move the canvas text around the canvas by using JavaScript.
CSS code to design the structure:
HTML
<style> body { text-align: center; } h1 { color: green; } canvas { border: 2px solid green; }</style>
JavaScript code: In this section we can place the text inside the canvas.Syntax:
fabric.Textbox('Sample Text', { width: 100 });
Javascript
<script> // Create a new instance of Canvas var canvas = new fabric.Canvas("canvas"); // Create a new Textbox instance var text = new fabric.Textbox('A Computer Science Portal', { width: 450 }); // Render the Textbox on Canvas canvas.add(text);</script>
Program: We can use FabricJS to create simple editable canvas-like textbox as given below:
HTML
<!DOCTYPE html><html> <head> <!-- FabricJS CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } canvas { border: 2px solid green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b>Creating canvas-type textbox</b> <canvas id="canvas" width="600" height="200"> </canvas> </center> <script> // Create a new instance of Canvas var canvas = new fabric.Canvas("canvas"); // Create a new Textbox instance var text = new fabric.Textbox('A Computer Science Portal', { width: 450 }); // Render the Textbox on Canvas canvas.add(text); </script></body></html>
Output:
rs1686740
surindertarika1234
blalverma92
CSS-Misc
Fabric.js
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
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": 25997,
"s": 25969,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 26397,
"s": 25997,
"text": "In this article, we are going to create a canvas textbox using Fabric.js. The canvas means text written in the Textbox is movable and can be stretched according to requirement. Further, the text itself can be edited into anything else too because it is a textbox.Creating structure: To make this possible we are going to use a JavaScript library called FabricJS and create a basic canvas structure. "
},
{
"code": null,
"e": 26457,
"s": 26397,
"text": "Including FabricJS library: Importing the library using CDN"
},
{
"code": null,
"e": 26550,
"s": 26457,
"text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js”></script>"
},
{
"code": null,
"e": 26818,
"s": 26550,
"text": "HTML code to create canvas structure: We will create a canvas block in the body tag which will contain our textbox. After this, we will initialize instances of Canvas and Textbox provided by FabricJS and render the Canvas on the Textbox as given in the example below."
},
{
"code": null,
"e": 26823,
"s": 26818,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> </head> <body> <center> <h1>GeeksforGeeks</h1> <b>Creating canvas-type textbox</b> <canvas id=\"canvas\" width=\"600\" height=\"200\"> </canvas> </center> </body></html> ",
"e": 27099,
"s": 26823,
"text": null
},
{
"code": null,
"e": 27270,
"s": 27099,
"text": "Design structure: In this section we will design the pre-created structure, and also add the functionality to move the canvas text around the canvas by using JavaScript. "
},
{
"code": null,
"e": 27304,
"s": 27270,
"text": "CSS code to design the structure:"
},
{
"code": null,
"e": 27309,
"s": 27304,
"text": "HTML"
},
{
"code": "<style> body { text-align: center; } h1 { color: green; } canvas { border: 2px solid green; }</style>",
"e": 27450,
"s": 27309,
"text": null
},
{
"code": null,
"e": 27531,
"s": 27450,
"text": "JavaScript code: In this section we can place the text inside the canvas.Syntax:"
},
{
"code": null,
"e": 27580,
"s": 27531,
"text": " fabric.Textbox('Sample Text', { width: 100 }); "
},
{
"code": null,
"e": 27591,
"s": 27580,
"text": "Javascript"
},
{
"code": "<script> // Create a new instance of Canvas var canvas = new fabric.Canvas(\"canvas\"); // Create a new Textbox instance var text = new fabric.Textbox('A Computer Science Portal', { width: 450 }); // Render the Textbox on Canvas canvas.add(text);</script>",
"e": 27883,
"s": 27591,
"text": null
},
{
"code": null,
"e": 27974,
"s": 27883,
"text": "Program: We can use FabricJS to create simple editable canvas-like textbox as given below:"
},
{
"code": null,
"e": 27979,
"s": 27974,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- FabricJS CDN --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } canvas { border: 2px solid green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b>Creating canvas-type textbox</b> <canvas id=\"canvas\" width=\"600\" height=\"200\"> </canvas> </center> <script> // Create a new instance of Canvas var canvas = new fabric.Canvas(\"canvas\"); // Create a new Textbox instance var text = new fabric.Textbox('A Computer Science Portal', { width: 450 }); // Render the Textbox on Canvas canvas.add(text); </script></body></html>",
"e": 28883,
"s": 27979,
"text": null
},
{
"code": null,
"e": 28891,
"s": 28883,
"text": "Output:"
},
{
"code": null,
"e": 28901,
"s": 28891,
"text": "rs1686740"
},
{
"code": null,
"e": 28920,
"s": 28901,
"text": "surindertarika1234"
},
{
"code": null,
"e": 28932,
"s": 28920,
"text": "blalverma92"
},
{
"code": null,
"e": 28941,
"s": 28932,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28951,
"s": 28941,
"text": "Fabric.js"
},
{
"code": null,
"e": 28961,
"s": 28951,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28977,
"s": 28961,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28981,
"s": 28977,
"text": "CSS"
},
{
"code": null,
"e": 28986,
"s": 28981,
"text": "HTML"
},
{
"code": null,
"e": 28997,
"s": 28986,
"text": "JavaScript"
},
{
"code": null,
"e": 29014,
"s": 28997,
"text": "Web Technologies"
},
{
"code": null,
"e": 29041,
"s": 29014,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29046,
"s": 29041,
"text": "HTML"
},
{
"code": null,
"e": 29144,
"s": 29046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29199,
"s": 29144,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29236,
"s": 29199,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29300,
"s": 29236,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29337,
"s": 29300,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29376,
"s": 29337,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29436,
"s": 29376,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29489,
"s": 29436,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29550,
"s": 29489,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29574,
"s": 29550,
"text": "REST API (Introduction)"
}
] |
Matcher toString() method in Java with Examples - GeeksforGeeks
|
27 Nov, 2018
The toString() method of Matcher Class is used to get the String representation of this matcher. This method is derived from the Object Class and behaves in the similar way.
Syntax:
public String toString()
Parameters: This method takes no parameters.
Return Value: This method returns a String value which is the String representation of this matcher.
Below examples illustrate the Matcher.toString() method:
Example 1:
// Java code to illustrate toString() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(Geeks)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = " Geeks for For Geeks Geek"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String representation of this matcher // using toString() method System.out.println(matcher.toString()); }}
java.util.regex.Matcher[pattern=(Geeks) region=0,25 lastmatch=]
Example 2:
// Java code to illustrate toString() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "(GFG)"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "FGF GFG GFG FGF"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String representation of this matcher // using toString() method System.out.println(matcher.toString()); }}
java.util.regex.Matcher[pattern=(GFG) region=0,15 lastmatch=]
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#toString–
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n27 Nov, 2018"
},
{
"code": null,
"e": 25399,
"s": 25225,
"text": "The toString() method of Matcher Class is used to get the String representation of this matcher. This method is derived from the Object Class and behaves in the similar way."
},
{
"code": null,
"e": 25407,
"s": 25399,
"text": "Syntax:"
},
{
"code": null,
"e": 25433,
"s": 25407,
"text": "public String toString()\n"
},
{
"code": null,
"e": 25478,
"s": 25433,
"text": "Parameters: This method takes no parameters."
},
{
"code": null,
"e": 25579,
"s": 25478,
"text": "Return Value: This method returns a String value which is the String representation of this matcher."
},
{
"code": null,
"e": 25636,
"s": 25579,
"text": "Below examples illustrate the Matcher.toString() method:"
},
{
"code": null,
"e": 25647,
"s": 25636,
"text": "Example 1:"
},
{
"code": "// Java code to illustrate toString() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(Geeks)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \" Geeks for For Geeks Geek\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String representation of this matcher // using toString() method System.out.println(matcher.toString()); }}",
"e": 26330,
"s": 25647,
"text": null
},
{
"code": null,
"e": 26395,
"s": 26330,
"text": "java.util.regex.Matcher[pattern=(Geeks) region=0,25 lastmatch=]\n"
},
{
"code": null,
"e": 26406,
"s": 26395,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate toString() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"(GFG)\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"FGF GFG GFG FGF\"; // Create a matcher for the input String Matcher matcher = pattern.matcher(stringToBeMatched); // Get the String representation of this matcher // using toString() method System.out.println(matcher.toString()); }}",
"e": 27088,
"s": 26406,
"text": null
},
{
"code": null,
"e": 27151,
"s": 27088,
"text": "java.util.regex.Matcher[pattern=(GFG) region=0,15 lastmatch=]\n"
},
{
"code": null,
"e": 27243,
"s": 27151,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#toString–"
},
{
"code": null,
"e": 27263,
"s": 27243,
"text": "Java - util package"
},
{
"code": null,
"e": 27278,
"s": 27263,
"text": "Java-Functions"
},
{
"code": null,
"e": 27291,
"s": 27278,
"text": "Java-Matcher"
},
{
"code": null,
"e": 27296,
"s": 27291,
"text": "Java"
},
{
"code": null,
"e": 27301,
"s": 27296,
"text": "Java"
},
{
"code": null,
"e": 27399,
"s": 27301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27414,
"s": 27399,
"text": "Stream In Java"
},
{
"code": null,
"e": 27435,
"s": 27414,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27454,
"s": 27435,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27484,
"s": 27454,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27530,
"s": 27484,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27547,
"s": 27530,
"text": "Generics in Java"
},
{
"code": null,
"e": 27568,
"s": 27547,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27604,
"s": 27568,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 27647,
"s": 27604,
"text": "Comparator Interface in Java with Examples"
}
] |
AtomicIntegerArray accumulateAndGet() method in Java with Examples - GeeksforGeeks
|
27 Feb, 2019
The Java.util.concurrent.atomic.AtomicIntegerArray.accumulateAndGet() is an inbuilt method in java that atomically updates the element at index i with the results of applying the given function to the current and given values, returning the updated value. The function should be side-effect-free, since it may be re-applied when attempted updates fail due to contention among threads. The function is applied with the current value at index i as its first argument, and the given update as the second argument.
Syntax:
public final int accumulateAndGet(int i, int x, IntBinaryOperator accumulatorFunction)
Parameters: The function accepts three parameters:
i – The index where update is to be mada.
x – The value to make operation with value at i
accumulatorFunction – A side-effect-free function of two arguments.Return value: The function returns the updated value which is in Integer.Below programs illustrate the above method:Program 1:// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where update is to be made int idx = 4; // Value to make operation with value at idx int x = 5; // Declaring the accumulatorFunction IntBinaryOperator add = (u, v) -> u + v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, add); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }}Output:The array : [1, 2, 3, 4, 5]
The array after update : [1, 2, 3, 4, 10]
Program 2:// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 17, 22, 33, 44, 55 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where update is to be made int idx = 0; // Value to make operation with value at idx int x = 6; // Declaring the accumulatorFunction IntBinaryOperator sub = (u, v) -> u - v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, sub); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }}Output:The array : [17, 22, 33, 44, 55]
The array after update : [11, 22, 33, 44, 55]
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#getAndAccumulate-int-int-java.util.function.IntBinaryOperator-My Personal Notes
arrow_drop_upSave
Return value: The function returns the updated value which is in Integer.
Below programs illustrate the above method:Program 1:
// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where update is to be made int idx = 4; // Value to make operation with value at idx int x = 5; // Declaring the accumulatorFunction IntBinaryOperator add = (u, v) -> u + v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, add); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }}
The array : [1, 2, 3, 4, 5]
The array after update : [1, 2, 3, 4, 10]
Program 2:
// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 17, 22, 33, 44, 55 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println("The array : " + arr); // Index where update is to be made int idx = 0; // Value to make operation with value at idx int x = 6; // Declaring the accumulatorFunction IntBinaryOperator sub = (u, v) -> u - v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, sub); // Displaying the AtomicIntegerArray System.out.println("The array after update : " + arr); }}
The array : [17, 22, 33, 44, 55]
The array after update : [11, 22, 33, 44, 55]
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#getAndAccumulate-int-int-java.util.function.IntBinaryOperator-
Java-AtomicIntegerArray
Java-concurrent-package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n27 Feb, 2019"
},
{
"code": null,
"e": 25736,
"s": 25225,
"text": "The Java.util.concurrent.atomic.AtomicIntegerArray.accumulateAndGet() is an inbuilt method in java that atomically updates the element at index i with the results of applying the given function to the current and given values, returning the updated value. The function should be side-effect-free, since it may be re-applied when attempted updates fail due to contention among threads. The function is applied with the current value at index i as its first argument, and the given update as the second argument."
},
{
"code": null,
"e": 25744,
"s": 25736,
"text": "Syntax:"
},
{
"code": null,
"e": 25831,
"s": 25744,
"text": "public final int accumulateAndGet(int i, int x, IntBinaryOperator accumulatorFunction)"
},
{
"code": null,
"e": 25882,
"s": 25831,
"text": "Parameters: The function accepts three parameters:"
},
{
"code": null,
"e": 25924,
"s": 25882,
"text": "i – The index where update is to be mada."
},
{
"code": null,
"e": 25972,
"s": 25924,
"text": "x – The value to make operation with value at i"
},
{
"code": null,
"e": 28558,
"s": 25972,
"text": "accumulatorFunction – A side-effect-free function of two arguments.Return value: The function returns the updated value which is in Integer.Below programs illustrate the above method:Program 1:// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where update is to be made int idx = 4; // Value to make operation with value at idx int x = 5; // Declaring the accumulatorFunction IntBinaryOperator add = (u, v) -> u + v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, add); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}Output:The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 4, 10]\nProgram 2:// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 17, 22, 33, 44, 55 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where update is to be made int idx = 0; // Value to make operation with value at idx int x = 6; // Declaring the accumulatorFunction IntBinaryOperator sub = (u, v) -> u - v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, sub); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}Output:The array : [17, 22, 33, 44, 55]\nThe array after update : [11, 22, 33, 44, 55]\nReference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#getAndAccumulate-int-int-java.util.function.IntBinaryOperator-My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28632,
"s": 28558,
"text": "Return value: The function returns the updated value which is in Integer."
},
{
"code": null,
"e": 28686,
"s": 28632,
"text": "Below programs illustrate the above method:Program 1:"
},
{
"code": "// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 1, 2, 3, 4, 5 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where update is to be made int idx = 4; // Value to make operation with value at idx int x = 5; // Declaring the accumulatorFunction IntBinaryOperator add = (u, v) -> u + v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, add); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}",
"e": 29693,
"s": 28686,
"text": null
},
{
"code": null,
"e": 29764,
"s": 29693,
"text": "The array : [1, 2, 3, 4, 5]\nThe array after update : [1, 2, 3, 4, 10]\n"
},
{
"code": null,
"e": 29775,
"s": 29764,
"text": "Program 2:"
},
{
"code": "// Java program that demonstrates// the accumulateAndGet() function import java.util.concurrent.atomic.AtomicIntegerArray;import java.util.function.IntBinaryOperator; public class GFG { public static void main(String args[]) { // Initializing an array int a[] = { 17, 22, 33, 44, 55 }; // Initializing an AtomicIntegerArray with array a AtomicIntegerArray arr = new AtomicIntegerArray(a); // Displaying the AtomicIntegerArray System.out.println(\"The array : \" + arr); // Index where update is to be made int idx = 0; // Value to make operation with value at idx int x = 6; // Declaring the accumulatorFunction IntBinaryOperator sub = (u, v) -> u - v; // Updating the value at idx // applying accumulatorFunction arr.accumulateAndGet(idx, x, sub); // Displaying the AtomicIntegerArray System.out.println(\"The array after update : \" + arr); }}",
"e": 30787,
"s": 29775,
"text": null
},
{
"code": null,
"e": 30867,
"s": 30787,
"text": "The array : [17, 22, 33, 44, 55]\nThe array after update : [11, 22, 33, 44, 55]\n"
},
{
"code": null,
"e": 31035,
"s": 30867,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicIntegerArray.html#getAndAccumulate-int-int-java.util.function.IntBinaryOperator-"
},
{
"code": null,
"e": 31059,
"s": 31035,
"text": "Java-AtomicIntegerArray"
},
{
"code": null,
"e": 31083,
"s": 31059,
"text": "Java-concurrent-package"
},
{
"code": null,
"e": 31098,
"s": 31083,
"text": "Java-Functions"
},
{
"code": null,
"e": 31103,
"s": 31098,
"text": "Java"
},
{
"code": null,
"e": 31108,
"s": 31103,
"text": "Java"
},
{
"code": null,
"e": 31206,
"s": 31108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31221,
"s": 31206,
"text": "Stream In Java"
},
{
"code": null,
"e": 31242,
"s": 31221,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31261,
"s": 31242,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31291,
"s": 31261,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31337,
"s": 31291,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31354,
"s": 31337,
"text": "Generics in Java"
},
{
"code": null,
"e": 31375,
"s": 31354,
"text": "Introduction to Java"
},
{
"code": null,
"e": 31418,
"s": 31375,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31454,
"s": 31418,
"text": "Internal Working of HashMap in Java"
}
] |
Bootstrap 4 | Tables - GeeksforGeeks
|
28 Apr, 2022
Bootstrap provides a series of classes that can be used to apply various styling to the tables such as changing the heading appearance, making the rows stripped, adding or removing borders, making rows hoverable, etc. Bootstrap also provides classes for making tables responsive.
Simple Table: The .table class is used to create a simple Bootstrap table. This class name is used with the <table> tag to create a table.
Syntax:
<table class="table"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table class --> <table class="table"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Stripped rows: The .table-stripped class is used to create an alternate dark and light rows. Use the combination of table and table-stripped classes within the <table> tag to create a striped table.
Syntax:
<table class="table table-stripped"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table and table-stripped classes --> <table class="table table-stripped"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Bordered Table: The .table-bordered class is used to add borders on all sides of the table and cell. Use the combination of table and table-bordered classes within the <table> tag to create bordered table.
Syntax:
<table class="table table-bordered"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table and table-bordered classes --> <table class="table table-bordered"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Hover Rows Table: The .table-hover class is used to add the hover effect (change background color to gray when the mouse moves over) on table rows. Use the combination of table and table-hover classes within the <table> tag to create a hover rows table.
Syntax:
<table class="table table-hover"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table and table-hover classes --> <table class="table table-hover"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Black/Dark Table: The .table-dark class is used to add the black background color of a table. Use the combination of table and table-dark classes within the <table> tag to create a dark table.
Syntax:
<table class="table table-dark"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table and table-dark classes --> <table class="table table-dark"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Dark Stripped Table: The .table-dark and .table-stripped classes are used to create a dark striped table. Use the combination of table, table-dark, and table-stripped classes within the <table> tag to create the dark striped table.
Syntax:
<table class="table table-dark table-stripped"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table and table-dark and table-stripped classes --> <table class="table table-dark table-stripped"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Dark Hoverable Table: The .table-dark and .table-hover classes are used to add the hover effect (change background color to dark gray when the mouse moves over) on table rows. Use the combination of table, table-dark, and table-hover classes within the <table> tag to create the dark hover effect table.
Syntax:
<table class="table table-dark table-hover"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table, table-dark and table-hover classes --> <table class="table table-dark table-hover"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Borderless Table: The .table-borderless is used to remove the border from the table. Use the combination of table and table-borderless classes within the <table> tag to create a borderless table.
Syntax:
<table class="table table-borderless"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table, table-borderless classes --> <table class="table table-borderless"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Colored table: Bootstrap provides a number of contextual classes that can be used to color the entire row or a single cell of a table. These classes should be used with a light table and not with a dark table for a better appearance. The list of contextual classes is given below.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table class --> <table class="table"> <thead> <tr class="table-primary"> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr class="table-secondary"> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr class="table-success"> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class="table-danger"> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Dark Colored Table: To color the dark tables, background-color classes of Bootstrap will use.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table and table-dark classes --> <table class="table table-dark"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr class="bg-secondary"> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr class="bg-success"> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class="bg-danger"> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Small Table: The .table-sm class is used to create a small table by reducing the cell padding. Use the combination of table, table-bordered, and table-sm classes within the <table> tag to create a bordered small table.
Syntax:
<table class="table table-bordered table-sm"> Table Contents... <table>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table, table-bordered and table-sm classes --> <table class="table table-bordered table-sm"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">Name</th> <th scope="col">City</th> <th scope="col">Age</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>
Output:
Responsive Tables: The .table-responsive class is used to create a responsive table. To make the table responsive on all viewport sizes, wrap the table within an opening and closing <div> tags, having class table-responsive within the opening <div> tag. Similarly, to make the table responsive depending upon the viewport size, use class table-responsive{-sm|-md|-lg|-xl}.
In case of viewport specific responsive table, the table will become responsive if the viewport size is less than the viewport specified by the class table-responsive{-sm|-md|-lg|-xl}. The list of responsive table viewports size are given below:
Syntax:
<div class="table-responsive"> Table <div>
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Tables</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <div class="container"> <h1 style="text-align:center;color:green;"> GeeksforGeeks </h1> <!-- Bootstrap table-responsive class --> <div class="table-responsive-xl"> <!-- Bootstrap table class --> <table class="table"> <thead> <tr> <th scope="col">S. No.</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Email</th> <th scope="col">Contact No.</th> <th scope="col">Gender</th> <th scope="col">City</th> <th scope="col">Country</th> <th scope="col">Pin Code</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Ajit</td> <td>Singh</td> <td>ajt@gfg.com</td> <td>XXXXXXXXXX</td> <td>Male</td> <td>Noida</td> <td>India</td> <td>201301</td> </tr> </tbody> </table> </div> </div></body></html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
ruhelaa48
varshagumber28
sahilintern
Bootstrap-4
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 29685,
"s": 29657,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 29965,
"s": 29685,
"text": "Bootstrap provides a series of classes that can be used to apply various styling to the tables such as changing the heading appearance, making the rows stripped, adding or removing borders, making rows hoverable, etc. Bootstrap also provides classes for making tables responsive."
},
{
"code": null,
"e": 30104,
"s": 29965,
"text": "Simple Table: The .table class is used to create a simple Bootstrap table. This class name is used with the <table> tag to create a table."
},
{
"code": null,
"e": 30112,
"s": 30104,
"text": "Syntax:"
},
{
"code": null,
"e": 30160,
"s": 30112,
"text": "<table class=\"table\"> Table Contents... <table>"
},
{
"code": null,
"e": 30169,
"s": 30160,
"text": "Example:"
},
{
"code": null,
"e": 30174,
"s": 30169,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table class --> <table class=\"table\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 31845,
"s": 30174,
"text": null
},
{
"code": null,
"e": 31853,
"s": 31845,
"text": "Output:"
},
{
"code": null,
"e": 32052,
"s": 31853,
"text": "Stripped rows: The .table-stripped class is used to create an alternate dark and light rows. Use the combination of table and table-stripped classes within the <table> tag to create a striped table."
},
{
"code": null,
"e": 32060,
"s": 32052,
"text": "Syntax:"
},
{
"code": null,
"e": 32123,
"s": 32060,
"text": "<table class=\"table table-stripped\"> Table Contents... <table>"
},
{
"code": null,
"e": 32132,
"s": 32123,
"text": "Example:"
},
{
"code": null,
"e": 32137,
"s": 32132,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table and table-stripped classes --> <table class=\"table table-stripped\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 33844,
"s": 32137,
"text": null
},
{
"code": null,
"e": 33852,
"s": 33844,
"text": "Output:"
},
{
"code": null,
"e": 34058,
"s": 33852,
"text": "Bordered Table: The .table-bordered class is used to add borders on all sides of the table and cell. Use the combination of table and table-bordered classes within the <table> tag to create bordered table."
},
{
"code": null,
"e": 34066,
"s": 34058,
"text": "Syntax:"
},
{
"code": null,
"e": 34129,
"s": 34066,
"text": "<table class=\"table table-bordered\"> Table Contents... <table>"
},
{
"code": null,
"e": 34138,
"s": 34129,
"text": "Example:"
},
{
"code": null,
"e": 34143,
"s": 34138,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table and table-bordered classes --> <table class=\"table table-bordered\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 35850,
"s": 34143,
"text": null
},
{
"code": null,
"e": 35858,
"s": 35850,
"text": "Output:"
},
{
"code": null,
"e": 36112,
"s": 35858,
"text": "Hover Rows Table: The .table-hover class is used to add the hover effect (change background color to gray when the mouse moves over) on table rows. Use the combination of table and table-hover classes within the <table> tag to create a hover rows table."
},
{
"code": null,
"e": 36120,
"s": 36112,
"text": "Syntax:"
},
{
"code": null,
"e": 36180,
"s": 36120,
"text": "<table class=\"table table-hover\"> Table Contents... <table>"
},
{
"code": null,
"e": 36189,
"s": 36180,
"text": "Example:"
},
{
"code": null,
"e": 36194,
"s": 36189,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table and table-hover classes --> <table class=\"table table-hover\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 37895,
"s": 36194,
"text": null
},
{
"code": null,
"e": 37903,
"s": 37895,
"text": "Output:"
},
{
"code": null,
"e": 38096,
"s": 37903,
"text": "Black/Dark Table: The .table-dark class is used to add the black background color of a table. Use the combination of table and table-dark classes within the <table> tag to create a dark table."
},
{
"code": null,
"e": 38104,
"s": 38096,
"text": "Syntax:"
},
{
"code": null,
"e": 38163,
"s": 38104,
"text": "<table class=\"table table-dark\"> Table Contents... <table>"
},
{
"code": null,
"e": 38172,
"s": 38163,
"text": "Example:"
},
{
"code": null,
"e": 38177,
"s": 38172,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table and table-dark classes --> <table class=\"table table-dark\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 39876,
"s": 38177,
"text": null
},
{
"code": null,
"e": 39884,
"s": 39876,
"text": "Output:"
},
{
"code": null,
"e": 40116,
"s": 39884,
"text": "Dark Stripped Table: The .table-dark and .table-stripped classes are used to create a dark striped table. Use the combination of table, table-dark, and table-stripped classes within the <table> tag to create the dark striped table."
},
{
"code": null,
"e": 40124,
"s": 40116,
"text": "Syntax:"
},
{
"code": null,
"e": 40198,
"s": 40124,
"text": "<table class=\"table table-dark table-stripped\"> Table Contents... <table>"
},
{
"code": null,
"e": 40207,
"s": 40198,
"text": "Example:"
},
{
"code": null,
"e": 40212,
"s": 40207,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table and table-dark and table-stripped classes --> <table class=\"table table-dark table-stripped\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 41945,
"s": 40212,
"text": null
},
{
"code": null,
"e": 41953,
"s": 41945,
"text": "Output:"
},
{
"code": null,
"e": 42257,
"s": 41953,
"text": "Dark Hoverable Table: The .table-dark and .table-hover classes are used to add the hover effect (change background color to dark gray when the mouse moves over) on table rows. Use the combination of table, table-dark, and table-hover classes within the <table> tag to create the dark hover effect table."
},
{
"code": null,
"e": 42265,
"s": 42257,
"text": "Syntax:"
},
{
"code": null,
"e": 42336,
"s": 42265,
"text": "<table class=\"table table-dark table-hover\"> Table Contents... <table>"
},
{
"code": null,
"e": 42345,
"s": 42336,
"text": "Example:"
},
{
"code": null,
"e": 42350,
"s": 42345,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table, table-dark and table-hover classes --> <table class=\"table table-dark table-hover\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 44074,
"s": 42350,
"text": null
},
{
"code": null,
"e": 44082,
"s": 44074,
"text": "Output:"
},
{
"code": null,
"e": 44278,
"s": 44082,
"text": "Borderless Table: The .table-borderless is used to remove the border from the table. Use the combination of table and table-borderless classes within the <table> tag to create a borderless table."
},
{
"code": null,
"e": 44286,
"s": 44278,
"text": "Syntax:"
},
{
"code": null,
"e": 44351,
"s": 44286,
"text": "<table class=\"table table-borderless\"> Table Contents... <table>"
},
{
"code": null,
"e": 44360,
"s": 44351,
"text": "Example:"
},
{
"code": null,
"e": 44365,
"s": 44360,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table, table-borderless classes --> <table class=\"table table-borderless\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 46073,
"s": 44365,
"text": null
},
{
"code": null,
"e": 46081,
"s": 46073,
"text": "Output:"
},
{
"code": null,
"e": 46362,
"s": 46081,
"text": "Colored table: Bootstrap provides a number of contextual classes that can be used to color the entire row or a single cell of a table. These classes should be used with a light table and not with a dark table for a better appearance. The list of contextual classes is given below."
},
{
"code": null,
"e": 46371,
"s": 46362,
"text": "Example:"
},
{
"code": null,
"e": 46376,
"s": 46371,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table class --> <table class=\"table\"> <thead> <tr class=\"table-primary\"> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr class=\"table-secondary\"> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr class=\"table-success\"> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class=\"table-danger\"> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 48136,
"s": 46376,
"text": null
},
{
"code": null,
"e": 48144,
"s": 48136,
"text": "Output:"
},
{
"code": null,
"e": 48238,
"s": 48144,
"text": "Dark Colored Table: To color the dark tables, background-color classes of Bootstrap will use."
},
{
"code": null,
"e": 48247,
"s": 48238,
"text": "Example:"
},
{
"code": null,
"e": 48252,
"s": 48247,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table and table-dark classes --> <table class=\"table table-dark\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr class=\"bg-secondary\"> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr class=\"bg-success\"> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class=\"bg-danger\"> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 50009,
"s": 48252,
"text": null
},
{
"code": null,
"e": 50017,
"s": 50009,
"text": "Output:"
},
{
"code": null,
"e": 50236,
"s": 50017,
"text": "Small Table: The .table-sm class is used to create a small table by reducing the cell padding. Use the combination of table, table-bordered, and table-sm classes within the <table> tag to create a bordered small table."
},
{
"code": null,
"e": 50244,
"s": 50236,
"text": "Syntax:"
},
{
"code": null,
"e": 50316,
"s": 50244,
"text": "<table class=\"table table-bordered table-sm\"> Table Contents... <table>"
},
{
"code": null,
"e": 50325,
"s": 50316,
"text": "Example:"
},
{
"code": null,
"e": 50330,
"s": 50325,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table, table-bordered and table-sm classes --> <table class=\"table table-bordered table-sm\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">Name</th> <th scope=\"col\">City</th> <th scope=\"col\">Age</th> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</th> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</th> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</th> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div></body></html>",
"e": 52056,
"s": 50330,
"text": null
},
{
"code": null,
"e": 52064,
"s": 52056,
"text": "Output:"
},
{
"code": null,
"e": 52437,
"s": 52064,
"text": "Responsive Tables: The .table-responsive class is used to create a responsive table. To make the table responsive on all viewport sizes, wrap the table within an opening and closing <div> tags, having class table-responsive within the opening <div> tag. Similarly, to make the table responsive depending upon the viewport size, use class table-responsive{-sm|-md|-lg|-xl}."
},
{
"code": null,
"e": 52683,
"s": 52437,
"text": "In case of viewport specific responsive table, the table will become responsive if the viewport size is less than the viewport specified by the class table-responsive{-sm|-md|-lg|-xl}. The list of responsive table viewports size are given below:"
},
{
"code": null,
"e": 52691,
"s": 52683,
"text": "Syntax:"
},
{
"code": null,
"e": 52734,
"s": 52691,
"text": "<div class=\"table-responsive\"> Table <div>"
},
{
"code": null,
"e": 52743,
"s": 52734,
"text": "Example:"
},
{
"code": null,
"e": 52748,
"s": 52743,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Tables</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <div class=\"container\"> <h1 style=\"text-align:center;color:green;\"> GeeksforGeeks </h1> <!-- Bootstrap table-responsive class --> <div class=\"table-responsive-xl\"> <!-- Bootstrap table class --> <table class=\"table\"> <thead> <tr> <th scope=\"col\">S. No.</th> <th scope=\"col\">First Name</th> <th scope=\"col\">Last Name</th> <th scope=\"col\">Email</th> <th scope=\"col\">Contact No.</th> <th scope=\"col\">Gender</th> <th scope=\"col\">City</th> <th scope=\"col\">Country</th> <th scope=\"col\">Pin Code</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Ajit</td> <td>Singh</td> <td>ajt@gfg.com</td> <td>XXXXXXXXXX</td> <td>Male</td> <td>Noida</td> <td>India</td> <td>201301</td> </tr> </tbody> </table> </div> </div></body></html>",
"e": 54693,
"s": 52748,
"text": null
},
{
"code": null,
"e": 54701,
"s": 54693,
"text": "Output:"
},
{
"code": null,
"e": 54720,
"s": 54701,
"text": "Supported Browser:"
},
{
"code": null,
"e": 54734,
"s": 54720,
"text": "Google Chrome"
},
{
"code": null,
"e": 54752,
"s": 54734,
"text": "Internet Explorer"
},
{
"code": null,
"e": 54760,
"s": 54752,
"text": "Firefox"
},
{
"code": null,
"e": 54766,
"s": 54760,
"text": "Opera"
},
{
"code": null,
"e": 54773,
"s": 54766,
"text": "Safari"
},
{
"code": null,
"e": 54785,
"s": 54773,
"text": "ysachin2314"
},
{
"code": null,
"e": 54795,
"s": 54785,
"text": "ruhelaa48"
},
{
"code": null,
"e": 54810,
"s": 54795,
"text": "varshagumber28"
},
{
"code": null,
"e": 54822,
"s": 54810,
"text": "sahilintern"
},
{
"code": null,
"e": 54834,
"s": 54822,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 54844,
"s": 54834,
"text": "Bootstrap"
},
{
"code": null,
"e": 54861,
"s": 54844,
"text": "Web Technologies"
},
{
"code": null,
"e": 54959,
"s": 54861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 55009,
"s": 54959,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 55038,
"s": 55009,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 55079,
"s": 55038,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 55135,
"s": 55079,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 55176,
"s": 55135,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 55216,
"s": 55176,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 55249,
"s": 55216,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 55294,
"s": 55249,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 55337,
"s": 55294,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
AngularJS | Services - GeeksforGeeks
|
21 May, 2019
Services are used to create variables/data that can be shared and can be used outside the component in which it is defined.
STEP #1: Creating a service:-ng g s service-names is a short-form for service.This creates two files service-name.service.spec.ts which is not supposed to be changed and a service-name.service.ts.
ng g s service-name
s is a short-form for service.This creates two files service-name.service.spec.ts which is not supposed to be changed and a service-name.service.ts.
STEP #2: After the service is created, we have to include it in the providers of app.module.tsproviders: [Service-nameService],here, the first letter of the service-name should be capital followed by Service written without any space.
here, the first letter of the service-name should be capital followed by Service written without any space.
STEP #3: So we have to now make changes in service-name.service.ts create a json variable which is supposed to be made available to various componentsSailors = [22, ‘Dustin’, 7];Sailors variable here is an array.
STEP #4: In app.component.ts make the following changes:import the service among the rest of the required importsExample:-import { Service-nameService } from './service-name.service';just like the way we did it in providers.Create a variable of any type: newData without mentioning any typeIn constructor define a property of the Service typeconstructor(private demoService: ServiceService) {}Also create an ngOnInit method: ngOnInit(): void {
this.newData=this.demoService.Sailors;
import { Service-nameService } from './service-name.service';
just like the way we did it in providers.
constructor(private demoService: ServiceService) {}
ngOnInit(): void {
this.newData=this.demoService.Sailors;
STEP #5: In app.component.html we will print the data stored in newData :{{newData}}Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.tsSyntax (Example #1):serice.service.tsimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root'})export class ServiceService { Sailors = [ { id: 22, name: 'Dustin', rating: 7 }, { id: 29, name: 'Brutus', rating: 1 }, { id: 31, name: 'Lubber', rating: 8 }, { id: 32, name: 'Andy', rating: 8 }, { id: 58, name: 'Rusty', rating: 10 }, { id: 64, name: 'Horatio', rating: 7 }, { id: 71, name: 'Zorba', rating: 10 }, { id: 74, name: 'Horatio', rating: 9 } ]; constructor() { } getData() { return 'This is the list of sailors and their corresponding ratings'; }}In app.component.tsimport { Component } from '@angular/core';import { ServiceService } from './service.service';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { newData; message:string=''; constructor(private demoService: ServiceService) {} ngOnInit(): void { this.newData=this.demoService.Sailors; this.message=this.demoService.getData(); }}app.component.html<b>Service Example</b><h5>{{ message }}</h5><p> ID Name Rating</p><div *ngFor="let m of newData;"> <p>{{m.id}} {{m.name}} {{m.rating}}</p></div>Output:References:https://coursetro.com/posts/code/61/Angular-4-Services-TutorialMy Personal Notes
arrow_drop_upSave
{{newData}}
Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.ts
Syntax (Example #1):serice.service.ts
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root'})export class ServiceService { Sailors = [ { id: 22, name: 'Dustin', rating: 7 }, { id: 29, name: 'Brutus', rating: 1 }, { id: 31, name: 'Lubber', rating: 8 }, { id: 32, name: 'Andy', rating: 8 }, { id: 58, name: 'Rusty', rating: 10 }, { id: 64, name: 'Horatio', rating: 7 }, { id: 71, name: 'Zorba', rating: 10 }, { id: 74, name: 'Horatio', rating: 9 } ]; constructor() { } getData() { return 'This is the list of sailors and their corresponding ratings'; }}
In app.component.ts
import { Component } from '@angular/core';import { ServiceService } from './service.service';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { newData; message:string=''; constructor(private demoService: ServiceService) {} ngOnInit(): void { this.newData=this.demoService.Sailors; this.message=this.demoService.getData(); }}
app.component.html
<b>Service Example</b><h5>{{ message }}</h5><p> ID Name Rating</p><div *ngFor="let m of newData;"> <p>{{m.id}} {{m.name}} {{m.rating}}</p></div>
Output:
References:https://coursetro.com/posts/code/61/Angular-4-Services-Tutorial
Picked
AngularJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
Angular PrimeNG Calendar Component
What is AOT and JIT Compiler in Angular ?
How to set focus on input field automatically on page load in AngularJS ?
Angular 10 (blur) Event
Angular PrimeNG Messages Component
|
[
{
"code": null,
"e": 29516,
"s": 29488,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 29640,
"s": 29516,
"text": "Services are used to create variables/data that can be shared and can be used outside the component in which it is defined."
},
{
"code": null,
"e": 29837,
"s": 29640,
"text": "STEP #1: Creating a service:-ng g s service-names is a short-form for service.This creates two files service-name.service.spec.ts which is not supposed to be changed and a service-name.service.ts."
},
{
"code": null,
"e": 29857,
"s": 29837,
"text": "ng g s service-name"
},
{
"code": null,
"e": 30006,
"s": 29857,
"text": "s is a short-form for service.This creates two files service-name.service.spec.ts which is not supposed to be changed and a service-name.service.ts."
},
{
"code": null,
"e": 30241,
"s": 30006,
"text": "STEP #2: After the service is created, we have to include it in the providers of app.module.tsproviders: [Service-nameService],here, the first letter of the service-name should be capital followed by Service written without any space."
},
{
"code": null,
"e": 30349,
"s": 30241,
"text": "here, the first letter of the service-name should be capital followed by Service written without any space."
},
{
"code": null,
"e": 30562,
"s": 30349,
"text": "STEP #3: So we have to now make changes in service-name.service.ts create a json variable which is supposed to be made available to various componentsSailors = [22, ‘Dustin’, 7];Sailors variable here is an array."
},
{
"code": null,
"e": 31053,
"s": 30562,
"text": "STEP #4: In app.component.ts make the following changes:import the service among the rest of the required importsExample:-import { Service-nameService } from './service-name.service';just like the way we did it in providers.Create a variable of any type: newData without mentioning any typeIn constructor define a property of the Service typeconstructor(private demoService: ServiceService) {}Also create an ngOnInit method: ngOnInit(): void {\n this.newData=this.demoService.Sailors;\n"
},
{
"code": null,
"e": 31115,
"s": 31053,
"text": "import { Service-nameService } from './service-name.service';"
},
{
"code": null,
"e": 31157,
"s": 31115,
"text": "just like the way we did it in providers."
},
{
"code": null,
"e": 31209,
"s": 31157,
"text": "constructor(private demoService: ServiceService) {}"
},
{
"code": null,
"e": 31276,
"s": 31209,
"text": " ngOnInit(): void {\n this.newData=this.demoService.Sailors;\n"
},
{
"code": null,
"e": 32863,
"s": 31276,
"text": "STEP #5: In app.component.html we will print the data stored in newData :{{newData}}Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.tsSyntax (Example #1):serice.service.tsimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root'})export class ServiceService { Sailors = [ { id: 22, name: 'Dustin', rating: 7 }, { id: 29, name: 'Brutus', rating: 1 }, { id: 31, name: 'Lubber', rating: 8 }, { id: 32, name: 'Andy', rating: 8 }, { id: 58, name: 'Rusty', rating: 10 }, { id: 64, name: 'Horatio', rating: 7 }, { id: 71, name: 'Zorba', rating: 10 }, { id: 74, name: 'Horatio', rating: 9 } ]; constructor() { } getData() { return 'This is the list of sailors and their corresponding ratings'; }}In app.component.tsimport { Component } from '@angular/core';import { ServiceService } from './service.service';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { newData; message:string=''; constructor(private demoService: ServiceService) {} ngOnInit(): void { this.newData=this.demoService.Sailors; this.message=this.demoService.getData(); }}app.component.html<b>Service Example</b><h5>{{ message }}</h5><p> ID Name Rating</p><div *ngFor=\"let m of newData;\"> <p>{{m.id}} {{m.name}} {{m.rating}}</p></div>Output:References:https://coursetro.com/posts/code/61/Angular-4-Services-TutorialMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32875,
"s": 32863,
"text": "{{newData}}"
},
{
"code": null,
"e": 32978,
"s": 32875,
"text": "Note: As we have added ngFor in app.component.html we will have to import FormsModule in app.module.ts"
},
{
"code": null,
"e": 33016,
"s": 32978,
"text": "Syntax (Example #1):serice.service.ts"
},
{
"code": "import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root'})export class ServiceService { Sailors = [ { id: 22, name: 'Dustin', rating: 7 }, { id: 29, name: 'Brutus', rating: 1 }, { id: 31, name: 'Lubber', rating: 8 }, { id: 32, name: 'Andy', rating: 8 }, { id: 58, name: 'Rusty', rating: 10 }, { id: 64, name: 'Horatio', rating: 7 }, { id: 71, name: 'Zorba', rating: 10 }, { id: 74, name: 'Horatio', rating: 9 } ]; constructor() { } getData() { return 'This is the list of sailors and their corresponding ratings'; }}",
"e": 33656,
"s": 33016,
"text": null
},
{
"code": null,
"e": 33676,
"s": 33656,
"text": "In app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { ServiceService } from './service.service';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { newData; message:string=''; constructor(private demoService: ServiceService) {} ngOnInit(): void { this.newData=this.demoService.Sailors; this.message=this.demoService.getData(); }}",
"e": 34101,
"s": 33676,
"text": null
},
{
"code": null,
"e": 34120,
"s": 34101,
"text": "app.component.html"
},
{
"code": "<b>Service Example</b><h5>{{ message }}</h5><p> ID Name Rating</p><div *ngFor=\"let m of newData;\"> <p>{{m.id}} {{m.name}} {{m.rating}}</p></div>",
"e": 34268,
"s": 34120,
"text": null
},
{
"code": null,
"e": 34276,
"s": 34268,
"text": "Output:"
},
{
"code": null,
"e": 34351,
"s": 34276,
"text": "References:https://coursetro.com/posts/code/61/Angular-4-Services-Tutorial"
},
{
"code": null,
"e": 34358,
"s": 34351,
"text": "Picked"
},
{
"code": null,
"e": 34368,
"s": 34358,
"text": "AngularJS"
},
{
"code": null,
"e": 34466,
"s": 34368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34486,
"s": 34466,
"text": "Angular File Upload"
},
{
"code": null,
"e": 34521,
"s": 34486,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 34543,
"s": 34521,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 34574,
"s": 34543,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 34662,
"s": 34574,
"text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?"
},
{
"code": null,
"e": 34697,
"s": 34662,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 34739,
"s": 34697,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 34813,
"s": 34739,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 34837,
"s": 34813,
"text": "Angular 10 (blur) Event"
}
] |
What is Query in LINQ? - GeeksforGeeks
|
06 Aug, 2021
A query is an expression which is used to recover data from the data source. Generally, queries are expressed in some specialized language. Different types of languages are developed to access the different type of data sources like SQL for a relational database, XQuery for XML, etc. So, every time the developer needs to learn different type of languages for a different type of data sources, this situation leads to the developer to develop a language through which they can access any type of data source with the help of a single language. So this requirement is fulfilled by the LINQ query, using LINQ query you can access any type of data source like XML document, SQL database, ADO.NET dataset, etc. provided by the LINQ provider. In LINQ query, the query always returns the result as an object, which allows you to use the object-oriented approach on the result and not to worry about transforming different data formats into an object.
Example:
C#
// C# program to demonstrate the // Simple query exampleusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Creating data source string[] language = {"C#", "VB", "Java", "C++", "C", "Perl", "Ruby", "Python"}; // Creating a query to get the // value from the data source var result = from lang in language where lang.Contains('C') select lang; // display the result of the query foreach(var l in result) { Console.WriteLine(l); } }}
Output:
C#
C++
C
In the above example, the LINQ query contains three different actions:
Get data source: In the above example, the data source is an array.string[]language = {"C#", "VB", "Java", "C++", "C", "Perl", "Ruby", "Python"};Which implicitly support generic IEnumerable<T> interface. In LINQ query, it is a basic rule that the data source of any object must support IEnumerable<T> interface or interface that inherits from the IEnumerable<T> interface.Create Query: Now the next step is to create a query. With the help of the query, you can get the information from the data source. The query is stored in the query variable and which is initialized with the query expression. The query expression contains the operation that you want to perform on the data source, generally, query expression contains three clauses, i.e, from, where, and select. The from clause is used to specify the data source, where clause applies the filter and select clause provides the type of the returned items. Example:var result = from lang in language
where lang.Contains('C')
select lang;Here result in the query variable which is initialized with a query expression.Note: The query variable itself does not perform any operation. It only used to store the result of the query expression and used when the query executes.Execute Query: The query variable stores the result of the query expression. But the execution of the query takes place when you iterate over the query variable using foreach loop to display the result of the query. When you use the foreach loop to execute the query, then it is known as deferred execution. In the above example, we use deferred execution.foreach(var l in result){
Console.WriteLine(l);
}
Get data source: In the above example, the data source is an array.string[]language = {"C#", "VB", "Java", "C++", "C", "Perl", "Ruby", "Python"};Which implicitly support generic IEnumerable<T> interface. In LINQ query, it is a basic rule that the data source of any object must support IEnumerable<T> interface or interface that inherits from the IEnumerable<T> interface.
string[]language = {"C#", "VB", "Java", "C++", "C", "Perl", "Ruby", "Python"};
Which implicitly support generic IEnumerable<T> interface. In LINQ query, it is a basic rule that the data source of any object must support IEnumerable<T> interface or interface that inherits from the IEnumerable<T> interface.
Create Query: Now the next step is to create a query. With the help of the query, you can get the information from the data source. The query is stored in the query variable and which is initialized with the query expression. The query expression contains the operation that you want to perform on the data source, generally, query expression contains three clauses, i.e, from, where, and select. The from clause is used to specify the data source, where clause applies the filter and select clause provides the type of the returned items. Example:var result = from lang in language
where lang.Contains('C')
select lang;Here result in the query variable which is initialized with a query expression.Note: The query variable itself does not perform any operation. It only used to store the result of the query expression and used when the query executes.
var result = from lang in language
where lang.Contains('C')
select lang;
Here result in the query variable which is initialized with a query expression.Note: The query variable itself does not perform any operation. It only used to store the result of the query expression and used when the query executes.
Execute Query: The query variable stores the result of the query expression. But the execution of the query takes place when you iterate over the query variable using foreach loop to display the result of the query. When you use the foreach loop to execute the query, then it is known as deferred execution. In the above example, we use deferred execution.foreach(var l in result){
Console.WriteLine(l);
}
foreach(var l in result){
Console.WriteLine(l);
}
anikaseth98
CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 26495,
"s": 25547,
"text": "A query is an expression which is used to recover data from the data source. Generally, queries are expressed in some specialized language. Different types of languages are developed to access the different type of data sources like SQL for a relational database, XQuery for XML, etc. So, every time the developer needs to learn different type of languages for a different type of data sources, this situation leads to the developer to develop a language through which they can access any type of data source with the help of a single language. So this requirement is fulfilled by the LINQ query, using LINQ query you can access any type of data source like XML document, SQL database, ADO.NET dataset, etc. provided by the LINQ provider. In LINQ query, the query always returns the result as an object, which allows you to use the object-oriented approach on the result and not to worry about transforming different data formats into an object. "
},
{
"code": null,
"e": 26505,
"s": 26495,
"text": "Example: "
},
{
"code": null,
"e": 26508,
"s": 26505,
"text": "C#"
},
{
"code": "// C# program to demonstrate the // Simple query exampleusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Creating data source string[] language = {\"C#\", \"VB\", \"Java\", \"C++\", \"C\", \"Perl\", \"Ruby\", \"Python\"}; // Creating a query to get the // value from the data source var result = from lang in language where lang.Contains('C') select lang; // display the result of the query foreach(var l in result) { Console.WriteLine(l); } }}",
"e": 27138,
"s": 26508,
"text": null
},
{
"code": null,
"e": 27147,
"s": 27138,
"text": "Output: "
},
{
"code": null,
"e": 27156,
"s": 27147,
"text": "C#\nC++\nC"
},
{
"code": null,
"e": 27228,
"s": 27156,
"text": "In the above example, the LINQ query contains three different actions: "
},
{
"code": null,
"e": 28912,
"s": 27228,
"text": "Get data source: In the above example, the data source is an array.string[]language = {\"C#\", \"VB\", \"Java\", \"C++\", \"C\", \"Perl\", \"Ruby\", \"Python\"};Which implicitly support generic IEnumerable<T> interface. In LINQ query, it is a basic rule that the data source of any object must support IEnumerable<T> interface or interface that inherits from the IEnumerable<T> interface.Create Query: Now the next step is to create a query. With the help of the query, you can get the information from the data source. The query is stored in the query variable and which is initialized with the query expression. The query expression contains the operation that you want to perform on the data source, generally, query expression contains three clauses, i.e, from, where, and select. The from clause is used to specify the data source, where clause applies the filter and select clause provides the type of the returned items. Example:var result = from lang in language\n where lang.Contains('C')\n select lang;Here result in the query variable which is initialized with a query expression.Note: The query variable itself does not perform any operation. It only used to store the result of the query expression and used when the query executes.Execute Query: The query variable stores the result of the query expression. But the execution of the query takes place when you iterate over the query variable using foreach loop to display the result of the query. When you use the foreach loop to execute the query, then it is known as deferred execution. In the above example, we use deferred execution.foreach(var l in result){\n\n Console.WriteLine(l);\n }"
},
{
"code": null,
"e": 29285,
"s": 28912,
"text": "Get data source: In the above example, the data source is an array.string[]language = {\"C#\", \"VB\", \"Java\", \"C++\", \"C\", \"Perl\", \"Ruby\", \"Python\"};Which implicitly support generic IEnumerable<T> interface. In LINQ query, it is a basic rule that the data source of any object must support IEnumerable<T> interface or interface that inherits from the IEnumerable<T> interface."
},
{
"code": null,
"e": 29364,
"s": 29285,
"text": "string[]language = {\"C#\", \"VB\", \"Java\", \"C++\", \"C\", \"Perl\", \"Ruby\", \"Python\"};"
},
{
"code": null,
"e": 29592,
"s": 29364,
"text": "Which implicitly support generic IEnumerable<T> interface. In LINQ query, it is a basic rule that the data source of any object must support IEnumerable<T> interface or interface that inherits from the IEnumerable<T> interface."
},
{
"code": null,
"e": 30486,
"s": 29592,
"text": "Create Query: Now the next step is to create a query. With the help of the query, you can get the information from the data source. The query is stored in the query variable and which is initialized with the query expression. The query expression contains the operation that you want to perform on the data source, generally, query expression contains three clauses, i.e, from, where, and select. The from clause is used to specify the data source, where clause applies the filter and select clause provides the type of the returned items. Example:var result = from lang in language\n where lang.Contains('C')\n select lang;Here result in the query variable which is initialized with a query expression.Note: The query variable itself does not perform any operation. It only used to store the result of the query expression and used when the query executes."
},
{
"code": null,
"e": 30599,
"s": 30486,
"text": "var result = from lang in language\n where lang.Contains('C')\n select lang;"
},
{
"code": null,
"e": 30833,
"s": 30599,
"text": "Here result in the query variable which is initialized with a query expression.Note: The query variable itself does not perform any operation. It only used to store the result of the query expression and used when the query executes."
},
{
"code": null,
"e": 31252,
"s": 30833,
"text": "Execute Query: The query variable stores the result of the query expression. But the execution of the query takes place when you iterate over the query variable using foreach loop to display the result of the query. When you use the foreach loop to execute the query, then it is known as deferred execution. In the above example, we use deferred execution.foreach(var l in result){\n\n Console.WriteLine(l);\n }"
},
{
"code": null,
"e": 31315,
"s": 31252,
"text": "foreach(var l in result){\n\n Console.WriteLine(l);\n }"
},
{
"code": null,
"e": 31327,
"s": 31315,
"text": "anikaseth98"
},
{
"code": null,
"e": 31339,
"s": 31327,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 31342,
"s": 31339,
"text": "C#"
},
{
"code": null,
"e": 31440,
"s": 31342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31463,
"s": 31440,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 31491,
"s": 31463,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 31508,
"s": 31491,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 31530,
"s": 31508,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 31559,
"s": 31530,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 31599,
"s": 31559,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 31622,
"s": 31599,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 31662,
"s": 31622,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 31705,
"s": 31662,
"text": "C# | How to insert an element in an Array?"
}
] |
Batch Script - Length of an Array - GeeksforGeeks
|
28 Nov, 2021
The length of the array is the number of elements in the array. The index of the array starts from “0” to “N-1” where N is a number of elements.
For example
arr[0]=1
arr[1]=2
arr[2]=3
Here we can see that the index starts from 0 and ends with 2 . So, we know that the index of the element goes from 0 to N-1. Now, N-1=2, and hence the value of N becomes 3 i.e. N=3, where N is number of elements in the array.
In the batch script, there is no function to find the length of the array direct so we have to iterate the elements of the array.
First, open the notepad and write the below command.
@echo off
:: Here an array is defined
set array[0]=1
set array[1]=4
set array[2]=9
set array[3]=10
:: Here we initializing an variable named len to calculate length of array
set len=0
:: To iterate the element of array
:Loop
:: It will check if the element is defined or not
if defined array[%len%] (
set /a len+=1
GOTO :Loop
)
echo The length of the array is %len%
pause
Save the above file with “.bat” extension and run the file.
Output :
The length of the array is 4
First, we create an array to calculate the length.
After this, we have to initialize a variable to calculate the length of the array. Above we initialize len=0
Now we have to iterate the elements of the array to calculate the length of the array.
To check the element is exists or not in the array we have to put an if statement as shown in the above code.
In case if statement is true then there is an increment in len.
In case if statement is false then it will exit from the loop and return the length of the array.
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25797,
"s": 25651,
"text": "The length of the array is the number of elements in the array. The index of the array starts from “0” to “N-1” where N is a number of elements. "
},
{
"code": null,
"e": 25810,
"s": 25797,
"text": "For example "
},
{
"code": null,
"e": 25837,
"s": 25810,
"text": "arr[0]=1\narr[1]=2\narr[2]=3"
},
{
"code": null,
"e": 26064,
"s": 25837,
"text": "Here we can see that the index starts from 0 and ends with 2 . So, we know that the index of the element goes from 0 to N-1. Now, N-1=2, and hence the value of N becomes 3 i.e. N=3, where N is number of elements in the array. "
},
{
"code": null,
"e": 26194,
"s": 26064,
"text": "In the batch script, there is no function to find the length of the array direct so we have to iterate the elements of the array."
},
{
"code": null,
"e": 26247,
"s": 26194,
"text": "First, open the notepad and write the below command."
},
{
"code": null,
"e": 26632,
"s": 26247,
"text": "@echo off \n:: Here an array is defined\nset array[0]=1 \nset array[1]=4 \nset array[2]=9 \nset array[3]=10 \n\n\n:: Here we initializing an variable named len to calculate length of array\nset len=0 \n\n:: To iterate the element of array\n:Loop \n\n:: It will check if the element is defined or not\nif defined array[%len%] ( \nset /a len+=1\nGOTO :Loop \n)\necho The length of the array is %len%\npause"
},
{
"code": null,
"e": 26692,
"s": 26632,
"text": "Save the above file with “.bat” extension and run the file."
},
{
"code": null,
"e": 26702,
"s": 26692,
"text": "Output : "
},
{
"code": null,
"e": 26731,
"s": 26702,
"text": "The length of the array is 4"
},
{
"code": null,
"e": 26782,
"s": 26731,
"text": "First, we create an array to calculate the length."
},
{
"code": null,
"e": 26891,
"s": 26782,
"text": "After this, we have to initialize a variable to calculate the length of the array. Above we initialize len=0"
},
{
"code": null,
"e": 26978,
"s": 26891,
"text": "Now we have to iterate the elements of the array to calculate the length of the array."
},
{
"code": null,
"e": 27088,
"s": 26978,
"text": "To check the element is exists or not in the array we have to put an if statement as shown in the above code."
},
{
"code": null,
"e": 27152,
"s": 27088,
"text": "In case if statement is true then there is an increment in len."
},
{
"code": null,
"e": 27250,
"s": 27152,
"text": "In case if statement is false then it will exit from the loop and return the length of the array."
},
{
"code": null,
"e": 27263,
"s": 27250,
"text": "Batch-script"
},
{
"code": null,
"e": 27270,
"s": 27263,
"text": "Picked"
},
{
"code": null,
"e": 27281,
"s": 27270,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27379,
"s": 27281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27414,
"s": 27379,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27448,
"s": 27414,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27474,
"s": 27448,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27503,
"s": 27474,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27540,
"s": 27503,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27577,
"s": 27540,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27619,
"s": 27577,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27645,
"s": 27619,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27681,
"s": 27645,
"text": "uniq Command in LINUX with examples"
}
] |
How to apply inline CSS ?
|
17 Mar, 2021
Inline CSS contains the CSS property in the body section attached with the element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute. It is used to apply a unique style to a single HTML element.
Syntax:
<tag style = " "></tag>
Example 1:
HTML
<!DOCTYPE html><html> <body> <p style="color: #009900; font-size: 50px; font-style: italic; text-align: center;"> GeeksForGeeks </p> </body></html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <body> <h2 style="color: green; background: yellow"> Geeks For Geeks </h2> <p style="color: black"> Happy Preparation!!. </p> </body></html>
Output:
CSS-Basics
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 298,
"s": 52,
"text": "Inline CSS contains the CSS property in the body section attached with the element is known as inline CSS. This kind of style is specified within an HTML tag using the style attribute. It is used to apply a unique style to a single HTML element."
},
{
"code": null,
"e": 306,
"s": 298,
"text": "Syntax:"
},
{
"code": null,
"e": 330,
"s": 306,
"text": "<tag style = \" \"></tag>"
},
{
"code": null,
"e": 341,
"s": 330,
"text": "Example 1:"
},
{
"code": null,
"e": 346,
"s": 341,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <p style=\"color: #009900; font-size: 50px; font-style: italic; text-align: center;\"> GeeksForGeeks </p> </body></html>",
"e": 546,
"s": 346,
"text": null
},
{
"code": null,
"e": 554,
"s": 546,
"text": "Output:"
},
{
"code": null,
"e": 565,
"s": 554,
"text": "Example 2:"
},
{
"code": null,
"e": 570,
"s": 565,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2 style=\"color: green; background: yellow\"> Geeks For Geeks </h2> <p style=\"color: black\"> Happy Preparation!!. </p> </body></html>",
"e": 757,
"s": 570,
"text": null
},
{
"code": null,
"e": 765,
"s": 757,
"text": "Output:"
},
{
"code": null,
"e": 776,
"s": 765,
"text": "CSS-Basics"
},
{
"code": null,
"e": 790,
"s": 776,
"text": "CSS-Questions"
},
{
"code": null,
"e": 797,
"s": 790,
"text": "Picked"
},
{
"code": null,
"e": 801,
"s": 797,
"text": "CSS"
},
{
"code": null,
"e": 818,
"s": 801,
"text": "Web Technologies"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.