title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Finding Astronauts from different countries - GeeksforGeeks
|
23 Sep, 2021
Given a positive integer N denoting the number of astronauts(labelled from 0 from (N β 1))and a matrix mat[][] containing the pairs of astronauts that are from the same country, the task is to count the number of ways to choose two astronauts from different countries.
Examples:
Input: N = 6, mat[][] = {{0, 1}, {0, 2}, {2, 5}}Output: 9Explanation:Astronauts with ID {0, 1, 2, 5} belong to first country, astronaut with ID {3} belongs to second country and astronaut with ID {4} belongs to third country. The number of ways to choose two astronauts from different countries is:
Choose 1 astronaut from country 1 and 1 astronaut from country 2, then the total number of ways is 4*1 = 4.Choose 1 astronaut from country 1 and 1 astronaut from country 3, then the total number of ways is 4*1 = 4.Choose 1 astronaut from country 2 and 1 astronaut from country 3, then the total number of ways is 1*1 = 1.
Choose 1 astronaut from country 1 and 1 astronaut from country 2, then the total number of ways is 4*1 = 4.
Choose 1 astronaut from country 1 and 1 astronaut from country 3, then the total number of ways is 4*1 = 4.
Choose 1 astronaut from country 2 and 1 astronaut from country 3, then the total number of ways is 1*1 = 1.
Therefore, the total number of ways is 4 + 4 + 1 = 9.
Input: N = 5, mat[][] = {{0, 1}, {2, 3}, {0, 4}}Output: 6
Approach: The given problem can be solved by modeling this problem as a graph in which astronauts represent the vertices of the graph and the given pairs represent the edges in the graph. After constructing the graph, the idea is to calculate the number of ways to select 2 astronauts from different countries. Follow the steps to solve the problem:
Create a list of lists, adj[][] to store the adjacency list of the graph.
Traverse the given array arr[] using the variable i and append arr[i][1] to adj[arr[i][0]] and also append arr[i][0] to adj[arr[i][1]] for the undirected edge.
Now find the size of each connected component of the graph by performing the Depth First Search, using the approach discussed in this article, and store all the sizes of connected components be stored in an array say v[].
Initialize an integer variable, say ans as the total number of ways to choose 2 astronauts from N astronauts i.e., N*(N β 1)/2.
Traverse the array v[] and subtract v[i]*(v[i] β 1)/2 from the variable ans to exclude all possible pairs among each connected components.
After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to perform the DFS Traversal// to find the count of connected// componentsvoid dfs(int v, vector<vector<int> >& adj, vector<bool>& visited, int& num){ // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (int i = 0; i < adj[v].size(); i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj[v][i]]) { dfs(adj[v][i], adj, visited, num); } }} // Function to find the number of ways// to choose two astronauts from the// different countriesvoid numberOfPairs( int N, vector<vector<int> > arr){ // Stores the Adjacency list vector<vector<int> > adj(N); // Constructing the graph for (vector<int>& i : arr) { adj[i[0]].push_back(i[1]); adj[i[1]].push_back(i[0]); } // Stores the visited vertices vector<bool> visited(N); // Stores the size of every // connected components vector<int> v; int num = 0; for (int i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i, adj, visited, num); // Store size of every // connected component v.push_back(num); num = 0; } } // Stores the total number of // ways to count the pairs int ans = N * (N - 1) / 2; // Traverse the array for (int i : v) { ans -= (i * (i - 1) / 2); } // Print the value of ans cout << ans;} // Driver Codeint main(){ int N = 6; vector<vector<int> > arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } }; numberOfPairs(N, arr); return 0;}
// Java program for the above approachimport java.util.*;public class GFG{ // Function to perform the DFS Traversal // to find the count of connected // components static Vector<Vector<Integer>> adj; static boolean[] visited; static int num; // Function to perform the DFS Traversal // to find the count of connected // components static void dfs(int v) { // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (int i = 0; i < adj.get(v).size(); i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj.get(v).get(i)]) { dfs(adj.get(v).get(i)); } } } // Function to find the number of ways // to choose two astronauts from the // different countries static void numberOfPairs(int N, int[][] arr) { // Stores the Adjacency list adj = new Vector<Vector<Integer>>(); for(int i = 0; i < N; i++) { adj.add(new Vector<Integer>()); } // Constructing the graph for (int i = 0; i < 2; i++) { adj.get(arr[i][0]).add(arr[i][1]); adj.get(arr[i][1]).add(arr[i][0]); } // Stores the visited vertices visited = new boolean[N]; Arrays.fill(visited, false); // Stores the size of every // connected components Vector<Integer> v = new Vector<Integer>(); num = 0; for (int i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i); // Store size of every // connected component v.add(num); num = 0; } } // Stores the total number of // ways to count the pairs int ans = N * (N - 1) / 2 + 1; // Traverse the array for (int i = 0; i < v.size(); i++) { ans -= (v.get(i) * (v.get(i) - 1) / 2) +1; } // Print the value of ans System.out.print(ans); } public static void main(String[] args) { int N = 6; int[][] arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } }; numberOfPairs(N, arr); }} // This code is contributed by suresh07
# Python3 program for the above approach # Function to perform the DFS Traversal# to find the count of connected# componentsadj = []visited = []num = 0 def dfs(v): global adj, visited, num # Marking vertex visited visited[v] = True num+=1 # DFS call to neighbour vertices for i in range(len(adj[v])): # If the current node is not # visited, then recursively # call DFS if (not visited[adj[v][i]]): dfs(adj[v][i]) # Function to find the number of ways# to choose two astronauts from the# different countriesdef numberOfPairs(N, arr): global adj, visited, num # Stores the Adjacency list adj = [] for i in range(N): adj.append([]) # Constructing the graph for i in range(len(arr)): adj[arr[i][0]].append(arr[i][1]) adj[arr[i][1]].append(arr[i][0]) # Stores the visited vertices visited = [False]*(N) # Stores the size of every # connected components v = [] num = 0 for i in range(N): if (not visited[i]): # DFS call to the graph dfs(i) # Store size of every # connected component v.append(num) num = 0 # Stores the total number of # ways to count the pairs ans = N * int((N - 1) / 2) # Traverse the array for i in range(len(v)): ans -= (v[i] * int((v[i] - 1) / 2)) ans+=1 # Print the value of ans print(ans) N = 6arr = [ [ 0, 1 ], [ 0, 2 ], [ 2, 5 ] ]numberOfPairs(N, arr) # This code is contributed by mukesh07.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to perform the DFS Traversal // to find the count of connected // components static List<List<int>> adj; static bool[] visited; static int num; // Function to perform the DFS Traversal // to find the count of connected // components static void dfs(int v) { // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (int i = 0; i < adj[v].Count; i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj[v][i]]) { dfs(adj[v][i]); } } } // Function to find the number of ways // to choose two astronauts from the // different countries static void numberOfPairs(int N, int[,] arr) { // Stores the Adjacency list adj = new List<List<int>>(); for(int i = 0; i < N; i++) { adj.Add(new List<int>()); } // Constructing the graph for (int i = 0; i < 2; i++) { adj[arr[i,0]].Add(arr[i,1]); adj[arr[i,1]].Add(arr[i,0]); } // Stores the visited vertices visited = new bool[N]; Array.Fill(visited, false); // Stores the size of every // connected components List<int> v = new List<int>(); num = 0; for (int i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i); // Store size of every // connected component v.Add(num); num = 0; } } // Stores the total number of // ways to count the pairs int ans = N * (N - 1) / 2 + 1; // Traverse the array for (int i = 0; i < v.Count; i++) { ans -= (v[i] * (v[i] - 1) / 2) +1; } // Print the value of ans Console.Write(ans); } static void Main() { int N = 6; int[,] arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } }; numberOfPairs(N, arr); }} // This code is contributed by divyesh072019.
<script> // Javascript program for the above approach // Function to perform the DFS Traversal // to find the count of connected // components let adj; let visited; let num; function dfs(v) { // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (let i = 0; i < adj[v].length; i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj[v][i]]) { dfs(adj[v][i]); } } } // Function to find the number of ways // to choose two astronauts from the // different countries function numberOfPairs(N, arr) { // Stores the Adjacency list adj = []; for(let i = 0; i < N; i++) { adj.push([]); } // Constructing the graph for (let i = 0; i < arr.length; i++) { adj[arr[i][0]].push(arr[i][1]); adj[arr[i][1]].push(arr[i][0]); } // Stores the visited vertices visited = new Array(N); visited.fill(false); // Stores the size of every // connected components let v = []; num = 0; for (let i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i); // Store size of every // connected component v.push(num); num = 0; } } // Stores the total number of // ways to count the pairs let ans = N * (N - 1) / 2; // Traverse the array for (let i = 0; i < v.length; i++) { ans -= (v[i] * (v[i] - 1) / 2); } // Print the value of ans document.write(ans); } let N = 6; let arr = [ [ 0, 1 ], [ 0, 2 ], [ 2, 5 ] ]; numberOfPairs(N, arr); // This code is contributed by rameshtravel07.</script>
9
Time Complexity: O(N + E), where N is the number of vertices and E is the number of edges.Auxiliary Space: O(N + E)
rameshtravel07
mukesh07
divyesh072019
suresh07
DFS
Graph Traversals
graph-connectivity
Graph
Mathematical
Mathematical
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
Longest Path in a Directed Acyclic Graph
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24699,
"s": 24671,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 24968,
"s": 24699,
"text": "Given a positive integer N denoting the number of astronauts(labelled from 0 from (N β 1))and a matrix mat[][] containing the pairs of astronauts that are from the same country, the task is to count the number of ways to choose two astronauts from different countries."
},
{
"code": null,
"e": 24978,
"s": 24968,
"text": "Examples:"
},
{
"code": null,
"e": 25277,
"s": 24978,
"text": "Input: N = 6, mat[][] = {{0, 1}, {0, 2}, {2, 5}}Output: 9Explanation:Astronauts with ID {0, 1, 2, 5} belong to first country, astronaut with ID {3} belongs to second country and astronaut with ID {4} belongs to third country. The number of ways to choose two astronauts from different countries is:"
},
{
"code": null,
"e": 25599,
"s": 25277,
"text": "Choose 1 astronaut from country 1 and 1 astronaut from country 2, then the total number of ways is 4*1 = 4.Choose 1 astronaut from country 1 and 1 astronaut from country 3, then the total number of ways is 4*1 = 4.Choose 1 astronaut from country 2 and 1 astronaut from country 3, then the total number of ways is 1*1 = 1."
},
{
"code": null,
"e": 25707,
"s": 25599,
"text": "Choose 1 astronaut from country 1 and 1 astronaut from country 2, then the total number of ways is 4*1 = 4."
},
{
"code": null,
"e": 25815,
"s": 25707,
"text": "Choose 1 astronaut from country 1 and 1 astronaut from country 3, then the total number of ways is 4*1 = 4."
},
{
"code": null,
"e": 25923,
"s": 25815,
"text": "Choose 1 astronaut from country 2 and 1 astronaut from country 3, then the total number of ways is 1*1 = 1."
},
{
"code": null,
"e": 25978,
"s": 25923,
"text": "Therefore, the total number of ways is 4 + 4 + 1 = 9. "
},
{
"code": null,
"e": 26036,
"s": 25978,
"text": "Input: N = 5, mat[][] = {{0, 1}, {2, 3}, {0, 4}}Output: 6"
},
{
"code": null,
"e": 26386,
"s": 26036,
"text": "Approach: The given problem can be solved by modeling this problem as a graph in which astronauts represent the vertices of the graph and the given pairs represent the edges in the graph. After constructing the graph, the idea is to calculate the number of ways to select 2 astronauts from different countries. Follow the steps to solve the problem:"
},
{
"code": null,
"e": 26460,
"s": 26386,
"text": "Create a list of lists, adj[][] to store the adjacency list of the graph."
},
{
"code": null,
"e": 26620,
"s": 26460,
"text": "Traverse the given array arr[] using the variable i and append arr[i][1] to adj[arr[i][0]] and also append arr[i][0] to adj[arr[i][1]] for the undirected edge."
},
{
"code": null,
"e": 26842,
"s": 26620,
"text": "Now find the size of each connected component of the graph by performing the Depth First Search, using the approach discussed in this article, and store all the sizes of connected components be stored in an array say v[]."
},
{
"code": null,
"e": 26970,
"s": 26842,
"text": "Initialize an integer variable, say ans as the total number of ways to choose 2 astronauts from N astronauts i.e., N*(N β 1)/2."
},
{
"code": null,
"e": 27109,
"s": 26970,
"text": "Traverse the array v[] and subtract v[i]*(v[i] β 1)/2 from the variable ans to exclude all possible pairs among each connected components."
},
{
"code": null,
"e": 27181,
"s": 27109,
"text": "After completing the above steps, print the value of ans as the result."
},
{
"code": null,
"e": 27232,
"s": 27181,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27236,
"s": 27232,
"text": "C++"
},
{
"code": null,
"e": 27241,
"s": 27236,
"text": "Java"
},
{
"code": null,
"e": 27249,
"s": 27241,
"text": "Python3"
},
{
"code": null,
"e": 27252,
"s": 27249,
"text": "C#"
},
{
"code": null,
"e": 27263,
"s": 27252,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to perform the DFS Traversal// to find the count of connected// componentsvoid dfs(int v, vector<vector<int> >& adj, vector<bool>& visited, int& num){ // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (int i = 0; i < adj[v].size(); i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj[v][i]]) { dfs(adj[v][i], adj, visited, num); } }} // Function to find the number of ways// to choose two astronauts from the// different countriesvoid numberOfPairs( int N, vector<vector<int> > arr){ // Stores the Adjacency list vector<vector<int> > adj(N); // Constructing the graph for (vector<int>& i : arr) { adj[i[0]].push_back(i[1]); adj[i[1]].push_back(i[0]); } // Stores the visited vertices vector<bool> visited(N); // Stores the size of every // connected components vector<int> v; int num = 0; for (int i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i, adj, visited, num); // Store size of every // connected component v.push_back(num); num = 0; } } // Stores the total number of // ways to count the pairs int ans = N * (N - 1) / 2; // Traverse the array for (int i : v) { ans -= (i * (i - 1) / 2); } // Print the value of ans cout << ans;} // Driver Codeint main(){ int N = 6; vector<vector<int> > arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } }; numberOfPairs(N, arr); return 0;}",
"e": 29011,
"s": 27263,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to perform the DFS Traversal // to find the count of connected // components static Vector<Vector<Integer>> adj; static boolean[] visited; static int num; // Function to perform the DFS Traversal // to find the count of connected // components static void dfs(int v) { // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (int i = 0; i < adj.get(v).size(); i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj.get(v).get(i)]) { dfs(adj.get(v).get(i)); } } } // Function to find the number of ways // to choose two astronauts from the // different countries static void numberOfPairs(int N, int[][] arr) { // Stores the Adjacency list adj = new Vector<Vector<Integer>>(); for(int i = 0; i < N; i++) { adj.add(new Vector<Integer>()); } // Constructing the graph for (int i = 0; i < 2; i++) { adj.get(arr[i][0]).add(arr[i][1]); adj.get(arr[i][1]).add(arr[i][0]); } // Stores the visited vertices visited = new boolean[N]; Arrays.fill(visited, false); // Stores the size of every // connected components Vector<Integer> v = new Vector<Integer>(); num = 0; for (int i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i); // Store size of every // connected component v.add(num); num = 0; } } // Stores the total number of // ways to count the pairs int ans = N * (N - 1) / 2 + 1; // Traverse the array for (int i = 0; i < v.size(); i++) { ans -= (v.get(i) * (v.get(i) - 1) / 2) +1; } // Print the value of ans System.out.print(ans); } public static void main(String[] args) { int N = 6; int[][] arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } }; numberOfPairs(N, arr); }} // This code is contributed by suresh07",
"e": 31371,
"s": 29011,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to perform the DFS Traversal# to find the count of connected# componentsadj = []visited = []num = 0 def dfs(v): global adj, visited, num # Marking vertex visited visited[v] = True num+=1 # DFS call to neighbour vertices for i in range(len(adj[v])): # If the current node is not # visited, then recursively # call DFS if (not visited[adj[v][i]]): dfs(adj[v][i]) # Function to find the number of ways# to choose two astronauts from the# different countriesdef numberOfPairs(N, arr): global adj, visited, num # Stores the Adjacency list adj = [] for i in range(N): adj.append([]) # Constructing the graph for i in range(len(arr)): adj[arr[i][0]].append(arr[i][1]) adj[arr[i][1]].append(arr[i][0]) # Stores the visited vertices visited = [False]*(N) # Stores the size of every # connected components v = [] num = 0 for i in range(N): if (not visited[i]): # DFS call to the graph dfs(i) # Store size of every # connected component v.append(num) num = 0 # Stores the total number of # ways to count the pairs ans = N * int((N - 1) / 2) # Traverse the array for i in range(len(v)): ans -= (v[i] * int((v[i] - 1) / 2)) ans+=1 # Print the value of ans print(ans) N = 6arr = [ [ 0, 1 ], [ 0, 2 ], [ 2, 5 ] ]numberOfPairs(N, arr) # This code is contributed by mukesh07.",
"e": 32925,
"s": 31371,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to perform the DFS Traversal // to find the count of connected // components static List<List<int>> adj; static bool[] visited; static int num; // Function to perform the DFS Traversal // to find the count of connected // components static void dfs(int v) { // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (int i = 0; i < adj[v].Count; i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj[v][i]]) { dfs(adj[v][i]); } } } // Function to find the number of ways // to choose two astronauts from the // different countries static void numberOfPairs(int N, int[,] arr) { // Stores the Adjacency list adj = new List<List<int>>(); for(int i = 0; i < N; i++) { adj.Add(new List<int>()); } // Constructing the graph for (int i = 0; i < 2; i++) { adj[arr[i,0]].Add(arr[i,1]); adj[arr[i,1]].Add(arr[i,0]); } // Stores the visited vertices visited = new bool[N]; Array.Fill(visited, false); // Stores the size of every // connected components List<int> v = new List<int>(); num = 0; for (int i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i); // Store size of every // connected component v.Add(num); num = 0; } } // Stores the total number of // ways to count the pairs int ans = N * (N - 1) / 2 + 1; // Traverse the array for (int i = 0; i < v.Count; i++) { ans -= (v[i] * (v[i] - 1) / 2) +1; } // Print the value of ans Console.Write(ans); } static void Main() { int N = 6; int[,] arr = { { 0, 1 }, { 0, 2 }, { 2, 5 } }; numberOfPairs(N, arr); }} // This code is contributed by divyesh072019.",
"e": 35171,
"s": 32925,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to perform the DFS Traversal // to find the count of connected // components let adj; let visited; let num; function dfs(v) { // Marking vertex visited visited[v] = true; num++; // DFS call to neighbour vertices for (let i = 0; i < adj[v].length; i++) { // If the current node is not // visited, then recursively // call DFS if (!visited[adj[v][i]]) { dfs(adj[v][i]); } } } // Function to find the number of ways // to choose two astronauts from the // different countries function numberOfPairs(N, arr) { // Stores the Adjacency list adj = []; for(let i = 0; i < N; i++) { adj.push([]); } // Constructing the graph for (let i = 0; i < arr.length; i++) { adj[arr[i][0]].push(arr[i][1]); adj[arr[i][1]].push(arr[i][0]); } // Stores the visited vertices visited = new Array(N); visited.fill(false); // Stores the size of every // connected components let v = []; num = 0; for (let i = 0; i < N; i++) { if (!visited[i]) { // DFS call to the graph dfs(i); // Store size of every // connected component v.push(num); num = 0; } } // Stores the total number of // ways to count the pairs let ans = N * (N - 1) / 2; // Traverse the array for (let i = 0; i < v.length; i++) { ans -= (v[i] * (v[i] - 1) / 2); } // Print the value of ans document.write(ans); } let N = 6; let arr = [ [ 0, 1 ], [ 0, 2 ], [ 2, 5 ] ]; numberOfPairs(N, arr); // This code is contributed by rameshtravel07.</script>",
"e": 37155,
"s": 35171,
"text": null
},
{
"code": null,
"e": 37157,
"s": 37155,
"text": "9"
},
{
"code": null,
"e": 37275,
"s": 37159,
"text": "Time Complexity: O(N + E), where N is the number of vertices and E is the number of edges.Auxiliary Space: O(N + E)"
},
{
"code": null,
"e": 37290,
"s": 37275,
"text": "rameshtravel07"
},
{
"code": null,
"e": 37299,
"s": 37290,
"text": "mukesh07"
},
{
"code": null,
"e": 37313,
"s": 37299,
"text": "divyesh072019"
},
{
"code": null,
"e": 37322,
"s": 37313,
"text": "suresh07"
},
{
"code": null,
"e": 37326,
"s": 37322,
"text": "DFS"
},
{
"code": null,
"e": 37343,
"s": 37326,
"text": "Graph Traversals"
},
{
"code": null,
"e": 37362,
"s": 37343,
"text": "graph-connectivity"
},
{
"code": null,
"e": 37368,
"s": 37362,
"text": "Graph"
},
{
"code": null,
"e": 37381,
"s": 37368,
"text": "Mathematical"
},
{
"code": null,
"e": 37394,
"s": 37381,
"text": "Mathematical"
},
{
"code": null,
"e": 37398,
"s": 37394,
"text": "DFS"
},
{
"code": null,
"e": 37404,
"s": 37398,
"text": "Graph"
},
{
"code": null,
"e": 37502,
"s": 37404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37511,
"s": 37502,
"text": "Comments"
},
{
"code": null,
"e": 37524,
"s": 37511,
"text": "Old Comments"
},
{
"code": null,
"e": 37560,
"s": 37524,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 37601,
"s": 37560,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 37643,
"s": 37601,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 37708,
"s": 37643,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 37778,
"s": 37708,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 37808,
"s": 37778,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37868,
"s": 37808,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37883,
"s": 37868,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37926,
"s": 37883,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
CSV Files for Storage? Absolutely Not. Use Apache Avro Instead | by Dario RadecΜicΜ | Towards Data Science
|
Iβm not a fan of CSVs. Theyβre slow to query and take more disk space than required. Think expensive if youβre using the cloud to process large CSV files.
There are many alternatives β such as Excel, databases, and HDFs β but one in particular stands above the competition. That is, if you want to stick with row storage. Itβs called Apache Avro, and youβll learn all about it today.
If you want even more efficient columnar data format, look no further than Parquet:
towardsdatascience.com
Todayβs article answers the following questions:
What is Avro?
How to work with Avro in Python?
CSV or Avro β which is more efficient?
Avro is an open-source project which provides services of data serialization and exchange for Apache Hadoop. Donβt worry β you donβt need a big data environment β your laptop will do just fine. The guy behind Avro is Doug Cutting. Heβs also called the father of Hadoop.
If youβre unfamiliar with the term serialization, hereβs a crash course. It is a process of converting objects such as arrays and dictionaries into byte streams that can be efficiently stored and transferred elsewhere. You can then deserialize the byte stream to get the original objects back.
Avro is row-orientated, just like CSV. This makes it different from, letβs say, Parquet, but itβs still a highly efficient data format.
Hereβs another crash course β for those unfamiliar with the difference between row and column storage. Imagine you have the following data:
Hereβs how it would be organized in both row and column storage:
Column storage files are more lightweight, as adequate compression can be made for each column. Row storage doesnβt work in that way, since a single row can have multiple data types.
But hereβs the deal with Avro β it stores a JSON-like schema with the data, so the correct data types are known in advance. Thatβs where the compression happens.
In a nutshell, a single Avro file contains a JSON-like schema for data types and the data itself in binary format.
Avro has an API for every major programming language. But thereβs a catch β Pandas doesnβt support it by default. So no, you donβt have access to read_avro() and to_avro() functions. Youβll have to work around that.
Itβs not difficult β as youβll see next.
There are two installable libraries for working with Avro files:
avro β Documentation link
fastavro β Documentation link
The latter states the former library is dog slow, as it takes about 14 seconds to process 10K records. Youβll stick with fastavro for that reason.
Hereβs how to set up a new virtual environment and install necessary libraries (for Anaconda users):
conda create --name avro_env python=3.8conda activate avro_envconda install -c conda-forge pandas fastavro jupyter jupyterlab
Execute the following command to start JupyterLab session:
jupyter lab
Youβll use the NYSE stock prices dataset for the hands-on part. The dataset comes in CSV format β around 50 MB in size. Use the following snippet to import the required libraries and load the dataset:
import pandas as pdfrom fastavro import writer, reader, parse_schemadf = pd.read_csv('prices.csv')df.head()
Hereβs how the stock prices dataset looks like:
Converting a Pandas DataFrame to Avro file is a three-step process:
Define the schema β Youβll have to define a JSON-like schema to specify what fields are expected, alongside their respective data types. Write it as a Python dictionary and parse it using fastavro.parse_schema().Convert the DataFrame to a list of records β Use to_dict('records') function from Pandas to convert a DataFrame to a list of dictionary objects.Write to Avro file β Use fastavro.writer() to save the Avro file.
Define the schema β Youβll have to define a JSON-like schema to specify what fields are expected, alongside their respective data types. Write it as a Python dictionary and parse it using fastavro.parse_schema().
Convert the DataFrame to a list of records β Use to_dict('records') function from Pandas to convert a DataFrame to a list of dictionary objects.
Write to Avro file β Use fastavro.writer() to save the Avro file.
Hereβs how all three steps look like in code:
# 1. Define the schemaschema = { 'doc': 'NYSE prices', 'name': 'NYSE', 'namespace': 'stocks', 'type': 'record', 'fields': [ {'name': 'date', 'type': { 'type': 'string', 'logicalType': 'time-millis' }}, {'name': 'symbol', 'type': 'string'}, {'name': 'open', 'type': 'float'}, {'name': 'close', 'type': 'float'}, {'name': 'low', 'type': 'float'}, {'name': 'high', 'type': 'float'}, {'name': 'volume', 'type': 'float'} ]}parsed_schema = parse_schema(schema)# 2. Convert pd.DataFrame to records - list of dictionariesrecords = df.to_dict('records')# 3. Write to Avro filewith open('prices.avro', 'wb') as out: writer(out, parsed_schema, records)
Itβs not as straightforward as calling a single function, but it isnβt that difficult either. It could get tedious if your dataset has hundreds of columns, but thatβs the price you pay for efficiency.
Thereβs also room for automating name and type generation. Get creative. Iβm sure you can handle it.
Going from Avro to Pandas DataFrame is also a three-step process:
Create a list to store the records β This list will store dictionary objects you can later convert to Pandas DataFrame.Read and parse the Avro file β Use fastavro.reader() to read the file and then iterate over the records.Convert to Pandas DataFrame β Call pd.DataFrame() and pass in a list of parsed records.
Create a list to store the records β This list will store dictionary objects you can later convert to Pandas DataFrame.
Read and parse the Avro file β Use fastavro.reader() to read the file and then iterate over the records.
Convert to Pandas DataFrame β Call pd.DataFrame() and pass in a list of parsed records.
Hereβs the code:
# 1. List to store the recordsavro_records = []# 2. Read the Avro filewith open('prices.avro', 'rb') as fo: avro_reader = reader(fo) for record in avro_reader: avro_records.append(record) # 3. Convert to pd.DataFramedf_avro = pd.DataFrame(avro_records)# Print the first couple of rowsdf_avro.head()
And hereβs how the first couple of rows look like:
Both CSV and Avro versions of the dataset are identical β but which one should you use? Letβs answer that next.
Itβs a bit tricky to answer this question. Some people like CSVs because you can edit them directly. Avro doesnβt come with that option. All results youβll see are based on the original 50 MB CSV file. Your mileage may vary.
Hereβs a comparison between read times β pd.read_csv() and fastavro.reader(), alongside the appending to a list:
Pandas is about three times faster here, provided a 50 MB dataset.
Hereβs a comparison between write times β pd.to_csv() and fastavro.writer():
The tables have turned β Pandas takes longer to save the identical dataset.
The final comparison is probably the most interesting one β file size comparison. Avro should provide a significant reduction in file size due to serialization. Here are the results:
Not quite the reduction Parquet offered, but it still isnβt too bad.
Does it matter for 50 MB datasets? Probably not, but the savings scale on larger datasets, too. Thatβs especially important if youβre storing data on the cloud and paying for the overall size.
Thatβs something to think about.
Loved the article? Become a Medium member to continue learning without limits. Iβll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Follow me on Medium for more stories like this
Sign up for my newsletter
Connect on LinkedIn
|
[
{
"code": null,
"e": 327,
"s": 172,
"text": "Iβm not a fan of CSVs. Theyβre slow to query and take more disk space than required. Think expensive if youβre using the cloud to process large CSV files."
},
{
"code": null,
"e": 556,
"s": 327,
"text": "There are many alternatives β such as Excel, databases, and HDFs β but one in particular stands above the competition. That is, if you want to stick with row storage. Itβs called Apache Avro, and youβll learn all about it today."
},
{
"code": null,
"e": 640,
"s": 556,
"text": "If you want even more efficient columnar data format, look no further than Parquet:"
},
{
"code": null,
"e": 663,
"s": 640,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 712,
"s": 663,
"text": "Todayβs article answers the following questions:"
},
{
"code": null,
"e": 726,
"s": 712,
"text": "What is Avro?"
},
{
"code": null,
"e": 759,
"s": 726,
"text": "How to work with Avro in Python?"
},
{
"code": null,
"e": 798,
"s": 759,
"text": "CSV or Avro β which is more efficient?"
},
{
"code": null,
"e": 1068,
"s": 798,
"text": "Avro is an open-source project which provides services of data serialization and exchange for Apache Hadoop. Donβt worry β you donβt need a big data environment β your laptop will do just fine. The guy behind Avro is Doug Cutting. Heβs also called the father of Hadoop."
},
{
"code": null,
"e": 1362,
"s": 1068,
"text": "If youβre unfamiliar with the term serialization, hereβs a crash course. It is a process of converting objects such as arrays and dictionaries into byte streams that can be efficiently stored and transferred elsewhere. You can then deserialize the byte stream to get the original objects back."
},
{
"code": null,
"e": 1498,
"s": 1362,
"text": "Avro is row-orientated, just like CSV. This makes it different from, letβs say, Parquet, but itβs still a highly efficient data format."
},
{
"code": null,
"e": 1638,
"s": 1498,
"text": "Hereβs another crash course β for those unfamiliar with the difference between row and column storage. Imagine you have the following data:"
},
{
"code": null,
"e": 1703,
"s": 1638,
"text": "Hereβs how it would be organized in both row and column storage:"
},
{
"code": null,
"e": 1886,
"s": 1703,
"text": "Column storage files are more lightweight, as adequate compression can be made for each column. Row storage doesnβt work in that way, since a single row can have multiple data types."
},
{
"code": null,
"e": 2048,
"s": 1886,
"text": "But hereβs the deal with Avro β it stores a JSON-like schema with the data, so the correct data types are known in advance. Thatβs where the compression happens."
},
{
"code": null,
"e": 2163,
"s": 2048,
"text": "In a nutshell, a single Avro file contains a JSON-like schema for data types and the data itself in binary format."
},
{
"code": null,
"e": 2379,
"s": 2163,
"text": "Avro has an API for every major programming language. But thereβs a catch β Pandas doesnβt support it by default. So no, you donβt have access to read_avro() and to_avro() functions. Youβll have to work around that."
},
{
"code": null,
"e": 2420,
"s": 2379,
"text": "Itβs not difficult β as youβll see next."
},
{
"code": null,
"e": 2485,
"s": 2420,
"text": "There are two installable libraries for working with Avro files:"
},
{
"code": null,
"e": 2511,
"s": 2485,
"text": "avro β Documentation link"
},
{
"code": null,
"e": 2541,
"s": 2511,
"text": "fastavro β Documentation link"
},
{
"code": null,
"e": 2688,
"s": 2541,
"text": "The latter states the former library is dog slow, as it takes about 14 seconds to process 10K records. Youβll stick with fastavro for that reason."
},
{
"code": null,
"e": 2789,
"s": 2688,
"text": "Hereβs how to set up a new virtual environment and install necessary libraries (for Anaconda users):"
},
{
"code": null,
"e": 2915,
"s": 2789,
"text": "conda create --name avro_env python=3.8conda activate avro_envconda install -c conda-forge pandas fastavro jupyter jupyterlab"
},
{
"code": null,
"e": 2974,
"s": 2915,
"text": "Execute the following command to start JupyterLab session:"
},
{
"code": null,
"e": 2986,
"s": 2974,
"text": "jupyter lab"
},
{
"code": null,
"e": 3187,
"s": 2986,
"text": "Youβll use the NYSE stock prices dataset for the hands-on part. The dataset comes in CSV format β around 50 MB in size. Use the following snippet to import the required libraries and load the dataset:"
},
{
"code": null,
"e": 3295,
"s": 3187,
"text": "import pandas as pdfrom fastavro import writer, reader, parse_schemadf = pd.read_csv('prices.csv')df.head()"
},
{
"code": null,
"e": 3343,
"s": 3295,
"text": "Hereβs how the stock prices dataset looks like:"
},
{
"code": null,
"e": 3411,
"s": 3343,
"text": "Converting a Pandas DataFrame to Avro file is a three-step process:"
},
{
"code": null,
"e": 3833,
"s": 3411,
"text": "Define the schema β Youβll have to define a JSON-like schema to specify what fields are expected, alongside their respective data types. Write it as a Python dictionary and parse it using fastavro.parse_schema().Convert the DataFrame to a list of records β Use to_dict('records') function from Pandas to convert a DataFrame to a list of dictionary objects.Write to Avro file β Use fastavro.writer() to save the Avro file."
},
{
"code": null,
"e": 4046,
"s": 3833,
"text": "Define the schema β Youβll have to define a JSON-like schema to specify what fields are expected, alongside their respective data types. Write it as a Python dictionary and parse it using fastavro.parse_schema()."
},
{
"code": null,
"e": 4191,
"s": 4046,
"text": "Convert the DataFrame to a list of records β Use to_dict('records') function from Pandas to convert a DataFrame to a list of dictionary objects."
},
{
"code": null,
"e": 4257,
"s": 4191,
"text": "Write to Avro file β Use fastavro.writer() to save the Avro file."
},
{
"code": null,
"e": 4303,
"s": 4257,
"text": "Hereβs how all three steps look like in code:"
},
{
"code": null,
"e": 5033,
"s": 4303,
"text": "# 1. Define the schemaschema = { 'doc': 'NYSE prices', 'name': 'NYSE', 'namespace': 'stocks', 'type': 'record', 'fields': [ {'name': 'date', 'type': { 'type': 'string', 'logicalType': 'time-millis' }}, {'name': 'symbol', 'type': 'string'}, {'name': 'open', 'type': 'float'}, {'name': 'close', 'type': 'float'}, {'name': 'low', 'type': 'float'}, {'name': 'high', 'type': 'float'}, {'name': 'volume', 'type': 'float'} ]}parsed_schema = parse_schema(schema)# 2. Convert pd.DataFrame to records - list of dictionariesrecords = df.to_dict('records')# 3. Write to Avro filewith open('prices.avro', 'wb') as out: writer(out, parsed_schema, records)"
},
{
"code": null,
"e": 5234,
"s": 5033,
"text": "Itβs not as straightforward as calling a single function, but it isnβt that difficult either. It could get tedious if your dataset has hundreds of columns, but thatβs the price you pay for efficiency."
},
{
"code": null,
"e": 5335,
"s": 5234,
"text": "Thereβs also room for automating name and type generation. Get creative. Iβm sure you can handle it."
},
{
"code": null,
"e": 5401,
"s": 5335,
"text": "Going from Avro to Pandas DataFrame is also a three-step process:"
},
{
"code": null,
"e": 5712,
"s": 5401,
"text": "Create a list to store the records β This list will store dictionary objects you can later convert to Pandas DataFrame.Read and parse the Avro file β Use fastavro.reader() to read the file and then iterate over the records.Convert to Pandas DataFrame β Call pd.DataFrame() and pass in a list of parsed records."
},
{
"code": null,
"e": 5832,
"s": 5712,
"text": "Create a list to store the records β This list will store dictionary objects you can later convert to Pandas DataFrame."
},
{
"code": null,
"e": 5937,
"s": 5832,
"text": "Read and parse the Avro file β Use fastavro.reader() to read the file and then iterate over the records."
},
{
"code": null,
"e": 6025,
"s": 5937,
"text": "Convert to Pandas DataFrame β Call pd.DataFrame() and pass in a list of parsed records."
},
{
"code": null,
"e": 6042,
"s": 6025,
"text": "Hereβs the code:"
},
{
"code": null,
"e": 6361,
"s": 6042,
"text": "# 1. List to store the recordsavro_records = []# 2. Read the Avro filewith open('prices.avro', 'rb') as fo: avro_reader = reader(fo) for record in avro_reader: avro_records.append(record) # 3. Convert to pd.DataFramedf_avro = pd.DataFrame(avro_records)# Print the first couple of rowsdf_avro.head()"
},
{
"code": null,
"e": 6412,
"s": 6361,
"text": "And hereβs how the first couple of rows look like:"
},
{
"code": null,
"e": 6524,
"s": 6412,
"text": "Both CSV and Avro versions of the dataset are identical β but which one should you use? Letβs answer that next."
},
{
"code": null,
"e": 6749,
"s": 6524,
"text": "Itβs a bit tricky to answer this question. Some people like CSVs because you can edit them directly. Avro doesnβt come with that option. All results youβll see are based on the original 50 MB CSV file. Your mileage may vary."
},
{
"code": null,
"e": 6862,
"s": 6749,
"text": "Hereβs a comparison between read times β pd.read_csv() and fastavro.reader(), alongside the appending to a list:"
},
{
"code": null,
"e": 6929,
"s": 6862,
"text": "Pandas is about three times faster here, provided a 50 MB dataset."
},
{
"code": null,
"e": 7006,
"s": 6929,
"text": "Hereβs a comparison between write times β pd.to_csv() and fastavro.writer():"
},
{
"code": null,
"e": 7082,
"s": 7006,
"text": "The tables have turned β Pandas takes longer to save the identical dataset."
},
{
"code": null,
"e": 7265,
"s": 7082,
"text": "The final comparison is probably the most interesting one β file size comparison. Avro should provide a significant reduction in file size due to serialization. Here are the results:"
},
{
"code": null,
"e": 7334,
"s": 7265,
"text": "Not quite the reduction Parquet offered, but it still isnβt too bad."
},
{
"code": null,
"e": 7527,
"s": 7334,
"text": "Does it matter for 50 MB datasets? Probably not, but the savings scale on larger datasets, too. Thatβs especially important if youβre storing data on the cloud and paying for the overall size."
},
{
"code": null,
"e": 7560,
"s": 7527,
"text": "Thatβs something to think about."
},
{
"code": null,
"e": 7743,
"s": 7560,
"text": "Loved the article? Become a Medium member to continue learning without limits. Iβll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 7754,
"s": 7743,
"text": "medium.com"
},
{
"code": null,
"e": 7801,
"s": 7754,
"text": "Follow me on Medium for more stories like this"
},
{
"code": null,
"e": 7827,
"s": 7801,
"text": "Sign up for my newsletter"
}
] |
JSX Full Form - GeeksforGeeks
|
03 Jun, 2021
JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code). It is easy to create a template using JSX in React, but it is not a simple template language instead it comes with the full power of JavaScript.It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript. Instead of separating the markup and logic in separated files, React uses components for this purpose. We will learn about components in detail in further articles.
Syntax:
const element = <h1>Welcome to GeeksforGeeks.</h1>;
Characteristics of JSX:
JSX is not mandatory to use there are other ways to achieve the same thing but using JSX makes it easier to develop react application.
JSX allows writing expression in { }. The expression can be any JS expression or React variable.
To insert a large block of HTML we have to write it in a parenthesis i.e, ().
JSX produces react elements.
JSX follows XML rule.
After compilation, JSX expressions become regular JavaScript function calls.
JSX uses camelcase notation for naming HTML attributes. For example, tabindex in HTML is used as tabIndex in JSX.
Advantages of JSX:
JSX makes it easier to write or add HTML in React.
JSX can easily convert HTML tags to react elements.
It is faster than regular JavaScript.
JSX allows us to put HTML elements in DOM without using appendChild() or createElement() method.
As JSX is an expression, we can use it inside of if statements and for loops, assign it to variables, accept it as arguments, or return it from functions.
JSX prevents XSS (cross-site-scripting) attacks popularly known as injection attacks.
It is type-safe, and most of the errors can be found at compilation time.
Disadvantages of JSX:
JSX throws an error if the HTML is not correct.
In JSX HTML code must be wrapped in one top-level element otherwise it will give an error.
If HTML elements are not properly closed JSX will give an error.
Example :
index.js
import React from 'react';import ReactDOM from 'react-dom'; const name = "Learner"; const element = <h1>Hello,{ name }.Welcome to GeeksforGeeks.< /h1>; ReactDOM.render( element, document.getElementById("root"));
Output:
ReactJS-Basics
Full Form
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SSTF Full Form
JPEG Full Form
DML Full Form
BLOB Full Form
CIDR Full Form
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 ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
|
[
{
"code": null,
"e": 23067,
"s": 23039,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 23632,
"s": 23067,
"text": "JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code). It is easy to create a template using JSX in React, but it is not a simple template language instead it comes with the full power of JavaScript.It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript. Instead of separating the markup and logic in separated files, React uses components for this purpose. We will learn about components in detail in further articles. "
},
{
"code": null,
"e": 23640,
"s": 23632,
"text": "Syntax:"
},
{
"code": null,
"e": 23692,
"s": 23640,
"text": "const element = <h1>Welcome to GeeksforGeeks.</h1>;"
},
{
"code": null,
"e": 23716,
"s": 23692,
"text": "Characteristics of JSX:"
},
{
"code": null,
"e": 23851,
"s": 23716,
"text": "JSX is not mandatory to use there are other ways to achieve the same thing but using JSX makes it easier to develop react application."
},
{
"code": null,
"e": 23948,
"s": 23851,
"text": "JSX allows writing expression in { }. The expression can be any JS expression or React variable."
},
{
"code": null,
"e": 24026,
"s": 23948,
"text": "To insert a large block of HTML we have to write it in a parenthesis i.e, ()."
},
{
"code": null,
"e": 24055,
"s": 24026,
"text": "JSX produces react elements."
},
{
"code": null,
"e": 24077,
"s": 24055,
"text": "JSX follows XML rule."
},
{
"code": null,
"e": 24154,
"s": 24077,
"text": "After compilation, JSX expressions become regular JavaScript function calls."
},
{
"code": null,
"e": 24268,
"s": 24154,
"text": "JSX uses camelcase notation for naming HTML attributes. For example, tabindex in HTML is used as tabIndex in JSX."
},
{
"code": null,
"e": 24287,
"s": 24268,
"text": "Advantages of JSX:"
},
{
"code": null,
"e": 24338,
"s": 24287,
"text": "JSX makes it easier to write or add HTML in React."
},
{
"code": null,
"e": 24390,
"s": 24338,
"text": "JSX can easily convert HTML tags to react elements."
},
{
"code": null,
"e": 24428,
"s": 24390,
"text": "It is faster than regular JavaScript."
},
{
"code": null,
"e": 24525,
"s": 24428,
"text": "JSX allows us to put HTML elements in DOM without using appendChild() or createElement() method."
},
{
"code": null,
"e": 24680,
"s": 24525,
"text": "As JSX is an expression, we can use it inside of if statements and for loops, assign it to variables, accept it as arguments, or return it from functions."
},
{
"code": null,
"e": 24766,
"s": 24680,
"text": "JSX prevents XSS (cross-site-scripting) attacks popularly known as injection attacks."
},
{
"code": null,
"e": 24840,
"s": 24766,
"text": "It is type-safe, and most of the errors can be found at compilation time."
},
{
"code": null,
"e": 24864,
"s": 24842,
"text": "Disadvantages of JSX:"
},
{
"code": null,
"e": 24912,
"s": 24864,
"text": "JSX throws an error if the HTML is not correct."
},
{
"code": null,
"e": 25003,
"s": 24912,
"text": "In JSX HTML code must be wrapped in one top-level element otherwise it will give an error."
},
{
"code": null,
"e": 25068,
"s": 25003,
"text": "If HTML elements are not properly closed JSX will give an error."
},
{
"code": null,
"e": 25078,
"s": 25068,
"text": "Example :"
},
{
"code": null,
"e": 25087,
"s": 25078,
"text": "index.js"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom'; const name = \"Learner\"; const element = <h1>Hello,{ name }.Welcome to GeeksforGeeks.< /h1>; ReactDOM.render( element, document.getElementById(\"root\"));",
"e": 25308,
"s": 25087,
"text": null
},
{
"code": null,
"e": 25316,
"s": 25308,
"text": "Output:"
},
{
"code": null,
"e": 25331,
"s": 25316,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 25341,
"s": 25331,
"text": "Full Form"
},
{
"code": null,
"e": 25349,
"s": 25341,
"text": "ReactJS"
},
{
"code": null,
"e": 25366,
"s": 25349,
"text": "Web Technologies"
},
{
"code": null,
"e": 25464,
"s": 25366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25473,
"s": 25464,
"text": "Comments"
},
{
"code": null,
"e": 25486,
"s": 25473,
"text": "Old Comments"
},
{
"code": null,
"e": 25501,
"s": 25486,
"text": "SSTF Full Form"
},
{
"code": null,
"e": 25516,
"s": 25501,
"text": "JPEG Full Form"
},
{
"code": null,
"e": 25530,
"s": 25516,
"text": "DML Full Form"
},
{
"code": null,
"e": 25545,
"s": 25530,
"text": "BLOB Full Form"
},
{
"code": null,
"e": 25560,
"s": 25545,
"text": "CIDR Full Form"
},
{
"code": null,
"e": 25603,
"s": 25560,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25648,
"s": 25603,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 25713,
"s": 25648,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 25754,
"s": 25713,
"text": "Create a Responsive Navbar using ReactJS"
}
] |
IMS DB - DL/I Functions
|
DL/I function is the first parameter that is used in a DL/I call. This function tells which operation is going to be performed on the IMS database by the IMS DL/I call. The syntax of DL/I function is as follows β
01 DLI-FUNCTIONS.
05 DLI-GU PIC X(4) VALUE 'GU '.
05 DLI-GHU PIC X(4) VALUE 'GHU '.
05 DLI-GN PIC X(4) VALUE 'GN '.
05 DLI-GHN PIC X(4) VALUE 'GHN '.
05 DLI-GNP PIC X(4) VALUE 'GNP '.
05 DLI-GHNP PIC X(4) VALUE 'GHNP'.
05 DLI-ISRT PIC X(4) VALUE 'ISRT'.
05 DLI-DLET PIC X(4) VALUE 'DLET'.
05 DLI-REPL PIC X(4) VALUE 'REPL'.
05 DLI-CHKP PIC X(4) VALUE 'CHKP'.
05 DLI-XRST PIC X(4) VALUE 'XRST'.
05 DLI-PCB PIC X(4) VALUE 'PCB '.
This syntax represents the following key points β
For this parameter, we can provide any four-character name as a storage field to store the function code.
For this parameter, we can provide any four-character name as a storage field to store the function code.
DL/I function parameter is coded in the working storage section of the COBOL program.
DL/I function parameter is coded in the working storage section of the COBOL program.
For specifying the DL/I function, the programmer needs to code one of the 05 level data names such as DLI-GU in a DL/I call, since COBOL does not allow to code literals on a CALL statement.
For specifying the DL/I function, the programmer needs to code one of the 05 level data names such as DLI-GU in a DL/I call, since COBOL does not allow to code literals on a CALL statement.
DL/I functions are divided into three categories: Get, Update, and Other functions. Let us discuss each of them in detail.
DL/I functions are divided into three categories: Get, Update, and Other functions. Let us discuss each of them in detail.
Get functions are similar to the read operation supported by any programming language. Get function is used to fetch segments from an IMS DL/I database. The following Get functions are used in IMS DB β
Get Unique
Get Next
Get Next within Parent
Get Hold Unique
Get Hold Next
Get Hold Next within Parent
Let us consider the following IMS database structure to understand the DL/I function calls β
'GU' code is used for the Get Unique function. It works similar to the random read statement in COBOL. It is used to fetch a particular segment occurrence based on the field values. The field values can be provided using segment search arguments. The syntax of a GU call is as follows β
CALL 'CBLTDLI' USING DLI-GU
PCB Mask
Segment I/O Area
[Segment Search Arguments]
If you execute the above call statement by providing appropriate values for all parameters in the COBOL program, you can retrieve the segment in the segment I/O area from the database. In the above example, if you provide the field values of Library, Magazines, and Health, then you get the desired occurrence of the Health segment.
'GN' code is used for the Get Next function. It works similar to the read next statement in COBOL. It is used to fetch segment occurrences in a sequence. The predefined pattern for accessing data segment occurrences is down the hierarchy, then left to right. The syntax of a GN call is as follows β
CALL 'CBLTDLI' USING DLI-GN
PCB Mask
Segment I/O Area
[Segment Search Arguments]
If you execute the above call statement by providing appropriate values for all parameters in the COBOL program, you can retrieve the segment occurrence in the segment I/O area from the database in a sequential order. In the above example, it starts with accessing the Library segment, then Books segment, and so on. We perform the GN call again and again, until we reach the segment occurrence we want.
'GNP' code is used for Get Next within Parent. This function is used to retrieve segment occurrences in sequence subordinate to an established parent segment. The syntax of a GNP call is as follows β
CALL 'CBLTDLI' USING DLI-GNP
PCB Mask
Segment I/O Area
[Segment Search Arguments]
'GHU' code is used for Get Hold Unique. Hold function specifies that we are going to update the segment after retrieval. The Get Hold Unique function corresponds to the Get Unique call. Given below is the syntax of a GHU call β
CALL 'CBLTDLI' USING DLI-GHU
PCB Mask
Segment I/O Area
[Segment Search Arguments]
'GHN' code is used for Get Hold Next. Hold function specifies that we are going to update the segment after retrieval. The Get Hold Next function corresponds to the Get Next call. Given below is the syntax of a GHN call β
CALL 'CBLTDLI' USING DLI-GHN
PCB Mask
Segment I/O Area
[Segment Search Arguments]
'GHNP' code is used for Get Hold Next within Parent. Hold function specifies that we are going to update the segment after retrieval. The Get Hold Next within Parent function corresponds to the Get Next within Parent call. Given below is the syntax of a GHNP call β
CALL 'CBLTDLI' USING DLI-GHNP
PCB Mask
Segment I/O Area
[Segment Search Arguments]
Update functions are similar to re-write or insert operations in any other programming language. Update functions are used to update segments in an IMS DL/I database. Before using the update function, there must be a successful call with Hold clause for the segment occurrence. The following Update functions are used in IMS DB β
Insert
Delete
Replace
'ISRT' code is used for the Insert function. The ISRT function is used to add a new segment to the database. It is used to change an existing database or load a new database. Given below is the syntax of an ISRT call β
CALL 'CBLTDLI' USING DLI-ISRT
PCB Mask
Segment I/O Area
[Segment Search Arguments]
'DLET' code is used for the Delete function. It is used to remove a segment from an IMS DL/I database. Given below is the syntax of a DLET call β
CALL 'CBLTDLI' USING DLI-DLET
PCB Mask
Segment I/O Area
[Segment Search Arguments]
'REPL' code is used for Get Hold Next within Parent. The Replace function is used to replace a segment in the IMS DL/I database. Given below is the syntax of an REPL call β
CALL 'CBLTDLI' USING DLI-REPL
PCB Mask
Segment I/O Area
[Segment Search Arguments]
The following other functions are used in IMS DL/I calls β
Checkpoint
Restart
PCB
'CHKP' code is used for the Checkpoint function. It is used in the recovery features of IMS. Given below is the syntax of a CHKP call β
CALL 'CBLTDLI' USING DLI-CHKP
PCB Mask
Segment I/O Area
[Segment Search Arguments]
'XRST' code is used for the Restart function. It is used in the restart features of IMS. Given below is the syntax of an XRST call β
CALL 'CBLTDLI' USING DLI-XRST
PCB Mask
Segment I/O Area
[Segment Search Arguments]
PCB function is used in CICS programs in the IMS DL/I database. Given below is the syntax of a PCB call β
CALL 'CBLTDLI' USING DLI-PCB
PCB Mask
Segment I/O Area
[Segment Search Arguments]
You can find more details about these functions in the recovery chapter.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2159,
"s": 1946,
"text": "DL/I function is the first parameter that is used in a DL/I call. This function tells which operation is going to be performed on the IMS database by the IMS DL/I call. The syntax of DL/I function is as follows β"
},
{
"code": null,
"e": 2730,
"s": 2159,
"text": "01 DLI-FUNCTIONS.\n 05 DLI-GU PIC X(4) VALUE 'GU '.\n 05 DLI-GHU PIC X(4) VALUE 'GHU '.\n 05 DLI-GN PIC X(4) VALUE 'GN '.\n 05 DLI-GHN PIC X(4) VALUE 'GHN '.\n 05 DLI-GNP PIC X(4) VALUE 'GNP '.\n 05 DLI-GHNP PIC X(4) VALUE 'GHNP'.\n 05 DLI-ISRT PIC X(4) VALUE 'ISRT'.\n 05 DLI-DLET PIC X(4) VALUE 'DLET'.\n 05 DLI-REPL PIC X(4) VALUE 'REPL'.\n 05 DLI-CHKP PIC X(4) VALUE 'CHKP'.\n 05 DLI-XRST PIC X(4) VALUE 'XRST'.\n 05 DLI-PCB PIC X(4) VALUE 'PCB '.\n"
},
{
"code": null,
"e": 2780,
"s": 2730,
"text": "This syntax represents the following key points β"
},
{
"code": null,
"e": 2886,
"s": 2780,
"text": "For this parameter, we can provide any four-character name as a storage field to store the function code."
},
{
"code": null,
"e": 2992,
"s": 2886,
"text": "For this parameter, we can provide any four-character name as a storage field to store the function code."
},
{
"code": null,
"e": 3078,
"s": 2992,
"text": "DL/I function parameter is coded in the working storage section of the COBOL program."
},
{
"code": null,
"e": 3164,
"s": 3078,
"text": "DL/I function parameter is coded in the working storage section of the COBOL program."
},
{
"code": null,
"e": 3354,
"s": 3164,
"text": "For specifying the DL/I function, the programmer needs to code one of the 05 level data names such as DLI-GU in a DL/I call, since COBOL does not allow to code literals on a CALL statement."
},
{
"code": null,
"e": 3544,
"s": 3354,
"text": "For specifying the DL/I function, the programmer needs to code one of the 05 level data names such as DLI-GU in a DL/I call, since COBOL does not allow to code literals on a CALL statement."
},
{
"code": null,
"e": 3667,
"s": 3544,
"text": "DL/I functions are divided into three categories: Get, Update, and Other functions. Let us discuss each of them in detail."
},
{
"code": null,
"e": 3790,
"s": 3667,
"text": "DL/I functions are divided into three categories: Get, Update, and Other functions. Let us discuss each of them in detail."
},
{
"code": null,
"e": 3992,
"s": 3790,
"text": "Get functions are similar to the read operation supported by any programming language. Get function is used to fetch segments from an IMS DL/I database. The following Get functions are used in IMS DB β"
},
{
"code": null,
"e": 4003,
"s": 3992,
"text": "Get Unique"
},
{
"code": null,
"e": 4012,
"s": 4003,
"text": "Get Next"
},
{
"code": null,
"e": 4035,
"s": 4012,
"text": "Get Next within Parent"
},
{
"code": null,
"e": 4051,
"s": 4035,
"text": "Get Hold Unique"
},
{
"code": null,
"e": 4065,
"s": 4051,
"text": "Get Hold Next"
},
{
"code": null,
"e": 4093,
"s": 4065,
"text": "Get Hold Next within Parent"
},
{
"code": null,
"e": 4186,
"s": 4093,
"text": "Let us consider the following IMS database structure to understand the DL/I function calls β"
},
{
"code": null,
"e": 4473,
"s": 4186,
"text": "'GU' code is used for the Get Unique function. It works similar to the random read statement in COBOL. It is used to fetch a particular segment occurrence based on the field values. The field values can be provided using segment search arguments. The syntax of a GU call is as follows β"
},
{
"code": null,
"e": 4618,
"s": 4473,
"text": "CALL 'CBLTDLI' USING DLI-GU\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 4951,
"s": 4618,
"text": "If you execute the above call statement by providing appropriate values for all parameters in the COBOL program, you can retrieve the segment in the segment I/O area from the database. In the above example, if you provide the field values of Library, Magazines, and Health, then you get the desired occurrence of the Health segment."
},
{
"code": null,
"e": 5250,
"s": 4951,
"text": "'GN' code is used for the Get Next function. It works similar to the read next statement in COBOL. It is used to fetch segment occurrences in a sequence. The predefined pattern for accessing data segment occurrences is down the hierarchy, then left to right. The syntax of a GN call is as follows β"
},
{
"code": null,
"e": 5395,
"s": 5250,
"text": "CALL 'CBLTDLI' USING DLI-GN\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 5799,
"s": 5395,
"text": "If you execute the above call statement by providing appropriate values for all parameters in the COBOL program, you can retrieve the segment occurrence in the segment I/O area from the database in a sequential order. In the above example, it starts with accessing the Library segment, then Books segment, and so on. We perform the GN call again and again, until we reach the segment occurrence we want."
},
{
"code": null,
"e": 5999,
"s": 5799,
"text": "'GNP' code is used for Get Next within Parent. This function is used to retrieve segment occurrences in sequence subordinate to an established parent segment. The syntax of a GNP call is as follows β"
},
{
"code": null,
"e": 6145,
"s": 5999,
"text": "CALL 'CBLTDLI' USING DLI-GNP\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 6373,
"s": 6145,
"text": "'GHU' code is used for Get Hold Unique. Hold function specifies that we are going to update the segment after retrieval. The Get Hold Unique function corresponds to the Get Unique call. Given below is the syntax of a GHU call β"
},
{
"code": null,
"e": 6519,
"s": 6373,
"text": "CALL 'CBLTDLI' USING DLI-GHU\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 6741,
"s": 6519,
"text": "'GHN' code is used for Get Hold Next. Hold function specifies that we are going to update the segment after retrieval. The Get Hold Next function corresponds to the Get Next call. Given below is the syntax of a GHN call β"
},
{
"code": null,
"e": 6887,
"s": 6741,
"text": "CALL 'CBLTDLI' USING DLI-GHN\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 7153,
"s": 6887,
"text": "'GHNP' code is used for Get Hold Next within Parent. Hold function specifies that we are going to update the segment after retrieval. The Get Hold Next within Parent function corresponds to the Get Next within Parent call. Given below is the syntax of a GHNP call β"
},
{
"code": null,
"e": 7300,
"s": 7153,
"text": "CALL 'CBLTDLI' USING DLI-GHNP\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 7630,
"s": 7300,
"text": "Update functions are similar to re-write or insert operations in any other programming language. Update functions are used to update segments in an IMS DL/I database. Before using the update function, there must be a successful call with Hold clause for the segment occurrence. The following Update functions are used in IMS DB β"
},
{
"code": null,
"e": 7637,
"s": 7630,
"text": "Insert"
},
{
"code": null,
"e": 7644,
"s": 7637,
"text": "Delete"
},
{
"code": null,
"e": 7652,
"s": 7644,
"text": "Replace"
},
{
"code": null,
"e": 7871,
"s": 7652,
"text": "'ISRT' code is used for the Insert function. The ISRT function is used to add a new segment to the database. It is used to change an existing database or load a new database. Given below is the syntax of an ISRT call β"
},
{
"code": null,
"e": 8018,
"s": 7871,
"text": "CALL 'CBLTDLI' USING DLI-ISRT\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 8164,
"s": 8018,
"text": "'DLET' code is used for the Delete function. It is used to remove a segment from an IMS DL/I database. Given below is the syntax of a DLET call β"
},
{
"code": null,
"e": 8311,
"s": 8164,
"text": "CALL 'CBLTDLI' USING DLI-DLET\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 8484,
"s": 8311,
"text": "'REPL' code is used for Get Hold Next within Parent. The Replace function is used to replace a segment in the IMS DL/I database. Given below is the syntax of an REPL call β"
},
{
"code": null,
"e": 8631,
"s": 8484,
"text": "CALL 'CBLTDLI' USING DLI-REPL\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 8690,
"s": 8631,
"text": "The following other functions are used in IMS DL/I calls β"
},
{
"code": null,
"e": 8701,
"s": 8690,
"text": "Checkpoint"
},
{
"code": null,
"e": 8709,
"s": 8701,
"text": "Restart"
},
{
"code": null,
"e": 8713,
"s": 8709,
"text": "PCB"
},
{
"code": null,
"e": 8849,
"s": 8713,
"text": "'CHKP' code is used for the Checkpoint function. It is used in the recovery features of IMS. Given below is the syntax of a CHKP call β"
},
{
"code": null,
"e": 8996,
"s": 8849,
"text": "CALL 'CBLTDLI' USING DLI-CHKP\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 9129,
"s": 8996,
"text": "'XRST' code is used for the Restart function. It is used in the restart features of IMS. Given below is the syntax of an XRST call β"
},
{
"code": null,
"e": 9276,
"s": 9129,
"text": "CALL 'CBLTDLI' USING DLI-XRST\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 9382,
"s": 9276,
"text": "PCB function is used in CICS programs in the IMS DL/I database. Given below is the syntax of a PCB call β"
},
{
"code": null,
"e": 9528,
"s": 9382,
"text": "CALL 'CBLTDLI' USING DLI-PCB\n PCB Mask\n Segment I/O Area\n [Segment Search Arguments]\n"
},
{
"code": null,
"e": 9601,
"s": 9528,
"text": "You can find more details about these functions in the recovery chapter."
},
{
"code": null,
"e": 9608,
"s": 9601,
"text": " Print"
},
{
"code": null,
"e": 9619,
"s": 9608,
"text": " Add Notes"
}
] |
Python - Dictionary
|
In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this β {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.
A simple example is as follows β
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result β
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows β
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result β
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example β
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
When the above code is executed, it produces the following result β
dict['Age']: 8
dict['School']: DPS School
You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. A simple example is as mentioned below β
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Note βthat an exception is raised because after del dict dictionary does not exist any more β
Note βthat an exception is raised because after del dict dictionary does not exist any more β
This produces the following result β
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note β del() method is discussed in subsequent section.
Note β del() method is discussed in subsequent section.
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys β
More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.
More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result β
dict['Name']: Manni
Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.
An example is as follows β
#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result β
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2571,
"s": 2327,
"text": "In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this β {}."
},
{
"code": null,
"e": 2763,
"s": 2571,
"text": "Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples."
},
{
"code": null,
"e": 2875,
"s": 2763,
"text": "To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value."
},
{
"code": null,
"e": 2908,
"s": 2875,
"text": "A simple example is as follows β"
},
{
"code": null,
"e": 3051,
"s": 2908,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Name']: \", dict['Name']\nprint \"dict['Age']: \", dict['Age']"
},
{
"code": null,
"e": 3120,
"s": 3051,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 3157,
"s": 3120,
"text": "dict['Name']: Zara\ndict['Age']: 7\n"
},
{
"code": null,
"e": 3271,
"s": 3157,
"text": "If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows β"
},
{
"code": null,
"e": 3381,
"s": 3271,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\nprint \"dict['Alice']: \", dict['Alice']"
},
{
"code": null,
"e": 3450,
"s": 3381,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 3604,
"s": 3450,
"text": "dict['Alice']:\nTraceback (most recent call last):\n File \"test.py\", line 4, in <module>\n print \"dict['Alice']: \", dict['Alice'];\nKeyError: 'Alice'\n"
},
{
"code": null,
"e": 3773,
"s": 3604,
"text": "You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example β"
},
{
"code": null,
"e": 4009,
"s": 3773,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndict['Age'] = 8; # update existing entry\ndict['School'] = \"DPS School\"; # Add new entry\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']"
},
{
"code": null,
"e": 4077,
"s": 4009,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 4122,
"s": 4077,
"text": "dict['Age']: 8\ndict['School']: DPS School\n"
},
{
"code": null,
"e": 4282,
"s": 4122,
"text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation."
},
{
"code": null,
"e": 4394,
"s": 4282,
"text": "To explicitly remove an entire dictionary, just use the del statement. A simple example is as mentioned below β"
},
{
"code": null,
"e": 4683,
"s": 4394,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\n\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']"
},
{
"code": null,
"e": 4777,
"s": 4683,
"text": "Note βthat an exception is raised because after del dict dictionary does not exist any more β"
},
{
"code": null,
"e": 4871,
"s": 4777,
"text": "Note βthat an exception is raised because after del dict dictionary does not exist any more β"
},
{
"code": null,
"e": 4908,
"s": 4871,
"text": "This produces the following result β"
},
{
"code": null,
"e": 5082,
"s": 4908,
"text": "dict['Age']:\nTraceback (most recent call last):\n File \"test.py\", line 8, in <module>\n print \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable\n"
},
{
"code": null,
"e": 5138,
"s": 5082,
"text": "Note β del() method is discussed in subsequent section."
},
{
"code": null,
"e": 5194,
"s": 5138,
"text": "Note β del() method is discussed in subsequent section."
},
{
"code": null,
"e": 5364,
"s": 5194,
"text": "Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys."
},
{
"code": null,
"e": 5431,
"s": 5364,
"text": "There are two important points to remember about dictionary keys β"
},
{
"code": null,
"e": 5590,
"s": 5431,
"text": "More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins."
},
{
"code": null,
"e": 5749,
"s": 5590,
"text": "More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins."
},
{
"code": null,
"e": 5856,
"s": 5749,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}\nprint \"dict['Name']: \", dict['Name']"
},
{
"code": null,
"e": 5925,
"s": 5856,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 5947,
"s": 5925,
"text": "dict['Name']: Manni\n"
},
{
"code": null,
"e": 6084,
"s": 5947,
"text": "Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed."
},
{
"code": null,
"e": 6111,
"s": 6084,
"text": "An example is as follows β"
},
{
"code": null,
"e": 6203,
"s": 6111,
"text": "#!/usr/bin/python\n\ndict = {['Name']: 'Zara', 'Age': 7}\nprint \"dict['Name']: \", dict['Name']"
},
{
"code": null,
"e": 6271,
"s": 6203,
"text": "When the above code is executed, it produces the following result β"
},
{
"code": null,
"e": 6428,
"s": 6271,
"text": "Traceback (most recent call last):\n File \"test.py\", line 3, in <module>\n dict = {['Name']: 'Zara', 'Age': 7};\nTypeError: list objects are unhashable\n"
},
{
"code": null,
"e": 6465,
"s": 6428,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6481,
"s": 6465,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6514,
"s": 6481,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6533,
"s": 6514,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6568,
"s": 6533,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6590,
"s": 6568,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6624,
"s": 6590,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6652,
"s": 6624,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6687,
"s": 6652,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6701,
"s": 6687,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6734,
"s": 6701,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6751,
"s": 6734,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6758,
"s": 6751,
"text": " Print"
},
{
"code": null,
"e": 6769,
"s": 6758,
"text": " Add Notes"
}
] |
Measure Text Weight using TF-IDF in Python and scikit-learn | by Andrew Zhu | Towards Data Science
|
When dealing with text data, we want to measure the importance of a word to a document of a full text collection. One of the most intuitive solution would be counting the word appearance number, the higher the better. But simply counting the words # will lead to the result that favor to long document/article. After all, longer document contains more words.
We need another solution that can appropriately measure the importance of a word in the overall context. TF-IDF is one of the effective solutions. And also functioning as the backbone of modern search engines like Google.
The core idea of TF-IDF is, the solution not only measure the word frequency and also how importance of the word in the overall context.
For example, words like βisβ, βtheβ, βandβ appear almost in every document, the TF-IDF will lower down weight of those common words and increase the weight for those really matters.
Imagine we have a huge text database in Python, which includes three documents:
text_db = ['problem of evil', 'evil queen', 'horizon problem']
We can use this formula to calculate a wordβs TF-IDF value in a certain document.
TF_w,d represent the Term Frequency of the word in a certain document:
while the log part:
Represent the Inverse Document Frequency. The inverse here indicates this part will inverse the word frequency value, so that give some low values to those frequent used words.
For example, you have total 100 documents, and 10 of these contains the keywords. Then the IDF part will be log(D_all/D_w) = log(100/10) = log(10) = 2.3 (e base). As the log curve shows, the lower the keywords shows in the overall context, the higher IDF value will be produced.
Say, we want to get the TF-IDF value for keyword evil in document No1(βproblem of evilβ).
It should be easy to see evil shows up 1 time, and there are 3 words in total; 3 documents in the database, and 2 of these include evil keyword. So,
Together, we get the result:
In Python
import mathtf_1_evil = 1/3D_all = 3D_evil = 2tf_idf_evil = tf_1_evil * math.log(D_all/D_evil)print(tf_idf_evil)
print the result:
0.135
Scikit-learn provide a convenient way to calculate TF-IDF matrix in a quick way.
import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizervec = TfidfVectorizer()text_db = ['problem of evil', 'evil queen', 'horizon problem']tf_idf = vec.fit_transform(text_db)print(pd.DataFrame(tf_idf.toarray(), columns=vec.get_feature_names()))
The result.
evil horizon of problem queen0 0.517856 0.000000 0.680919 0.517856 0.0000001 0.605349 0.000000 0.000000 0.000000 0.7959612 0.000000 0.795961 0.000000 0.605349 0.000000
Wait, you may ask, Andrew, are you kidding me? the evil TF-IDF value for document 1(index shows 0) is 0.517856. what is wrong here?
There are two differences in the implementation of TfidfVectorizer of scikit-learn, which make the result different from the above formula that exists in most textbooks, and your professor told you.
First, sklearn use a different version of IDF formula,add 1s to numerator and denominator,to avoid dividing by zero scenario. TF remains the same.
Second, sklearn smooth the TF-IDF result by Euclidean Norm in document level.
In the case of calculating evil value in the first document(βproblem of evilβ), the formula is:
Now, letβs reshape the Python code to reflect the above two changes:
import mathtf_1_problem = 1/3tf_1_of = 1/3tf_1_evil = 1/3D_all = 3d_problem = 2d_of = 1d_evil = 2tf_idf_problem= tf_1_problem * (math.log((D_all+1)/(d_problem+1))+1)tf_idf_of = tf_1_of * (math.log((D_all+1)/(d_of+1))+1)tf_idf_evil = tf_1_evil * (math.log((D_all+1)/(d_evil+1))+1)denominator = math.sqrt(tf_idf_problem**2 + tf_idf_of**2 + tf_idf_evil**2)result = tf_idf_evil/denominatorprint("evil result:",result)
The TF-IDF value for evil is exactly the same as the one produced by scikit-learn.
evil result: 0.517856
A statistical interpretation of term specificity and its application in retrieval by Karen SpaΜrck Jones,
Jones first brought out the idea of TF-IDF in 1972.
Python Data Science Handbook β Feature Engineering by Jake VanderPlas https://jakevdp.github.io/PythonDataScienceHandbook/05.04-feature-engineering.html
Jake touched TF-IDF briefly in Chapter Feature Engineering, He doesnβt drill down too much of the TF-IDF usage, but he provided the best Python code to calculate TF-IDF values using scikit-learn. The sample text database with 3 documents used in this article is from this book.
ζ°ε¦δΉηΎ by Wu Jun https://book.douban.com/subject/10750155/
This book is written in Chinese, Dr, Wu Jun, a former Google researcher, former VP of Tencent. This book makes a great introduction to TF-IDF algorithm.
βSklearnβs TF-IDFβ vs βStandard TF-IDFβ by Sivakar Sivarajah https://towardsdatascience.com/how-sklearns-tf-idf-is-different-from-the-standard-tf-idf-275fa582e73d
Thanks to Sivakar, this article shows the differences of the TF-IDF implementation in scikit-learn from traditional textbook.
Medium does not support LaTex or Math formula input. It is painful to put those math formula in one article, and looks awful even using copied images. Here I put the content together in pure HTML format.
http://zhusd.com/understand_tfidf_in_python
Feel free to comments and correct me if you see anything. Thanks for reading it.
|
[
{
"code": null,
"e": 531,
"s": 172,
"text": "When dealing with text data, we want to measure the importance of a word to a document of a full text collection. One of the most intuitive solution would be counting the word appearance number, the higher the better. But simply counting the words # will lead to the result that favor to long document/article. After all, longer document contains more words."
},
{
"code": null,
"e": 753,
"s": 531,
"text": "We need another solution that can appropriately measure the importance of a word in the overall context. TF-IDF is one of the effective solutions. And also functioning as the backbone of modern search engines like Google."
},
{
"code": null,
"e": 890,
"s": 753,
"text": "The core idea of TF-IDF is, the solution not only measure the word frequency and also how importance of the word in the overall context."
},
{
"code": null,
"e": 1072,
"s": 890,
"text": "For example, words like βisβ, βtheβ, βandβ appear almost in every document, the TF-IDF will lower down weight of those common words and increase the weight for those really matters."
},
{
"code": null,
"e": 1152,
"s": 1072,
"text": "Imagine we have a huge text database in Python, which includes three documents:"
},
{
"code": null,
"e": 1235,
"s": 1152,
"text": "text_db = ['problem of evil', 'evil queen', 'horizon problem']"
},
{
"code": null,
"e": 1317,
"s": 1235,
"text": "We can use this formula to calculate a wordβs TF-IDF value in a certain document."
},
{
"code": null,
"e": 1388,
"s": 1317,
"text": "TF_w,d represent the Term Frequency of the word in a certain document:"
},
{
"code": null,
"e": 1408,
"s": 1388,
"text": "while the log part:"
},
{
"code": null,
"e": 1585,
"s": 1408,
"text": "Represent the Inverse Document Frequency. The inverse here indicates this part will inverse the word frequency value, so that give some low values to those frequent used words."
},
{
"code": null,
"e": 1864,
"s": 1585,
"text": "For example, you have total 100 documents, and 10 of these contains the keywords. Then the IDF part will be log(D_all/D_w) = log(100/10) = log(10) = 2.3 (e base). As the log curve shows, the lower the keywords shows in the overall context, the higher IDF value will be produced."
},
{
"code": null,
"e": 1954,
"s": 1864,
"text": "Say, we want to get the TF-IDF value for keyword evil in document No1(βproblem of evilβ)."
},
{
"code": null,
"e": 2103,
"s": 1954,
"text": "It should be easy to see evil shows up 1 time, and there are 3 words in total; 3 documents in the database, and 2 of these include evil keyword. So,"
},
{
"code": null,
"e": 2132,
"s": 2103,
"text": "Together, we get the result:"
},
{
"code": null,
"e": 2142,
"s": 2132,
"text": "In Python"
},
{
"code": null,
"e": 2283,
"s": 2142,
"text": "import mathtf_1_evil = 1/3D_all = 3D_evil = 2tf_idf_evil = tf_1_evil * math.log(D_all/D_evil)print(tf_idf_evil)"
},
{
"code": null,
"e": 2301,
"s": 2283,
"text": "print the result:"
},
{
"code": null,
"e": 2307,
"s": 2301,
"text": "0.135"
},
{
"code": null,
"e": 2388,
"s": 2307,
"text": "Scikit-learn provide a convenient way to calculate TF-IDF matrix in a quick way."
},
{
"code": null,
"e": 2677,
"s": 2388,
"text": "import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizervec = TfidfVectorizer()text_db = ['problem of evil', 'evil queen', 'horizon problem']tf_idf = vec.fit_transform(text_db)print(pd.DataFrame(tf_idf.toarray(), columns=vec.get_feature_names()))"
},
{
"code": null,
"e": 2689,
"s": 2677,
"text": "The result."
},
{
"code": null,
"e": 2890,
"s": 2689,
"text": " evil horizon of problem queen0 0.517856 0.000000 0.680919 0.517856 0.0000001 0.605349 0.000000 0.000000 0.000000 0.7959612 0.000000 0.795961 0.000000 0.605349 0.000000"
},
{
"code": null,
"e": 3022,
"s": 2890,
"text": "Wait, you may ask, Andrew, are you kidding me? the evil TF-IDF value for document 1(index shows 0) is 0.517856. what is wrong here?"
},
{
"code": null,
"e": 3221,
"s": 3022,
"text": "There are two differences in the implementation of TfidfVectorizer of scikit-learn, which make the result different from the above formula that exists in most textbooks, and your professor told you."
},
{
"code": null,
"e": 3368,
"s": 3221,
"text": "First, sklearn use a different version of IDF formula,add 1s to numerator and denominator,to avoid dividing by zero scenario. TF remains the same."
},
{
"code": null,
"e": 3446,
"s": 3368,
"text": "Second, sklearn smooth the TF-IDF result by Euclidean Norm in document level."
},
{
"code": null,
"e": 3542,
"s": 3446,
"text": "In the case of calculating evil value in the first document(βproblem of evilβ), the formula is:"
},
{
"code": null,
"e": 3611,
"s": 3542,
"text": "Now, letβs reshape the Python code to reflect the above two changes:"
},
{
"code": null,
"e": 4120,
"s": 3611,
"text": "import mathtf_1_problem = 1/3tf_1_of = 1/3tf_1_evil = 1/3D_all = 3d_problem = 2d_of = 1d_evil = 2tf_idf_problem= tf_1_problem * (math.log((D_all+1)/(d_problem+1))+1)tf_idf_of = tf_1_of * (math.log((D_all+1)/(d_of+1))+1)tf_idf_evil = tf_1_evil * (math.log((D_all+1)/(d_evil+1))+1)denominator = math.sqrt(tf_idf_problem**2 + tf_idf_of**2 + tf_idf_evil**2)result = tf_idf_evil/denominatorprint(\"evil result:\",result)"
},
{
"code": null,
"e": 4203,
"s": 4120,
"text": "The TF-IDF value for evil is exactly the same as the one produced by scikit-learn."
},
{
"code": null,
"e": 4225,
"s": 4203,
"text": "evil result: 0.517856"
},
{
"code": null,
"e": 4331,
"s": 4225,
"text": "A statistical interpretation of term specificity and its application in retrieval by Karen SpaΜrck Jones,"
},
{
"code": null,
"e": 4383,
"s": 4331,
"text": "Jones first brought out the idea of TF-IDF in 1972."
},
{
"code": null,
"e": 4536,
"s": 4383,
"text": "Python Data Science Handbook β Feature Engineering by Jake VanderPlas https://jakevdp.github.io/PythonDataScienceHandbook/05.04-feature-engineering.html"
},
{
"code": null,
"e": 4814,
"s": 4536,
"text": "Jake touched TF-IDF briefly in Chapter Feature Engineering, He doesnβt drill down too much of the TF-IDF usage, but he provided the best Python code to calculate TF-IDF values using scikit-learn. The sample text database with 3 documents used in this article is from this book."
},
{
"code": null,
"e": 4871,
"s": 4814,
"text": "ζ°ε¦δΉηΎ by Wu Jun https://book.douban.com/subject/10750155/"
},
{
"code": null,
"e": 5024,
"s": 4871,
"text": "This book is written in Chinese, Dr, Wu Jun, a former Google researcher, former VP of Tencent. This book makes a great introduction to TF-IDF algorithm."
},
{
"code": null,
"e": 5187,
"s": 5024,
"text": "βSklearnβs TF-IDFβ vs βStandard TF-IDFβ by Sivakar Sivarajah https://towardsdatascience.com/how-sklearns-tf-idf-is-different-from-the-standard-tf-idf-275fa582e73d"
},
{
"code": null,
"e": 5313,
"s": 5187,
"text": "Thanks to Sivakar, this article shows the differences of the TF-IDF implementation in scikit-learn from traditional textbook."
},
{
"code": null,
"e": 5517,
"s": 5313,
"text": "Medium does not support LaTex or Math formula input. It is painful to put those math formula in one article, and looks awful even using copied images. Here I put the content together in pure HTML format."
},
{
"code": null,
"e": 5561,
"s": 5517,
"text": "http://zhusd.com/understand_tfidf_in_python"
}
] |
MYSQL - CREATE ROLE Statement
|
A role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. To create a role, you need to have CREATE ROLE or CREATE USER privilege.
Following is the syntax of the CREATE ROLE Statement β
CREATE ROLE [IF NOT EXISTS] desiredname
Where, desiredname is the name of the role you need to create.
Following query creates a role named TestRole_ReadOnly.
mysql> CREATE ROLE 'TestRole_ReadOnly';
Query OK, 0 rows affected (0.13 sec)
Now, letβs grant read only privilege to the created role using the GRANT statement as β
mysql> GRANT SELECT ON * . * TO 'TestRole_ReadOnly';
Query OK, 0 rows affected (0.14 sec)
Then, you can GRANT the created role to a user as follows β
mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.14 sec)
mysql> GRANT 'TestRole_ReadOnly' TO 'newuser'@'localhost';
Query OK, 0 rows affected (0.13 sec)
You can create a role by specifying the host β
mysql> CREATE ROLE samplerole@localhost;
Query OK, 0 rows affected (0.14 sec)
You can also create multiple roles at once as shown below β
mysql> CREATE ROLE 'MyAdmin', 'MyDeveloper';
Query OK, 0 rows affected (0.21 sec)
If you try to create a role with an existing name an error will be generated β
mysql> CREATE ROLE 'testrole@localhost';
Query OK, 0 rows affected (0.16 sec)
mysql> CREATE ROLE 'testrole@localhost';
ERROR 1396 (HY000): Operation CREATE ROLE failed for 'testrole@localhost'@'%'
If you use the IF NOT EXISTS clause along with the CREATE ROLE statement as shown below a new role will be created and if a role with the given name, already exists the query will be ignored.
mysql> CREATE ROLE IF NOT EXISTS 'testrole@localhost';
Query OK, 0 rows affected, 1 warning (0.12 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2531,
"s": 2333,
"text": "A role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. To create a role, you need to have CREATE ROLE or CREATE USER privilege."
},
{
"code": null,
"e": 2586,
"s": 2531,
"text": "Following is the syntax of the CREATE ROLE Statement β"
},
{
"code": null,
"e": 2627,
"s": 2586,
"text": "CREATE ROLE [IF NOT EXISTS] desiredname\n"
},
{
"code": null,
"e": 2690,
"s": 2627,
"text": "Where, desiredname is the name of the role you need to create."
},
{
"code": null,
"e": 2746,
"s": 2690,
"text": "Following query creates a role named TestRole_ReadOnly."
},
{
"code": null,
"e": 2823,
"s": 2746,
"text": "mysql> CREATE ROLE 'TestRole_ReadOnly';\nQuery OK, 0 rows affected (0.13 sec)"
},
{
"code": null,
"e": 2911,
"s": 2823,
"text": "Now, letβs grant read only privilege to the created role using the GRANT statement as β"
},
{
"code": null,
"e": 3001,
"s": 2911,
"text": "mysql> GRANT SELECT ON * . * TO 'TestRole_ReadOnly';\nQuery OK, 0 rows affected (0.14 sec)"
},
{
"code": null,
"e": 3061,
"s": 3001,
"text": "Then, you can GRANT the created role to a user as follows β"
},
{
"code": null,
"e": 3262,
"s": 3061,
"text": "mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';\nQuery OK, 0 rows affected (0.14 sec)\n\nmysql> GRANT 'TestRole_ReadOnly' TO 'newuser'@'localhost';\nQuery OK, 0 rows affected (0.13 sec)"
},
{
"code": null,
"e": 3309,
"s": 3262,
"text": "You can create a role by specifying the host β"
},
{
"code": null,
"e": 3387,
"s": 3309,
"text": "mysql> CREATE ROLE samplerole@localhost;\nQuery OK, 0 rows affected (0.14 sec)"
},
{
"code": null,
"e": 3447,
"s": 3387,
"text": "You can also create multiple roles at once as shown below β"
},
{
"code": null,
"e": 3529,
"s": 3447,
"text": "mysql> CREATE ROLE 'MyAdmin', 'MyDeveloper';\nQuery OK, 0 rows affected (0.21 sec)"
},
{
"code": null,
"e": 3608,
"s": 3529,
"text": "If you try to create a role with an existing name an error will be generated β"
},
{
"code": null,
"e": 3805,
"s": 3608,
"text": "mysql> CREATE ROLE 'testrole@localhost';\nQuery OK, 0 rows affected (0.16 sec)\nmysql> CREATE ROLE 'testrole@localhost';\nERROR 1396 (HY000): Operation CREATE ROLE failed for 'testrole@localhost'@'%'"
},
{
"code": null,
"e": 3997,
"s": 3805,
"text": "If you use the IF NOT EXISTS clause along with the CREATE ROLE statement as shown below a new role will be created and if a role with the given name, already exists the query will be ignored."
},
{
"code": null,
"e": 4100,
"s": 3997,
"text": "mysql> CREATE ROLE IF NOT EXISTS 'testrole@localhost';\nQuery OK, 0 rows affected, 1 warning (0.12 sec)"
},
{
"code": null,
"e": 4133,
"s": 4100,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4161,
"s": 4133,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4196,
"s": 4161,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4213,
"s": 4196,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4247,
"s": 4213,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4282,
"s": 4247,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 4316,
"s": 4282,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4344,
"s": 4316,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4377,
"s": 4344,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4397,
"s": 4377,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4430,
"s": 4397,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4448,
"s": 4430,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4455,
"s": 4448,
"text": " Print"
},
{
"code": null,
"e": 4466,
"s": 4455,
"text": " Add Notes"
}
] |
HTML | <th> align Attribute - GeeksforGeeks
|
31 Dec, 2021
The HTML <th> align Attribute is used to set the horizontal alignment of text content inside the table header cell.
Syntax:
<th align= "left | right | center | justify | char">
Attribute Values:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align.
justify: It stretches the text of paragraph to set the width of all lines equal.
char: It sets the text-align to a specific character.
Note: The
Example:
<!DOCTYPE html><html> <head> <title> HTML th align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th align Attribute</h2> <table width="300" border="1"> <tr> <th align="left">NAME</th> <th align="center">AGE</th> <th align="right">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <th> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
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": 24333,
"s": 24305,
"text": "\n31 Dec, 2021"
},
{
"code": null,
"e": 24449,
"s": 24333,
"text": "The HTML <th> align Attribute is used to set the horizontal alignment of text content inside the table header cell."
},
{
"code": null,
"e": 24457,
"s": 24449,
"text": "Syntax:"
},
{
"code": null,
"e": 24510,
"s": 24457,
"text": "<th align= \"left | right | center | justify | char\">"
},
{
"code": null,
"e": 24528,
"s": 24510,
"text": "Attribute Values:"
},
{
"code": null,
"e": 24563,
"s": 24528,
"text": "left: It sets the text left-align."
},
{
"code": null,
"e": 24600,
"s": 24563,
"text": "right: It sets the text right-align."
},
{
"code": null,
"e": 24639,
"s": 24600,
"text": "center: It sets the text center-align."
},
{
"code": null,
"e": 24720,
"s": 24639,
"text": "justify: It stretches the text of paragraph to set the width of all lines equal."
},
{
"code": null,
"e": 24774,
"s": 24720,
"text": "char: It sets the text-align to a specific character."
},
{
"code": null,
"e": 24784,
"s": 24774,
"text": "Note: The"
},
{
"code": null,
"e": 24793,
"s": 24784,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML th align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th align Attribute</h2> <table width=\"300\" border=\"1\"> <tr> <th align=\"left\">NAME</th> <th align=\"center\">AGE</th> <th align=\"right\">BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>",
"e": 25359,
"s": 24793,
"text": null
},
{
"code": null,
"e": 25367,
"s": 25359,
"text": "Output:"
},
{
"code": null,
"e": 25456,
"s": 25367,
"text": "Supported Browsers: The browser supported by HTML <th> align attribute are listed below:"
},
{
"code": null,
"e": 25470,
"s": 25456,
"text": "Google Chrome"
},
{
"code": null,
"e": 25488,
"s": 25470,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25496,
"s": 25488,
"text": "Firefox"
},
{
"code": null,
"e": 25503,
"s": 25496,
"text": "Safari"
},
{
"code": null,
"e": 25509,
"s": 25503,
"text": "Opera"
},
{
"code": null,
"e": 25646,
"s": 25509,
"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": 25666,
"s": 25646,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 25682,
"s": 25666,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 25687,
"s": 25682,
"text": "HTML"
},
{
"code": null,
"e": 25704,
"s": 25687,
"text": "Web Technologies"
},
{
"code": null,
"e": 25709,
"s": 25704,
"text": "HTML"
},
{
"code": null,
"e": 25807,
"s": 25709,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25816,
"s": 25807,
"text": "Comments"
},
{
"code": null,
"e": 25829,
"s": 25816,
"text": "Old Comments"
},
{
"code": null,
"e": 25877,
"s": 25829,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 25914,
"s": 25877,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 25964,
"s": 25914,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26014,
"s": 25964,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26038,
"s": 26014,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26094,
"s": 26038,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26127,
"s": 26094,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26170,
"s": 26127,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26231,
"s": 26170,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to conditionally add attributes to React components? - GeeksforGeeks
|
05 Jan, 2021
We can conditionally add attributes to React components with the following approaches:
Approach 1:
Evidently, with some attributes, React is smart enough to omit the attribute if the value you pass to it is not truthy. For example:
state= {
disabled: false,
required: true
}
return (
<input type="text" disabled={disabled} required={required} />
);
Above Syntax will result in the following output:
<input type="text" required>
Creating React Application:
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
Project Structure: It will look like the following.
Approach 2: We can use the below syntax:
state {
condition: true
}
return (
<Button {...(condition ? {className: 'btn btn-primary'} : {})} />
);
Depending on the value of condition either the {className: βbtn btn-primaryβ} or {} will be returned. The Spread Operator will then spread the returned object properties to the Button component. In the falsy case, because the returned object has no properties, nothing will be passed to the component.
Approach 1:
Javascript
import React, { Component } from "react";class App extends Component { state = { disabled: true, text: "Make it Unable" } updateState = () => { let text = !this.state.disabled ? "Make it Unable" : "Make it Disable"; this.setState({ disabled: !this.state.disabled, text: text }) } render() { return ( <div> <input type="text" disabled={this.state.disabled} /> <button onClick={this.updateState}> {this.state.text} </button> </div> ); }} export default App;
Output:
Approach 2:
Javascript
import React, { Component } from "react";class App extends Component { state = { condition: true } updateState = () => { this.setState({ condition: !this.state.condition }) } render() { return ( <div> <button {...(this.state.condition ? { className: 'btn btn-primary' } : {})} onClick={this.updateState}> click </button> </div> ); }} export default App;
Output:
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Lodash _.debounce() Method
Angular File Upload
How to remove duplicate elements from JavaScript Array ?
How to change selected value of a drop-down list using jQuery?
|
[
{
"code": null,
"e": 26653,
"s": 26625,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 26740,
"s": 26653,
"text": "We can conditionally add attributes to React components with the following approaches:"
},
{
"code": null,
"e": 26753,
"s": 26740,
"text": "Approach 1: "
},
{
"code": null,
"e": 26886,
"s": 26753,
"text": "Evidently, with some attributes, React is smart enough to omit the attribute if the value you pass to it is not truthy. For example:"
},
{
"code": null,
"e": 27012,
"s": 26886,
"text": "state= {\n disabled: false,\n required: true\n}\n\nreturn (\n <input type=\"text\" disabled={disabled} required={required} />\n);"
},
{
"code": null,
"e": 27062,
"s": 27012,
"text": "Above Syntax will result in the following output:"
},
{
"code": null,
"e": 27091,
"s": 27062,
"text": "<input type=\"text\" required>"
},
{
"code": null,
"e": 27119,
"s": 27091,
"text": "Creating React Application:"
},
{
"code": null,
"e": 27183,
"s": 27119,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27215,
"s": 27183,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27315,
"s": 27215,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27329,
"s": 27315,
"text": "cd foldername"
},
{
"code": null,
"e": 27381,
"s": 27329,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27422,
"s": 27381,
"text": "Approach 2: We can use the below syntax:"
},
{
"code": null,
"e": 27531,
"s": 27422,
"text": "state {\n condition: true\n}\n\nreturn (\n <Button {...(condition ? {className: 'btn btn-primary'} : {})} />\n);"
},
{
"code": null,
"e": 27833,
"s": 27531,
"text": "Depending on the value of condition either the {className: βbtn btn-primaryβ} or {} will be returned. The Spread Operator will then spread the returned object properties to the Button component. In the falsy case, because the returned object has no properties, nothing will be passed to the component."
},
{
"code": null,
"e": 27845,
"s": 27833,
"text": "Approach 1:"
},
{
"code": null,
"e": 27856,
"s": 27845,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";class App extends Component { state = { disabled: true, text: \"Make it Unable\" } updateState = () => { let text = !this.state.disabled ? \"Make it Unable\" : \"Make it Disable\"; this.setState({ disabled: !this.state.disabled, text: text }) } render() { return ( <div> <input type=\"text\" disabled={this.state.disabled} /> <button onClick={this.updateState}> {this.state.text} </button> </div> ); }} export default App;",
"e": 28394,
"s": 27856,
"text": null
},
{
"code": null,
"e": 28402,
"s": 28394,
"text": "Output:"
},
{
"code": null,
"e": 28414,
"s": 28402,
"text": "Approach 2:"
},
{
"code": null,
"e": 28425,
"s": 28414,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";class App extends Component { state = { condition: true } updateState = () => { this.setState({ condition: !this.state.condition }) } render() { return ( <div> <button {...(this.state.condition ? { className: 'btn btn-primary' } : {})} onClick={this.updateState}> click </button> </div> ); }} export default App;",
"e": 28861,
"s": 28425,
"text": null
},
{
"code": null,
"e": 28870,
"s": 28861,
"text": "Output: "
},
{
"code": null,
"e": 28877,
"s": 28870,
"text": "Picked"
},
{
"code": null,
"e": 28886,
"s": 28877,
"text": "react-js"
},
{
"code": null,
"e": 28897,
"s": 28886,
"text": "JavaScript"
},
{
"code": null,
"e": 28995,
"s": 28897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29035,
"s": 28995,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29096,
"s": 29035,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29137,
"s": 29096,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29159,
"s": 29137,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29213,
"s": 29159,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29261,
"s": 29213,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 29288,
"s": 29261,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 29308,
"s": 29288,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29365,
"s": 29308,
"text": "How to remove duplicate elements from JavaScript Array ?"
}
] |
Advanced Streamlit: Session State and Callbacks for Data Labelling Tool | by ChiaChong | Towards Data Science
|
It is very simple to create a web app using Streamlit nowadays, but there are limitations when building something complex. One of them is the lack of statefulness because variables in the code will get reinitialize every time we interact with a widget. The good news is Streamlit now has native support of session state and callbacks function in their 0.84 release. We can now store variables across reruns and define our custom event handler upon interaction with a widget.
Hacks of session state have existed since October of 2019 but the new st.session_state provides us with an elegant solution to access stateful variables. One of the use cases of session state in my data labelling tool is able to preserve the selected project. The app needs to know what are the available projects and what is the project working on. This can simply be done by:
import streamlit as st# set variables in session statest.session_state.projects = [ 'Boring Project', 'Interesting Project']st.session_state.current_project = st.radio( 'Select a project to work with:', st.session_state.projects,)
The next step is to fetch data of the selected project. Besides the selected project, the app also needs the row index of the data to fetch. For simplicity, we assume there is a function that fetches data from the database as follows:
def fetch_data(project_name: str, row_index: int): """ A simple example function to fetch data. """ dbs = { 'Boring Project': [...], 'Interesting Project': [...], } return dbs[project_name][row_index] # output can be any formif 'current_project' in st.session_state: row_index = st.session_state.get('row_index', 0) data = fetch_data(st.session_state.current_project, row_index)
Once a user clicks the next or previous data, the row_index variable in the session state can be set to another number and new data will be loaded automatically.
# examples to update row indexif st.button('Next', key='next_data'): st.session_state.row_index += 1if st.button('Previous', key='previous_data'): st.session_state.row_index -= 1
Callback is the function that gets called when the input widget is triggered. Streamlit widgets that support callback are st.button(), st.radio(), st.text_input(), etc. Let's look at an example of callback in a submit button to add a new project.
def submit_add_project(project_name: str): """ Callback function during adding a new project. """ # display a warning if the user entered an existing name if project_name in st.session_state.projects: st.warning(f'The name "{project_name}" is already exists.') else: st.session_state.projects.append(project_name)new_project = st.text_input('New project name:', key='input_new_project_name')st.button('Add project', key='button_add_project', on_click=submit_add_project, args=(new_project, ))
Note that the callback function requires project_name argument, hence we need to pass the argument using args. Besides adding a new project, we should also allow the user to delete a project by doing so:
def submit_delete_project(project_name: str): """ Callback function during deleting an existing project. """ st.session_state.projects.remove(project_name)to_delete = st.selectbox('Project to be deleted:', st.session_state.projects)st.button('Delete project', key='button_delete_project', on_click=submit_delete_project, args=(to_delete, ))
This article shows some examples of session state and callbacks which enable the app to preserve variables across rerun and interaction with widgets. I recommend you to have a try with them for in-depth understanding and check out the streamlit blog post. Lastly, You can find the repo for the data labelling tool in Github.
This is my first medium post and Iβm very grateful to have you as my readers. Hope that you enjoyed and learned something from this article. Thank you for your time. Stay safe.
|
[
{
"code": null,
"e": 647,
"s": 172,
"text": "It is very simple to create a web app using Streamlit nowadays, but there are limitations when building something complex. One of them is the lack of statefulness because variables in the code will get reinitialize every time we interact with a widget. The good news is Streamlit now has native support of session state and callbacks function in their 0.84 release. We can now store variables across reruns and define our custom event handler upon interaction with a widget."
},
{
"code": null,
"e": 1025,
"s": 647,
"text": "Hacks of session state have existed since October of 2019 but the new st.session_state provides us with an elegant solution to access stateful variables. One of the use cases of session state in my data labelling tool is able to preserve the selected project. The app needs to know what are the available projects and what is the project working on. This can simply be done by:"
},
{
"code": null,
"e": 1265,
"s": 1025,
"text": "import streamlit as st# set variables in session statest.session_state.projects = [ 'Boring Project', 'Interesting Project']st.session_state.current_project = st.radio( 'Select a project to work with:', st.session_state.projects,)"
},
{
"code": null,
"e": 1500,
"s": 1265,
"text": "The next step is to fetch data of the selected project. Besides the selected project, the app also needs the row index of the data to fetch. For simplicity, we assume there is a function that fetches data from the database as follows:"
},
{
"code": null,
"e": 1912,
"s": 1500,
"text": "def fetch_data(project_name: str, row_index: int): \"\"\" A simple example function to fetch data. \"\"\" dbs = { 'Boring Project': [...], 'Interesting Project': [...], } return dbs[project_name][row_index] # output can be any formif 'current_project' in st.session_state: row_index = st.session_state.get('row_index', 0) data = fetch_data(st.session_state.current_project, row_index)"
},
{
"code": null,
"e": 2074,
"s": 1912,
"text": "Once a user clicks the next or previous data, the row_index variable in the session state can be set to another number and new data will be loaded automatically."
},
{
"code": null,
"e": 2259,
"s": 2074,
"text": "# examples to update row indexif st.button('Next', key='next_data'): st.session_state.row_index += 1if st.button('Previous', key='previous_data'): st.session_state.row_index -= 1"
},
{
"code": null,
"e": 2506,
"s": 2259,
"text": "Callback is the function that gets called when the input widget is triggered. Streamlit widgets that support callback are st.button(), st.radio(), st.text_input(), etc. Let's look at an example of callback in a submit button to add a new project."
},
{
"code": null,
"e": 3061,
"s": 2506,
"text": "def submit_add_project(project_name: str): \"\"\" Callback function during adding a new project. \"\"\" # display a warning if the user entered an existing name if project_name in st.session_state.projects: st.warning(f'The name \"{project_name}\" is already exists.') else: st.session_state.projects.append(project_name)new_project = st.text_input('New project name:', key='input_new_project_name')st.button('Add project', key='button_add_project', on_click=submit_add_project, args=(new_project, ))"
},
{
"code": null,
"e": 3265,
"s": 3061,
"text": "Note that the callback function requires project_name argument, hence we need to pass the argument using args. Besides adding a new project, we should also allow the user to delete a project by doing so:"
},
{
"code": null,
"e": 3645,
"s": 3265,
"text": "def submit_delete_project(project_name: str): \"\"\" Callback function during deleting an existing project. \"\"\" st.session_state.projects.remove(project_name)to_delete = st.selectbox('Project to be deleted:', st.session_state.projects)st.button('Delete project', key='button_delete_project', on_click=submit_delete_project, args=(to_delete, ))"
},
{
"code": null,
"e": 3970,
"s": 3645,
"text": "This article shows some examples of session state and callbacks which enable the app to preserve variables across rerun and interaction with widgets. I recommend you to have a try with them for in-depth understanding and check out the streamlit blog post. Lastly, You can find the repo for the data labelling tool in Github."
}
] |
Array Pair Sum Divisibility Problem | Practice | GeeksforGeeks
|
Given an array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair is divisible by k.
Example 1 :
Input : arr = [9, 5, 7, 3], k = 6
Output: True
Explanation: {(9, 3), (5, 7)} is a
possible solution. 9 + 3 = 12 is divisible
by 6 and 7 + 5 = 12 is also divisible by 6.
Example 2:
Input : arr = [2, 4, 1, 3], k = 4
Output: False
Explanation: There is no possible solution.
Your Task:
You don't need to read or print anything. Your task is to complete the function canPair() which takes array and k as input parameter and returns true if array can be divided into pairs such that sum of every pair is divisible by k otherwise returns false.
Expected Time Complexity: O(n)
Expected Space Complexity : O(n)
Constraints:
1 <= length of array <= 100000
1 <= elements of array <= 100000
1 <= k <= 100000
0
akshayjadhav34 days ago
c++ with hash map
bool canPair(vector<int> nums, int k) { // Code here. unordered_map<int,int>s; if(nums.size()%2!=0) { return false; } for(int i=0;i<nums.size();i++) { s[nums[i]%k]++; } for(auto x : s) { if(x.first==0) { if(x.second%2!=0) { return false; } } else { int a=x.first; auto it=s.find(k-a); if(it==s.end()) { return false; } else { if((*it).second!=x.second) { return false; } } } } return true; }
0
gulrezalam5 days ago
Java Solution
Total Time Taken:
0.65/2.3
class Solution {
public boolean canPair(int[] nums, int k) {
if (nums.length % 2 != 0)
return false;
else if (k == 1 || k == 0)
return true;
HashMap<Integer, Integer> rem = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int remainder = nums[i] % k;
rem.put(remainder, rem.getOrDefault(remainder, 0) + 1);
}
for (int e: rem.keySet()) {
int dif = k - e;
if (e == 0) {
if (rem.get(e) % 2 != 0)
return false;
}
else if (rem.containsKey(dif)) {
if (rem.get(e) != rem.get(dif))
return false;
}
else {
return false;
}
}
return true;
}
}
0
patilamrut1793 weeks ago
javascriptclass Solution { canPair(nums,k){ //code here const len = nums.length; if(len%2!==0) return false; let pairs = 0; const hash = {}; for(let i=0; i<len; i++) { const mod = nums[i]%k; if(mod === 0 && hash[mod]) { pairs++; hash[mod]--; if(hash[mod]===0) delete hash[mod]; } else if(hash[k-mod]) { pairs++; hash[k-mod]--; if(hash[k-mod]===0) delete hash[k-mod]; } else { hash[mod] = (hash[mod] || 0)+1; } } return (len/2)===pairs; }}
0
lindan1233 weeks ago
bool canPair(vector<int> nums, int k) {
unordered_map<int,int> mp;
if(nums.size()%2!=0)
{
return false;
}
for(int i=0;i<nums.size();i++)
{
mp[nums[i]%k]++;
}
for(auto x : mp)
{
int rem = k-x.first;
if(x.first==0)
{
if(mp[0]%2!=0)return false;
}
else if(mp[x.first]!=mp[rem]) return false;
}
return true;
}
Time Taken : 0.22sec
Cpp
0
imranwahid3 weeks ago
Easy C++ solution
0
amrit_kumar3 weeks ago
c++ simple soln
bool canPair(vector<int> nums, int k)
{
int ans=0;
if(nums.size()%2!=0) return false;
unordered_map<int,int> mp;
for(int i=0;i<nums.size();i++)
mp[nums[i]%k]++;
for(auto i = mp.begin();i!=mp.end();i++)
{
int temp = k-i->first;
if(i->first==0)
{
if(mp[0]%2!=0) return false;
}
else if(mp[i->first]!=mp[temp]) return false;
}
return true;
}
0
himanshu201911 month ago
int n=nums.size(); if(n%2!=0) return false; vector<int> vec; for(int i=0;i<n;i++){ vec.push_back(nums[i]%k); } unordered_map<int,int> m; for(int i=0;i<n;i++){ m[vec[i]]++; } for(int i=0;i<n;i++){ if(vec[i]==0){ if(m[vec[i]]%2!=0) return false; } else if(2*vec[i]==k){ if(m[vec[i]]%2!=0) return false; } else{ if(m[vec[i]]!=m[k-vec[i]]) return false; } } return true;
+3
mayank_manas1 month ago
this shouldn't be in the easy section.
-1
abhishektiwari162 months ago
class Solution {
boolean flag = false;
public boolean canPair(int[] nums, int k) {
// Code here
HashSet<Integer> set = new HashSet<>();
HashMap<Integer,Integer> map = new HashMap<>();
int key;
for(int i: nums){
key = (k-(i%k))%k;
if(map.containsKey(key)){
map.put(key, map.get(key) - 1);
if(map.get(key) == 0)
map.remove(key);
}
else{
key = i%k;
if(map.containsKey(key)) map.put(key, map.get(key) +1);
else
map.put(key, 1);
}
}
if(map.size() == 0)
return true;
return false;
}
}
0
ayushsunariya4582 months ago
bool canPair(vector<int> nums, int k) {
// Code here.
vector<int>res(k,0);
for(auto &x:nums){
x%=k;
res[x]++;
}
for(auto x:nums){
if(x==0){
if(res[0]%2==0){
continue;
}
else return false;
}
if(res[k-x]>0){
res[k-x]--;
}
else return false;
}
return true;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 406,
"s": 238,
"text": "Given an array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair is divisible by k.\n "
},
{
"code": null,
"e": 418,
"s": 406,
"text": "Example 1 :"
},
{
"code": null,
"e": 590,
"s": 418,
"text": "Input : arr = [9, 5, 7, 3], k = 6\nOutput: True\nExplanation: {(9, 3), (5, 7)} is a \npossible solution. 9 + 3 = 12 is divisible\nby 6 and 7 + 5 = 12 is also divisible by 6.\n\n"
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Example 2:"
},
{
"code": null,
"e": 694,
"s": 601,
"text": "Input : arr = [2, 4, 1, 3], k = 4\nOutput: False\nExplanation: There is no possible solution.\n"
},
{
"code": null,
"e": 965,
"s": 696,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function canPair() which takes array and k as input parameter and returns true if array can be divided into pairs such that sum of every pair is divisible by k otherwise returns false.\n "
},
{
"code": null,
"e": 1031,
"s": 965,
"text": "Expected Time Complexity: O(n)\nExpected Space Complexity : O(n)\n "
},
{
"code": null,
"e": 1125,
"s": 1031,
"text": "Constraints:\n1 <= length of array <= 100000\n1 <= elements of array <= 100000\n1 <= k <= 100000"
},
{
"code": null,
"e": 1127,
"s": 1125,
"text": "0"
},
{
"code": null,
"e": 1151,
"s": 1127,
"text": "akshayjadhav34 days ago"
},
{
"code": null,
"e": 1169,
"s": 1151,
"text": "c++ with hash map"
},
{
"code": null,
"e": 2280,
"s": 1171,
"text": "bool canPair(vector<int> nums, int k) { // Code here. unordered_map<int,int>s; if(nums.size()%2!=0) { return false; } for(int i=0;i<nums.size();i++) { s[nums[i]%k]++; } for(auto x : s) { if(x.first==0) { if(x.second%2!=0) { return false; } } else { int a=x.first; auto it=s.find(k-a); if(it==s.end()) { return false; } else { if((*it).second!=x.second) { return false; } } } } return true; }"
},
{
"code": null,
"e": 2288,
"s": 2286,
"text": "0"
},
{
"code": null,
"e": 2309,
"s": 2288,
"text": "gulrezalam5 days ago"
},
{
"code": null,
"e": 3225,
"s": 2309,
"text": "Java Solution\n\n\n\nTotal Time Taken:\n0.65/2.3\n\n\n\n\n\nclass Solution {\n \n public boolean canPair(int[] nums, int k) {\n if (nums.length % 2 != 0)\n return false;\n else if (k == 1 || k == 0)\n return true;\n \n HashMap<Integer, Integer> rem = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++) {\n int remainder = nums[i] % k;\n rem.put(remainder, rem.getOrDefault(remainder, 0) + 1);\n }\n\n for (int e: rem.keySet()) {\n int dif = k - e;\n \n if (e == 0) {\n if (rem.get(e) % 2 != 0)\n return false;\n }\n else if (rem.containsKey(dif)) {\n if (rem.get(e) != rem.get(dif))\n return false;\n }\n else {\n return false;\n }\n }\n return true;\n }\n}"
},
{
"code": null,
"e": 3231,
"s": 3229,
"text": "0"
},
{
"code": null,
"e": 3256,
"s": 3231,
"text": "patilamrut1793 weeks ago"
},
{
"code": null,
"e": 3895,
"s": 3256,
"text": "javascriptclass Solution { canPair(nums,k){ //code here const len = nums.length; if(len%2!==0) return false; let pairs = 0; const hash = {}; for(let i=0; i<len; i++) { const mod = nums[i]%k; if(mod === 0 && hash[mod]) { pairs++; hash[mod]--; if(hash[mod]===0) delete hash[mod]; } else if(hash[k-mod]) { pairs++; hash[k-mod]--; if(hash[k-mod]===0) delete hash[k-mod]; } else { hash[mod] = (hash[mod] || 0)+1; } } return (len/2)===pairs; }}"
},
{
"code": null,
"e": 3897,
"s": 3895,
"text": "0"
},
{
"code": null,
"e": 3918,
"s": 3897,
"text": "lindan1233 weeks ago"
},
{
"code": null,
"e": 4469,
"s": 3918,
"text": "bool canPair(vector<int> nums, int k) {\n \n unordered_map<int,int> mp;\n if(nums.size()%2!=0)\n {\n return false;\n }\n \n for(int i=0;i<nums.size();i++)\n {\n mp[nums[i]%k]++;\n }\n \n for(auto x : mp)\n {\n int rem = k-x.first;\n \n if(x.first==0)\n {\n if(mp[0]%2!=0)return false;\n }\n \n else if(mp[x.first]!=mp[rem]) return false;\n }\n return true;\n }"
},
{
"code": null,
"e": 4490,
"s": 4469,
"text": "Time Taken : 0.22sec"
},
{
"code": null,
"e": 4494,
"s": 4490,
"text": "Cpp"
},
{
"code": null,
"e": 4496,
"s": 4494,
"text": "0"
},
{
"code": null,
"e": 4518,
"s": 4496,
"text": "imranwahid3 weeks ago"
},
{
"code": null,
"e": 4536,
"s": 4518,
"text": "Easy C++ solution"
},
{
"code": null,
"e": 4538,
"s": 4536,
"text": "0"
},
{
"code": null,
"e": 4561,
"s": 4538,
"text": "amrit_kumar3 weeks ago"
},
{
"code": null,
"e": 4577,
"s": 4561,
"text": "c++ simple soln"
},
{
"code": null,
"e": 5114,
"s": 4579,
"text": "bool canPair(vector<int> nums, int k) \n {\n int ans=0;\n \n if(nums.size()%2!=0) return false;\n unordered_map<int,int> mp;\n \n for(int i=0;i<nums.size();i++)\n mp[nums[i]%k]++;\n \n for(auto i = mp.begin();i!=mp.end();i++)\n {\n int temp = k-i->first;\n if(i->first==0)\n {\n if(mp[0]%2!=0) return false;\n }\n \n else if(mp[i->first]!=mp[temp]) return false;\n \n \n }\n \n return true;\n \n }"
},
{
"code": null,
"e": 5116,
"s": 5114,
"text": "0"
},
{
"code": null,
"e": 5141,
"s": 5116,
"text": "himanshu201911 month ago"
},
{
"code": null,
"e": 5690,
"s": 5141,
"text": "int n=nums.size(); if(n%2!=0) return false; vector<int> vec; for(int i=0;i<n;i++){ vec.push_back(nums[i]%k); } unordered_map<int,int> m; for(int i=0;i<n;i++){ m[vec[i]]++; } for(int i=0;i<n;i++){ if(vec[i]==0){ if(m[vec[i]]%2!=0) return false; } else if(2*vec[i]==k){ if(m[vec[i]]%2!=0) return false; } else{ if(m[vec[i]]!=m[k-vec[i]]) return false; } } return true;"
},
{
"code": null,
"e": 5693,
"s": 5690,
"text": "+3"
},
{
"code": null,
"e": 5717,
"s": 5693,
"text": "mayank_manas1 month ago"
},
{
"code": null,
"e": 5756,
"s": 5717,
"text": "this shouldn't be in the easy section."
},
{
"code": null,
"e": 5759,
"s": 5756,
"text": "-1"
},
{
"code": null,
"e": 5788,
"s": 5759,
"text": "abhishektiwari162 months ago"
},
{
"code": null,
"e": 6592,
"s": 5788,
"text": "class Solution {\n boolean flag = false;\n \n public boolean canPair(int[] nums, int k) {\n // Code here\n HashSet<Integer> set = new HashSet<>();\n \n HashMap<Integer,Integer> map = new HashMap<>();\n \n \n \n int key;\n for(int i: nums){\n \n key = (k-(i%k))%k;\n if(map.containsKey(key)){\n map.put(key, map.get(key) - 1);\n if(map.get(key) == 0)\n map.remove(key);\n }\n else{\n key = i%k;\n if(map.containsKey(key)) map.put(key, map.get(key) +1);\n else\n map.put(key, 1);\n }\n }\n \n if(map.size() == 0)\n return true;\n \n return false;\n }\n}"
},
{
"code": null,
"e": 6594,
"s": 6592,
"text": "0"
},
{
"code": null,
"e": 6623,
"s": 6594,
"text": "ayushsunariya4582 months ago"
},
{
"code": null,
"e": 7109,
"s": 6623,
"text": " bool canPair(vector<int> nums, int k) {\n // Code here.\n vector<int>res(k,0);\n for(auto &x:nums){\n x%=k;\n res[x]++;\n }\n\n for(auto x:nums){\n if(x==0){\n if(res[0]%2==0){\n continue;\n }\n else return false;\n }\n if(res[k-x]>0){\n res[k-x]--;\n }\n else return false;\n }\n return true;\n }"
},
{
"code": null,
"e": 7255,
"s": 7109,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 7291,
"s": 7255,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7301,
"s": 7291,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7311,
"s": 7301,
"text": "\nContest\n"
},
{
"code": null,
"e": 7374,
"s": 7311,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7522,
"s": 7374,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7730,
"s": 7522,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7836,
"s": 7730,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C# | Math.Atan() Method - GeeksforGeeks
|
31 Jan, 2019
Math.Atan() is an inbuilt Math class method which returns the angle whose tangent is given as a double value argument. If the argument is NaN, then the result will be NaN.
Syntax:
public static double Atan(double num)
Parameter:
num: It is the number that represents a tangent and type of this parameter is System.Double.
Return Type: Returns an angle Ξ, measured in radians and its type is System.Double. Here the angle is always measured in radians, such that -Ο/2 β€ Ξ β€ Ο/2.
Examples:
Input : Math.Atan(1)
Output : 0.785398163397448
Input : Math.Atan(0.0)
Output : 0
Input : Math.Atan(-0.0)
Output : 0
Input : Math.Atan(Double.PositiveInfinity)
Output : 1.5707963267949
Input : Math.Atan(Double.NegativeInfinity)
Output : -1.5707963267949
Program: To illustrate the Math.Atan() method
// C# program to demonstrate working// of Math.Atan() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = Math.PI; // using Math.Atan() method Console.WriteLine(Math.Atan(a)); double d = 0.0; double e = -0.0; double posi = Double.PositiveInfinity; double nega = Double.NegativeInfinity; double nan = Double.NaN; Console.WriteLine(Math.Atan(1)); // Input positive zero // Output positive zero Console.WriteLine(Math.Atan(d)); // Input negative zero // Output positive zero Console.WriteLine(Math.Atan(e)); // input PositiveInfinity // Output 1.5707963267949 Console.WriteLine(Math.Atan(posi)); // input NegativeInfinity // Output -1.5707963267949 Console.WriteLine(Math.Atan(nega)); // input NaN // Output NaN Console.WriteLine(Math.Atan(nan)); }}
1.26262725567891
0.785398163397448
0
0
1.5707963267949
-1.5707963267949
NaN
Reference: https://msdn.microsoft.com/en-us/library/system.math.atan
CSharp-Math
CSharp-method
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#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 25719,
"s": 25547,
"text": "Math.Atan() is an inbuilt Math class method which returns the angle whose tangent is given as a double value argument. If the argument is NaN, then the result will be NaN."
},
{
"code": null,
"e": 25727,
"s": 25719,
"text": "Syntax:"
},
{
"code": null,
"e": 25766,
"s": 25727,
"text": "public static double Atan(double num)\n"
},
{
"code": null,
"e": 25777,
"s": 25766,
"text": "Parameter:"
},
{
"code": null,
"e": 25870,
"s": 25777,
"text": "num: It is the number that represents a tangent and type of this parameter is System.Double."
},
{
"code": null,
"e": 26026,
"s": 25870,
"text": "Return Type: Returns an angle Ξ, measured in radians and its type is System.Double. Here the angle is always measured in radians, such that -Ο/2 β€ Ξ β€ Ο/2."
},
{
"code": null,
"e": 26036,
"s": 26026,
"text": "Examples:"
},
{
"code": null,
"e": 26305,
"s": 26036,
"text": "Input : Math.Atan(1)\nOutput : 0.785398163397448\n \nInput : Math.Atan(0.0)\nOutput : 0\n\nInput : Math.Atan(-0.0)\nOutput : 0\n\nInput : Math.Atan(Double.PositiveInfinity)\nOutput : 1.5707963267949\n\nInput : Math.Atan(Double.NegativeInfinity)\nOutput : -1.5707963267949\n"
},
{
"code": null,
"e": 26351,
"s": 26305,
"text": "Program: To illustrate the Math.Atan() method"
},
{
"code": "// C# program to demonstrate working// of Math.Atan() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = Math.PI; // using Math.Atan() method Console.WriteLine(Math.Atan(a)); double d = 0.0; double e = -0.0; double posi = Double.PositiveInfinity; double nega = Double.NegativeInfinity; double nan = Double.NaN; Console.WriteLine(Math.Atan(1)); // Input positive zero // Output positive zero Console.WriteLine(Math.Atan(d)); // Input negative zero // Output positive zero Console.WriteLine(Math.Atan(e)); // input PositiveInfinity // Output 1.5707963267949 Console.WriteLine(Math.Atan(posi)); // input NegativeInfinity // Output -1.5707963267949 Console.WriteLine(Math.Atan(nega)); // input NaN // Output NaN Console.WriteLine(Math.Atan(nan)); }}",
"e": 27379,
"s": 26351,
"text": null
},
{
"code": null,
"e": 27456,
"s": 27379,
"text": "1.26262725567891\n0.785398163397448\n0\n0\n1.5707963267949\n-1.5707963267949\nNaN\n"
},
{
"code": null,
"e": 27525,
"s": 27456,
"text": "Reference: https://msdn.microsoft.com/en-us/library/system.math.atan"
},
{
"code": null,
"e": 27537,
"s": 27525,
"text": "CSharp-Math"
},
{
"code": null,
"e": 27551,
"s": 27537,
"text": "CSharp-method"
},
{
"code": null,
"e": 27554,
"s": 27551,
"text": "C#"
},
{
"code": null,
"e": 27652,
"s": 27554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27675,
"s": 27652,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27703,
"s": 27675,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27720,
"s": 27703,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27742,
"s": 27720,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27771,
"s": 27742,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27811,
"s": 27771,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27834,
"s": 27811,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 27877,
"s": 27834,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27917,
"s": 27877,
"text": "Convert String to Character Array in C#"
}
] |
How to Build a JavaScript Command Line Interface (CLI) with Node.js - GeeksforGeeks
|
04 Aug, 2021
In this article, we will see how to create a JavaScript CLI with the help of NodeJs.
JavaScript being an interpreter language, it is a very dynamic language, due to which it provides us with many facilities, due to which many tasks become very easy and anyone can understand them very easily, so in todayβs era JavaScript It is one of the most popular programming languages ββof the world, that is why today many tools are being built in it.
In this article, we will build a CLI application with the help of JavaScript. We need NodeJs to run JavaScript directly. If you have not installed NodeJs on your computer or facing any problem in NodeJs, then refer to this article.
Approach: We want to make a CLI application in JavaScript but JavaScript runs only on the browser but if we want to use it outside the browser then we will need a run-time that NodeJS provides so we have to use NodeJs. Then we will be able to create a CLI application with the help of JavaScript. We will use readline module of nodejs.
Step 1: In the first step, we set up a NodeJs project environment. If you do have not installed NPM or NodeJs please refer to this article.
Run the below command and initiate the NodeJs project.
npm init -y
Use β-yβ to keep default answers to all questions.
Project Structure: After doing the above things move to create an index.js file for writing our code, and the directory looks like this.
.Step 2: Now we will see the working of the NodeJs readline module.
The readline module allows reading a data stream one line at a time. It can be included in the code with the require() method. We can enter any stream of data we want in the readline module, which allows us to work with standard input and output streams. Or the readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. It can be accessed using. The question method of the readline provides a facility to work a query-response mechanism we use the question method and pass two arguments first one is a query and the second one is a custom handler to take an argument as an input of the handler function.
Syntax:
readline.question(query, callback);
Accepts the display query string and the callback function to be invoked as a response of the userβs input to the query. The createInterface method of the readline provides an interface object to work with readline and their methods.
Syntax:
readline.createInterface();
Now letβs see the code implementation of the above approach. The below code shows the use of readline module for accepting input from the user as a CLI.
index.js
// import the readline module for work with stdin, or stdout.const readline = require('readline'); // create a readline object to work with the stream.// pass the stdin, or stdout in the current process.const prompts = readline.createInterface(process.stdin, process.stdout); // create a question or there handler.prompts.question('Enter Learning Resources Name : ', (response) => { // check the response. if(response.toLocaleLowerCase() == 'gfg') { console.log("You are a part of the very huge learning community."); }else { console.log("Have a look at Geeksforgeeks, they solve many of your technical doubts."); } // after the all work is done want to terminate this process. process.exit();});
Step to run the application:
node index.js
Output:
Explanation: The createInterface method is used to create an interface to take user input. It takes two parameters, the standard input (stdin) and standard output (stdout) of the current process. Next, the question() method of the createInterface object is used to prompt a question to the user. The second parameter is a callback function the will process the userβs input passed to it as a parameter. The logic inside the function will display an appropriate message based on the evaluation of the userβs input value. The process.exit() statement allows to exit the code else the interface will keep reading from the standard input.
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26403,
"s": 26375,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 26488,
"s": 26403,
"text": "In this article, we will see how to create a JavaScript CLI with the help of NodeJs."
},
{
"code": null,
"e": 26845,
"s": 26488,
"text": "JavaScript being an interpreter language, it is a very dynamic language, due to which it provides us with many facilities, due to which many tasks become very easy and anyone can understand them very easily, so in todayβs era JavaScript It is one of the most popular programming languages ββof the world, that is why today many tools are being built in it."
},
{
"code": null,
"e": 27077,
"s": 26845,
"text": "In this article, we will build a CLI application with the help of JavaScript. We need NodeJs to run JavaScript directly. If you have not installed NodeJs on your computer or facing any problem in NodeJs, then refer to this article."
},
{
"code": null,
"e": 27413,
"s": 27077,
"text": "Approach: We want to make a CLI application in JavaScript but JavaScript runs only on the browser but if we want to use it outside the browser then we will need a run-time that NodeJS provides so we have to use NodeJs. Then we will be able to create a CLI application with the help of JavaScript. We will use readline module of nodejs."
},
{
"code": null,
"e": 27553,
"s": 27413,
"text": "Step 1: In the first step, we set up a NodeJs project environment. If you do have not installed NPM or NodeJs please refer to this article."
},
{
"code": null,
"e": 27608,
"s": 27553,
"text": "Run the below command and initiate the NodeJs project."
},
{
"code": null,
"e": 27620,
"s": 27608,
"text": "npm init -y"
},
{
"code": null,
"e": 27671,
"s": 27620,
"text": "Use β-yβ to keep default answers to all questions."
},
{
"code": null,
"e": 27808,
"s": 27671,
"text": "Project Structure: After doing the above things move to create an index.js file for writing our code, and the directory looks like this."
},
{
"code": null,
"e": 27877,
"s": 27808,
"text": ".Step 2: Now we will see the working of the NodeJs readline module. "
},
{
"code": null,
"e": 28546,
"s": 27877,
"text": "The readline module allows reading a data stream one line at a time. It can be included in the code with the require() method. We can enter any stream of data we want in the readline module, which allows us to work with standard input and output streams. Or the readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. It can be accessed using. The question method of the readline provides a facility to work a query-response mechanism we use the question method and pass two arguments first one is a query and the second one is a custom handler to take an argument as an input of the handler function. "
},
{
"code": null,
"e": 28554,
"s": 28546,
"text": "Syntax:"
},
{
"code": null,
"e": 28590,
"s": 28554,
"text": "readline.question(query, callback);"
},
{
"code": null,
"e": 28824,
"s": 28590,
"text": "Accepts the display query string and the callback function to be invoked as a response of the userβs input to the query. The createInterface method of the readline provides an interface object to work with readline and their methods."
},
{
"code": null,
"e": 28832,
"s": 28824,
"text": "Syntax:"
},
{
"code": null,
"e": 28860,
"s": 28832,
"text": "readline.createInterface();"
},
{
"code": null,
"e": 29013,
"s": 28860,
"text": "Now letβs see the code implementation of the above approach. The below code shows the use of readline module for accepting input from the user as a CLI."
},
{
"code": null,
"e": 29022,
"s": 29013,
"text": "index.js"
},
{
"code": "// import the readline module for work with stdin, or stdout.const readline = require('readline'); // create a readline object to work with the stream.// pass the stdin, or stdout in the current process.const prompts = readline.createInterface(process.stdin, process.stdout); // create a question or there handler.prompts.question('Enter Learning Resources Name : ', (response) => { // check the response. if(response.toLocaleLowerCase() == 'gfg') { console.log(\"You are a part of the very huge learning community.\"); }else { console.log(\"Have a look at Geeksforgeeks, they solve many of your technical doubts.\"); } // after the all work is done want to terminate this process. process.exit();});",
"e": 29765,
"s": 29022,
"text": null
},
{
"code": null,
"e": 29794,
"s": 29765,
"text": "Step to run the application:"
},
{
"code": null,
"e": 29808,
"s": 29794,
"text": "node index.js"
},
{
"code": null,
"e": 29816,
"s": 29808,
"text": "Output:"
},
{
"code": null,
"e": 30452,
"s": 29816,
"text": "Explanation: The createInterface method is used to create an interface to take user input. It takes two parameters, the standard input (stdin) and standard output (stdout) of the current process. Next, the question() method of the createInterface object is used to prompt a question to the user. The second parameter is a callback function the will process the userβs input passed to it as a parameter. The logic inside the function will display an appropriate message based on the evaluation of the userβs input value. The process.exit() statement allows to exit the code else the interface will keep reading from the standard input."
},
{
"code": null,
"e": 30468,
"s": 30452,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 30485,
"s": 30468,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 30492,
"s": 30485,
"text": "Picked"
},
{
"code": null,
"e": 30500,
"s": 30492,
"text": "Node.js"
},
{
"code": null,
"e": 30517,
"s": 30500,
"text": "Web Technologies"
},
{
"code": null,
"e": 30615,
"s": 30517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30685,
"s": 30615,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 30710,
"s": 30685,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 30749,
"s": 30710,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 30771,
"s": 30749,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 30798,
"s": 30771,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 30838,
"s": 30798,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30883,
"s": 30838,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30926,
"s": 30883,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30976,
"s": 30926,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
CakePHP - Views
|
The letter βVβ in the MVC is for Views. Views are responsible for sending output to user based on request. View Classes is a powerful way to speed up the development process.
The View Templates file of CakePHP gets data from controller and then render the output so that it can be displayed properly to the user. We can use variables, various control structures in template.
Template files are stored in src/Template/, in a directory named after the controller that uses the files, and named after the action it corresponds to. For example, the Viewfile for the Products controllerβs βview()β action, would normally be found in src/Template/Products/view.php.
In short, the name of the controller (ProductsController) is same as the name of the folder (Products) but without the word Controller and name of action/method (view()) of the controller (ProductsController) is same as the name of the View file(view.php).
View variables are variables which get the value from controller. We can use as many variables in view templates as we want. We can use the set() method to pass values to variables in views. These set variables will be available in both the view and the layout your action renders. The following is the syntax of the set() method.
Cake\View\View::set(string $var, mixed $value)
This method takes two arguments β the name of the variable and its value.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
// Register scoped middleware for in scopes.
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
$builder->connect('template',['controller'=>'Products','action'=>'view']);
$builder->fallbacks();
});
Create a ProductsController.php file at src/Controller/ProductsController.php. Copy the following code in the controller file.
src/Controller/ProductsController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\View\Exception\MissingTemplateException;
class ProductsController extends AppController {
public function view(){
$this->set('Product_Name','XYZ');
}
}
Create a directory Products at src/Template and under that folder create a View file called view.php. Copy the following code in that file.
Value of variable is: <?php echo $Product_Name; ? >
Execute the above example by visiting the following URL.
http://localhost/cakephp4/template
The above URL will produce the following output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2417,
"s": 2242,
"text": "The letter βVβ in the MVC is for Views. Views are responsible for sending output to user based on request. View Classes is a powerful way to speed up the development process."
},
{
"code": null,
"e": 2617,
"s": 2417,
"text": "The View Templates file of CakePHP gets data from controller and then render the output so that it can be displayed properly to the user. We can use variables, various control structures in template."
},
{
"code": null,
"e": 2902,
"s": 2617,
"text": "Template files are stored in src/Template/, in a directory named after the controller that uses the files, and named after the action it corresponds to. For example, the Viewfile for the Products controllerβs βview()β action, would normally be found in src/Template/Products/view.php."
},
{
"code": null,
"e": 3159,
"s": 2902,
"text": "In short, the name of the controller (ProductsController) is same as the name of the folder (Products) but without the word Controller and name of action/method (view()) of the controller (ProductsController) is same as the name of the View file(view.php)."
},
{
"code": null,
"e": 3490,
"s": 3159,
"text": "View variables are variables which get the value from controller. We can use as many variables in view templates as we want. We can use the set() method to pass values to variables in views. These set variables will be available in both the view and the layout your action renders. The following is the syntax of the set() method."
},
{
"code": null,
"e": 3537,
"s": 3490,
"text": "Cake\\View\\View::set(string $var, mixed $value)"
},
{
"code": null,
"e": 3611,
"s": 3537,
"text": "This method takes two arguments β the name of the variable and its value."
},
{
"code": null,
"e": 3689,
"s": 3611,
"text": "Make Changes in the config/routes.php file as shown in the following program."
},
{
"code": null,
"e": 3707,
"s": 3689,
"text": "config/routes.php"
},
{
"code": null,
"e": 4229,
"s": 3707,
"text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n // Register scoped middleware for in scopes.\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n $builder->connect('template',['controller'=>'Products','action'=>'view']);\n $builder->fallbacks();\n});"
},
{
"code": null,
"e": 4356,
"s": 4229,
"text": "Create a ProductsController.php file at src/Controller/ProductsController.php. Copy the following code in the controller file."
},
{
"code": null,
"e": 4394,
"s": 4356,
"text": "src/Controller/ProductsController.php"
},
{
"code": null,
"e": 4757,
"s": 4394,
"text": "<?php\ndeclare(strict_types=1);\nnamespace App\\Controller;\nuse Cake\\Core\\Configure;\nuse Cake\\Http\\Exception\\ForbiddenException;\nuse Cake\\Http\\Exception\\NotFoundException;\nuse Cake\\Http\\Response;\nuse Cake\\View\\Exception\\MissingTemplateException;\nclass ProductsController extends AppController {\npublic function view(){\n $this->set('Product_Name','XYZ');\n }\n}"
},
{
"code": null,
"e": 4897,
"s": 4757,
"text": "Create a directory Products at src/Template and under that folder create a View file called view.php. Copy the following code in that file."
},
{
"code": null,
"e": 4950,
"s": 4897,
"text": "Value of variable is: <?php echo $Product_Name; ? >\n"
},
{
"code": null,
"e": 5007,
"s": 4950,
"text": "Execute the above example by visiting the following URL."
},
{
"code": null,
"e": 5042,
"s": 5007,
"text": "http://localhost/cakephp4/template"
},
{
"code": null,
"e": 5091,
"s": 5042,
"text": "The above URL will produce the following output."
},
{
"code": null,
"e": 5098,
"s": 5091,
"text": " Print"
},
{
"code": null,
"e": 5109,
"s": 5098,
"text": " Add Notes"
}
] |
Data Visualization with Leaflet Using R: Tutorial for the Beginner | by Audhi Aprilliant | Towards Data Science
|
1 Whatβs leaflet?2 Interaction Features3 Prerequisites4 Letβs Create the Data Viz5 Recap6 Conclusion7 References
The leaflet is an open-source library for easily making spatial data visualization. Because it is an open-source library and integrated into any platform and programming language, it currently becomes the most popular map library in the world. Historically, the leaflet is firstly developed by Vladimir Agafonkin in 2011.
Before we begin to build the visualization, make sure we fulfill the following requirements.
Programming language of R with several libraries, such as leaflet, leaflet.extras, and dplyr
The data consists of location points (latitude and longitude) and additional information. You can easily download the sample data here
Good internet connection
Building a script to create a leaflet map in R is quite simple. But, if we want to build an interactive and beautiful map, of course, some script must be added. The following script will create our simple map (actually itβs quite cool). Why? Because we have added some information to our marker, such as locationβs name, address, longitude, latitude, supervisor, and student's name, instead of only markers. That information is displayed using a popup after we click the marker.
leaflet(data.location) %>% addProviderTiles(providers$OpenStreetMap) %>% addMarkers(lng = ~long, lat = ~lat, popup = paste(paste('<b>Office:</b>', data.location$place), paste('<b>Address:</b>', data.location$address), paste('<b>Lat:</b>', data.location$lat), paste('<b>Long:</b>', data.location$long), paste('<b>Supervisor:</b>', data.location$supervisor), data.location$student1, data.location$student2, data.location$student3, sep = '<br/>'), label = ~place, group = 'data.location')
Okay, letβs add some features to our map. After zooming in and out of each location, itβs good to reset our view to default. So, we can add a reset map button. Further, we have a search feature to simplify our searching, just by typing our locationβs name and the algorithm will show up relevant results based on our keyword. So, just add the following script at the bottom of the previous script.
addResetMapButton() %>%addSearchFeatures( targetGroups = 'data.location', options = searchFeaturesOptions(zoom = 15, openPopup = TRUE, firstTipSubmit = TRUE, autoCollapse = TRUE, hideMarkerOnCollapse = TRUE))
Okay then, we add the measure button and highlight it for general info or title. For the measure button, as its name, it will show us the distance between two points or more. We can estimate the distance between two cities using this feature. If we meet the zigzag route, we can draw a straight line point by point. The unit of measurement must be set depending on our needs, for instance in meters. Lastly, to show up our general information, itβs good to add infobox.
addMeasure( position = 'bottomleft', primaryLengthUnit = 'meters', primaryAreaUnit = 'sqmeters', activeColor = '#3D535D', completedColor = '#7D4479') %>%addControl("<P><b>Masterpiece Statistics 53</b><br/>Search for offices/ industries<br/>in Java by name.</P>", position = 'topright')
To recap our script, we can run the following script properly, and voila, our map is ready to interpret and launch to production.
We can look at our map like the following figure.
And we can try the feature of searching. For instance, according to our previous codes, it will read any input from the data.
So, we can easily use leaflets as our tools to visualize the spatial data. It provides many features, such as searching features, zooming, and others. The leaflet is also easy to deploy into the HTML.
[1] A. Woodruff, R. Mullins, C. Jones. Leaflet: Make a web map! (2014), http://maptimeboston.github.io/leaflet-intro.
[2] V. Agafonkin. Leaflet: An Open-source JavaScript Library for Mobile-friendly Interactive Maps (2019), https://leafletjs.com/index.html.
|
[
{
"code": null,
"e": 285,
"s": 172,
"text": "1 Whatβs leaflet?2 Interaction Features3 Prerequisites4 Letβs Create the Data Viz5 Recap6 Conclusion7 References"
},
{
"code": null,
"e": 607,
"s": 285,
"text": "The leaflet is an open-source library for easily making spatial data visualization. Because it is an open-source library and integrated into any platform and programming language, it currently becomes the most popular map library in the world. Historically, the leaflet is firstly developed by Vladimir Agafonkin in 2011."
},
{
"code": null,
"e": 700,
"s": 607,
"text": "Before we begin to build the visualization, make sure we fulfill the following requirements."
},
{
"code": null,
"e": 793,
"s": 700,
"text": "Programming language of R with several libraries, such as leaflet, leaflet.extras, and dplyr"
},
{
"code": null,
"e": 928,
"s": 793,
"text": "The data consists of location points (latitude and longitude) and additional information. You can easily download the sample data here"
},
{
"code": null,
"e": 953,
"s": 928,
"text": "Good internet connection"
},
{
"code": null,
"e": 1432,
"s": 953,
"text": "Building a script to create a leaflet map in R is quite simple. But, if we want to build an interactive and beautiful map, of course, some script must be added. The following script will create our simple map (actually itβs quite cool). Why? Because we have added some information to our marker, such as locationβs name, address, longitude, latitude, supervisor, and student's name, instead of only markers. That information is displayed using a popup after we click the marker."
},
{
"code": null,
"e": 2336,
"s": 1432,
"text": "leaflet(data.location) %>% addProviderTiles(providers$OpenStreetMap) %>% addMarkers(lng = ~long, lat = ~lat, popup = paste(paste('<b>Office:</b>', data.location$place), paste('<b>Address:</b>', data.location$address), paste('<b>Lat:</b>', data.location$lat), paste('<b>Long:</b>', data.location$long), paste('<b>Supervisor:</b>', data.location$supervisor), data.location$student1, data.location$student2, data.location$student3, sep = '<br/>'), label = ~place, group = 'data.location')"
},
{
"code": null,
"e": 2734,
"s": 2336,
"text": "Okay, letβs add some features to our map. After zooming in and out of each location, itβs good to reset our view to default. So, we can add a reset map button. Further, we have a search feature to simplify our searching, just by typing our locationβs name and the algorithm will show up relevant results based on our keyword. So, just add the following script at the bottom of the previous script."
},
{
"code": null,
"e": 3077,
"s": 2734,
"text": "addResetMapButton() %>%addSearchFeatures( targetGroups = 'data.location', options = searchFeaturesOptions(zoom = 15, openPopup = TRUE, firstTipSubmit = TRUE, autoCollapse = TRUE, hideMarkerOnCollapse = TRUE))"
},
{
"code": null,
"e": 3547,
"s": 3077,
"text": "Okay then, we add the measure button and highlight it for general info or title. For the measure button, as its name, it will show us the distance between two points or more. We can estimate the distance between two cities using this feature. If we meet the zigzag route, we can draw a straight line point by point. The unit of measurement must be set depending on our needs, for instance in meters. Lastly, to show up our general information, itβs good to add infobox."
},
{
"code": null,
"e": 3858,
"s": 3547,
"text": "addMeasure( position = 'bottomleft', primaryLengthUnit = 'meters', primaryAreaUnit = 'sqmeters', activeColor = '#3D535D', completedColor = '#7D4479') %>%addControl(\"<P><b>Masterpiece Statistics 53</b><br/>Search for offices/ industries<br/>in Java by name.</P>\", position = 'topright')"
},
{
"code": null,
"e": 3988,
"s": 3858,
"text": "To recap our script, we can run the following script properly, and voila, our map is ready to interpret and launch to production."
},
{
"code": null,
"e": 4038,
"s": 3988,
"text": "We can look at our map like the following figure."
},
{
"code": null,
"e": 4164,
"s": 4038,
"text": "And we can try the feature of searching. For instance, according to our previous codes, it will read any input from the data."
},
{
"code": null,
"e": 4365,
"s": 4164,
"text": "So, we can easily use leaflets as our tools to visualize the spatial data. It provides many features, such as searching features, zooming, and others. The leaflet is also easy to deploy into the HTML."
},
{
"code": null,
"e": 4483,
"s": 4365,
"text": "[1] A. Woodruff, R. Mullins, C. Jones. Leaflet: Make a web map! (2014), http://maptimeboston.github.io/leaflet-intro."
}
] |
Spearmanβs Rank Correlation Coefficient Using Ordinal Data | by Shinichi Okada | Towards Data Science
|
Table of ContentsIntroduction1. Simplified formula2. General formula3. Pandas corr4. Finding mathematically using the formula (1β1)5 Finding mathematically using the formula (1β2)6. Real-life exampleConclusion
Spearmanβs rank correlation coefficient, rs shows the correlation between two ordinal data. How one ordinal data changes as the other ordinal changes.
A function between ordered sets is called a monotonic function.
In this article, I explore different methods to find Spearmanβs rank correlation coefficient using data with distinct ranks.
Spearmanβs rank correlation requires ordinal data. Examples of ordinal data are:
1st, 2nd, 3rd,
Small, Medium, Large, XL,
Strongly agree, Agree, Neutral, Disagree, Strongly Disagree
Very often, Often, Not Often, Not at all
When all ranks are distinct integers, the Spearman correlation coefficient is computed by the following formula.
This formula is an alternative to Pearsonβs correlation if the data are ordinal and monotonic and if there are no ties in data.
A value of 1 means the set of data is strictly increasing and the value of -1 means it is strictly decreasing. A value of 0 means that data shows no monotonic behavior. The Spearmanβs correlation between two variables will be high when an observation has a similar rank between the two variables.
towardsdatascience.com
The Spearman correlation coefficient is defined as the Pearson correlation coefficient using the rank variables. After raw data, x and y, are converted to ranked data rx and ry, The Spearman correlation coefficient is defined as:
Letβs find out how the correlation of the rank at 5km run relates to the rank of 10km run. All ranks are distinct integers and no same numbers. There are different ways to find the coefficient.
scipy.stats.spearmanr calculates a Spearman correlation coefficient with the associated p-value.Pandas corrUsing the formula (1β1)Using the formula (1β2)
scipy.stats.spearmanr calculates a Spearman correlation coefficient with the associated p-value.
Pandas corr
Using the formula (1β1)
Using the formula (1β2)
Letβs start. We need to import the necessary libraries.
The following is our sample data.
We find rs and p-value using scipy.stats.spearmanr.
correlation=0.428571, p-value=0.337368
The p-value is the level of significance. It determines the probability that the correlation happened by chance.
correlation=0.428571, p-value=0.337368At 5% level of significance, the final rankings is not significant or independent
Pandas corr returns a correlation matrix. We need to select the value from [0,1].
0.42857142857142855
1-(6*(0+4+1+16+1+9+1)/(7*(7**2-1)))=0.4285714285714286
We find the covariance of rx and ry, a standard deviation of Οrx,Οry.
As we expected we get all the same results.
A value of 1 means the set of data is strictly increasing. This happens when the ranks do not change. You find the p-value 0 in this case.
correlation=1.000000, p-value=0.000000
The value of -1 means it is strictly decreasing. The rank is in a reversal order.
correlation=-1.000000, p-value=0.000000
Non-monotonic behavior gives a value of 0.
correlation=0.000000, p-value=1.000000
towardsdatascience.com
We will use data from BIXI MontreΜal. BIXI MontreΜal is a public bicycle sharing system serving MontreΜal, Quebec, Canada. It is a big file so it takes time to process data. Letβs use shape() and head() to see the dimension and the head.
There are more than seventy-nine thousand lines with six columns. Columns are start_data, start_station_code, end_date, end_station_code, duration_sec and is_member.
We group by end_station_code and sum the duration_sec. We assign n_rides with the number of end_station_code.
Letβs plot the imported data.
Please note that the majority of data are on the lower end. We can use scipy.stats.rankdata to see the data by ranking.
Letβs find Spearmanβs Rs.
correlation, pval = spearmanr(by_end_station)print(f'correlation={correlation:.6f}')
The output is:
correlation=0.964881
The number of rides at a bike stop is almost proportional to the number of commuter seconds spend riding it.
We explored finding Spearmanβs correlation coefficient using ordinal data. All four different methods worked well. In Part 2, we are going to use a different data set that has identical data. This will need extra caution to find Spearmanβs correlation coefficient.
Get full access to every story on Medium by becoming a member.
IQ of a person with the number of hours spent on games
Free university meals and their CGPA scores
Physics and Math ranks
To compare the Spearman correlation and the Pearson correlation, please read A comparison of the Pearson and Spearman correlation here
|
[
{
"code": null,
"e": 381,
"s": 171,
"text": "Table of ContentsIntroduction1. Simplified formula2. General formula3. Pandas corr4. Finding mathematically using the formula (1β1)5 Finding mathematically using the formula (1β2)6. Real-life exampleConclusion"
},
{
"code": null,
"e": 532,
"s": 381,
"text": "Spearmanβs rank correlation coefficient, rs shows the correlation between two ordinal data. How one ordinal data changes as the other ordinal changes."
},
{
"code": null,
"e": 596,
"s": 532,
"text": "A function between ordered sets is called a monotonic function."
},
{
"code": null,
"e": 721,
"s": 596,
"text": "In this article, I explore different methods to find Spearmanβs rank correlation coefficient using data with distinct ranks."
},
{
"code": null,
"e": 802,
"s": 721,
"text": "Spearmanβs rank correlation requires ordinal data. Examples of ordinal data are:"
},
{
"code": null,
"e": 817,
"s": 802,
"text": "1st, 2nd, 3rd,"
},
{
"code": null,
"e": 843,
"s": 817,
"text": "Small, Medium, Large, XL,"
},
{
"code": null,
"e": 903,
"s": 843,
"text": "Strongly agree, Agree, Neutral, Disagree, Strongly Disagree"
},
{
"code": null,
"e": 944,
"s": 903,
"text": "Very often, Often, Not Often, Not at all"
},
{
"code": null,
"e": 1057,
"s": 944,
"text": "When all ranks are distinct integers, the Spearman correlation coefficient is computed by the following formula."
},
{
"code": null,
"e": 1185,
"s": 1057,
"text": "This formula is an alternative to Pearsonβs correlation if the data are ordinal and monotonic and if there are no ties in data."
},
{
"code": null,
"e": 1482,
"s": 1185,
"text": "A value of 1 means the set of data is strictly increasing and the value of -1 means it is strictly decreasing. A value of 0 means that data shows no monotonic behavior. The Spearmanβs correlation between two variables will be high when an observation has a similar rank between the two variables."
},
{
"code": null,
"e": 1505,
"s": 1482,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1735,
"s": 1505,
"text": "The Spearman correlation coefficient is defined as the Pearson correlation coefficient using the rank variables. After raw data, x and y, are converted to ranked data rx and ry, The Spearman correlation coefficient is defined as:"
},
{
"code": null,
"e": 1929,
"s": 1735,
"text": "Letβs find out how the correlation of the rank at 5km run relates to the rank of 10km run. All ranks are distinct integers and no same numbers. There are different ways to find the coefficient."
},
{
"code": null,
"e": 2083,
"s": 1929,
"text": "scipy.stats.spearmanr calculates a Spearman correlation coefficient with the associated p-value.Pandas corrUsing the formula (1β1)Using the formula (1β2)"
},
{
"code": null,
"e": 2180,
"s": 2083,
"text": "scipy.stats.spearmanr calculates a Spearman correlation coefficient with the associated p-value."
},
{
"code": null,
"e": 2192,
"s": 2180,
"text": "Pandas corr"
},
{
"code": null,
"e": 2216,
"s": 2192,
"text": "Using the formula (1β1)"
},
{
"code": null,
"e": 2240,
"s": 2216,
"text": "Using the formula (1β2)"
},
{
"code": null,
"e": 2296,
"s": 2240,
"text": "Letβs start. We need to import the necessary libraries."
},
{
"code": null,
"e": 2330,
"s": 2296,
"text": "The following is our sample data."
},
{
"code": null,
"e": 2382,
"s": 2330,
"text": "We find rs and p-value using scipy.stats.spearmanr."
},
{
"code": null,
"e": 2421,
"s": 2382,
"text": "correlation=0.428571, p-value=0.337368"
},
{
"code": null,
"e": 2534,
"s": 2421,
"text": "The p-value is the level of significance. It determines the probability that the correlation happened by chance."
},
{
"code": null,
"e": 2654,
"s": 2534,
"text": "correlation=0.428571, p-value=0.337368At 5% level of significance, the final rankings is not significant or independent"
},
{
"code": null,
"e": 2736,
"s": 2654,
"text": "Pandas corr returns a correlation matrix. We need to select the value from [0,1]."
},
{
"code": null,
"e": 2756,
"s": 2736,
"text": "0.42857142857142855"
},
{
"code": null,
"e": 2811,
"s": 2756,
"text": "1-(6*(0+4+1+16+1+9+1)/(7*(7**2-1)))=0.4285714285714286"
},
{
"code": null,
"e": 2881,
"s": 2811,
"text": "We find the covariance of rx and ry, a standard deviation of Οrx,Οry."
},
{
"code": null,
"e": 2925,
"s": 2881,
"text": "As we expected we get all the same results."
},
{
"code": null,
"e": 3064,
"s": 2925,
"text": "A value of 1 means the set of data is strictly increasing. This happens when the ranks do not change. You find the p-value 0 in this case."
},
{
"code": null,
"e": 3103,
"s": 3064,
"text": "correlation=1.000000, p-value=0.000000"
},
{
"code": null,
"e": 3185,
"s": 3103,
"text": "The value of -1 means it is strictly decreasing. The rank is in a reversal order."
},
{
"code": null,
"e": 3225,
"s": 3185,
"text": "correlation=-1.000000, p-value=0.000000"
},
{
"code": null,
"e": 3268,
"s": 3225,
"text": "Non-monotonic behavior gives a value of 0."
},
{
"code": null,
"e": 3307,
"s": 3268,
"text": "correlation=0.000000, p-value=1.000000"
},
{
"code": null,
"e": 3330,
"s": 3307,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3568,
"s": 3330,
"text": "We will use data from BIXI MontreΜal. BIXI MontreΜal is a public bicycle sharing system serving MontreΜal, Quebec, Canada. It is a big file so it takes time to process data. Letβs use shape() and head() to see the dimension and the head."
},
{
"code": null,
"e": 3734,
"s": 3568,
"text": "There are more than seventy-nine thousand lines with six columns. Columns are start_data, start_station_code, end_date, end_station_code, duration_sec and is_member."
},
{
"code": null,
"e": 3844,
"s": 3734,
"text": "We group by end_station_code and sum the duration_sec. We assign n_rides with the number of end_station_code."
},
{
"code": null,
"e": 3874,
"s": 3844,
"text": "Letβs plot the imported data."
},
{
"code": null,
"e": 3994,
"s": 3874,
"text": "Please note that the majority of data are on the lower end. We can use scipy.stats.rankdata to see the data by ranking."
},
{
"code": null,
"e": 4020,
"s": 3994,
"text": "Letβs find Spearmanβs Rs."
},
{
"code": null,
"e": 4105,
"s": 4020,
"text": "correlation, pval = spearmanr(by_end_station)print(f'correlation={correlation:.6f}')"
},
{
"code": null,
"e": 4120,
"s": 4105,
"text": "The output is:"
},
{
"code": null,
"e": 4141,
"s": 4120,
"text": "correlation=0.964881"
},
{
"code": null,
"e": 4250,
"s": 4141,
"text": "The number of rides at a bike stop is almost proportional to the number of commuter seconds spend riding it."
},
{
"code": null,
"e": 4515,
"s": 4250,
"text": "We explored finding Spearmanβs correlation coefficient using ordinal data. All four different methods worked well. In Part 2, we are going to use a different data set that has identical data. This will need extra caution to find Spearmanβs correlation coefficient."
},
{
"code": null,
"e": 4578,
"s": 4515,
"text": "Get full access to every story on Medium by becoming a member."
},
{
"code": null,
"e": 4633,
"s": 4578,
"text": "IQ of a person with the number of hours spent on games"
},
{
"code": null,
"e": 4677,
"s": 4633,
"text": "Free university meals and their CGPA scores"
},
{
"code": null,
"e": 4700,
"s": 4677,
"text": "Physics and Math ranks"
}
] |
Biometric Signal Verification of Handwriting with Hidden Markov Models | by Tim LoΜhr | Towards Data Science
|
Digital signatures are on the rise. Since many of us are working now from home, a lot of confidential company E-Mails need to be signed online. Ian Goodfellows' invention of Generative Adversarial Networks (GANβs) showed how easy it is nowadays to generate fake numbers on the MNIST dataset. It is actually just a tiny step from that, to also be able to generate imitated signatures with the handwriting style of any person. But isnβt that dangerous?
Can we distinguish with Machine Learning between an original and an artificially crafted signature? Indeed we can! We donβt necessarily even need one of those fancy neural network approaches, we can go totally classic with Hidden Markov Models (HMM). I will show in this post how we can incorporate HMMβs to classify whether a signature was original or imitated.
This project is loosely inspired by the paper of Julian Fierrez et. al. published 2007, called: HMM-Based On-Line Signature Verification.
Even though Hidden Markov Models are not state-of-the-art, as the publishing date β2007β of the paper above already suggests, they are still a fundamental concept every Data Scientist should at least have heard about. Understanding the way an HMM works can be enlightening when you want to understand more recent technologies like Recurrent Neural Networks, because many techniques have evolved out of the HMMβs basic idea.
Hidden Markov Models can include time dependency in their computations. In Figure 1 below we can see, that from each state (Rainy, Sunny) we can transit into Rainy or Sunny back and forth and each of them has a certain probability to emit the three possible output states at every time step (Walk, Shop, Clean). The start probability always needs to be provided as well (60% for Rainy and 40% for Sunny) to start the computational chain.
In our case this means, that a signature is written from left to right with one letter after another. So the time dependency involves the speed, pressure and coordinates of the pen moving around to form a letter. All of this information can be taken into consideration to make an estimate of how likely it is going to be that a signature has been written by the original person or if it has been faked.
Figure 1 suggests that we need prior knowledge about the:
start probability (Rainy 60% or Sunny 40%) Vector
transition (From e.g. Rainy to Rainy 70%) Matrix,
emission (From Rainy to either Walk 10%, Shop 40% or Clean 50%) Matrix
Notice that start probability sums up to 100% and for the Matrices transition and emission each row sums up to 100%.
We need time-dependent data and compute features out of them, then we can fit the GMM to find the parameters for our HMM. When we have the parameters of the HMM, we can compute scores for the original and the imitated signatures. Based on the scores, we can make classification estimates of how likely it is going to be that the signature is true or not.
Why should we even use a Gaussian Mixture Model for training the HMM parameters in the first place? Well basically hmmlearn offers us three possibilities to choose from:
GMM-HMM
Gaussian HMM
Multinomial HMM
The GMM just works the best, because estimating the density of our signature is most likely not just a single Gaussian or single distribution, but the ground truth looks more like a valley, which can be way better approximated by a GMM.
We can exploit GMMβs with the so-called EM (Expectation-Maximization) algorithm let us compute those hidden parameters automatically. What is the EM algorithm expecting to compute the hidden parameters?
The answer is: features.
The GMM uses the EM Algorithm to compute its parameters:
E-step: Compute the component occupation probabilities P(M|x) using the current estimates of the GMM parameters (means, variances)
M-step: Compute the GMM parameters using the current estimates of the component occupation probabilities.
Where we have to choose the Hyperparameters of the GMM, which are:
M: The Gaussian Mixture components
S: The HMM States (Sunny, Rainy)
In reality, we canβt know what the best set of Hyperparameters are, but we could use for example the K-Fold Crossvalidation to find that out.
Wait what, Hyperparameters, HMM parameters?
Ok, Hyperparameters are values that we as humans need to choose. This is also called the Model Selection problem. The Model parameters are parameters that the GMM with the EM algorithms computes for us.
For measuring those kinds of features (pressure, speed, etc.), we need a device like the one shown on the left-most picture below:
I am using the mobisig dataset. It contains 83 entries in total (49 male, 34 female), which we later will split into the train-, test-, and imitationset. The signatures were collected by Margit Antal et. al. and was published 2017 in their research paper: Online Signature Verification on MOBISIG Finger-Drawn Signature Corpus.
This paper provides one example signature.
It can be seen that the forgery signature contains more densely connected pressure points. The paper explains how the forgery was created. You can read it if you want, but this post focuses on how we can detect this forgery, not how it was generated.
I am going to use the hmmlearn package for python, so I donβt have to reinvent the wheel for building HMMβs from scratch.
Letβs start by importing the default packages for this project. I set the random seed, so you will have exactly the same plots as I have.
Also, we want to make sure to load the dataset properly, as can be seen in the code snippet above. The data is stored in dictionaries, were each person has two entries (βoriginalβ and βimitatedβ) which are further split into multiple signatures each. Furthermore, all signatures have a few hundred or thousand rows with the timestamp id (which progresses in milliseconds).
Looking back to Figure 1, the first step to proceed is the feature extraction. Fitting Gaussian, especially Mixture Gaussian is way more effective and efficient if the data points are zero centered and have a normalized standard deviation. From paper [1] we can obtain the following normalization step:
Next, we extract the four features after the normalization step. The formulas (2. Step) are obtained from [3]:
The normalization step 1 is shown in the function (lines: 1β2) of the code. This formula in Figure 3 just means to sum over all xβs and yβs and divide them by the number of occurrences N. So just taking the mean. Furthermore, epsilon (e = np.finfo) is added (lines: 2, 21, 22, 24, ... ) to be protected against a division by zero error.
The four features from step 2 are very straightforward computable. The dot over x and y indicate to use the normed x and y we just computed. Apart from that, theta can is calculated exactly like the formula suggests in line 24 of the code. The path velocity is calculated in line 27 the same way. It is just the square root!
Special attention goes to the Log curvature radius, because if you look closely, you can see that the authors want theta also to be normalized. Therefore in line 30 where Ο (rho) is computed, we also call the norm function on ΞΈ (theta).
The last feature I called alpha in the code, because it sounds nicer than just a. It is as straightforwardly calculated as the rest in line 33 of the code.
I appended all of the features to their according lists, because we need that in order to feed these features in the hidden Markov learning function.
So, we are done with the feature extraction step. Now letβs build the model.Oh no! We need to split the data into train-, test- and imitation datasets. From the mentioned entries I am using the first 25 people as training examples, this is the minimum amount to prevent overfitting, where one entry corresponds to multiple signatures by one person. So the trainset contains 25 different people with many according true and fake signatures. The testset contains another 20 different people and the validationset (X_val) set holds all the imitated signatures.
X_train: (3940, 8)X_test: (3140, 8)X_val: (10338, 8)
Since I said that the row length of all of the signatures were different, I always needed to keep track of the current length and append it to the new data frame. That were quite a hustle to program properly. In line 51, I renamed the features to the names from the feature extraction step.
Important to note is that I am calling the feature extraction function in line 47β49, to compute the features.
To train the GMM HMM, we need to have a look at the documentation from hmmlearn.
We need two essential variables:
transmat ( the transition matrix) (Rainy, Sunny)
startprob (the initial probability matrix for the start)(60% 40% β according to the number of S (HMM States))
The transition matrix will be parameterized such that it is diagonally filled with a 50% probability (0.5), except for the first and the last entry. This is suggested by hmmlearn in the documentation. The same goes for the startprob matrix, I chose the default initialization from hmmlearn.
The features variables X_train are now containing one timestamp and the seven features per row:
X and Y location
The pressure
The four extracted features
Now we can create the model in line 20 of the code below. The number of components and the number of mixtures play an essential role in how good the estimation of imitated signatures will be, but we canβt know what the best values will be as already said. For that reason, I tried different combinations against each other. So let us have a look at how these two hyperparameters behave against each other.
The score function in line 35, 39 and 43 evaluates the scores for the three different sets. Those scores are calculated by the objective function of the GMM, which is the negative log-likelihood.
Alright, letβs call the fit_hmm function with different values for components and GMMβs:
We call it Success when we are having a set of imitated signatures with different or lower scores than the original (blue or green) signatures.
We can see that the number of HMM states have the highest influence on the scores. We want scores that separate the red dots (imitation) as far as possible from the original blue and green dots. Seven or fewer HMM states appear to separate the red dots pretty well from the rest and the GMM components have apparently a low impact on the output.
If we draw a linear classification line between the colored dots,
we can see how well the HMM is able to detect if the signature is fake or not. We would for example set a threshold value at -2200 and then score a new signature. If the value of the score is less than -2200 we claim it to be fake, if it is bigger we say it is an original signature.
What we could do now is save up the scores and train for example a Logistic Regression to predict the probability (0β100%) based on the score on how likely it is that the signature is original or not. This Logistic Regression can be further extended with the accuracy score from sklearn, to estimate the uncertainty of the model.
Success! We can successfully distinguish between imitated and original signatures. Some state-of-the-art approaches to also map time constraints are Recurrent Neural Networks. But for now, we saw that this is also possible with very classical approaches like the HMM.
For more information, you can visit my website and add me in the social media I linked there. I would be happy if you give me a clap on this blog post :).
[1] Julian Fierrez et. al., HMM-based on-line signature verification: Feature extraction and signature modeling (2007), Science Direct[2] Margit Antal, LaΜszloΜ Zsolt SzaboΜ and TuΜnde Tordai, Online Signature Verification on MOBISIG Finger-Drawn Signature Corpus (2017), Hindawi[3] Julian Fierrez et. al., An On-Line Signature Verification System Based on Fusion of Local and Global Information (2005), Springer
This blog post is based from knowledge gained through the course Pattern Analysis from the Friedrich Alexander University Erlangen-NuΜrnberg. I used some parts of the lecture from Dr. Christian Riess to illustrate the examples for this post. So all rights go to Dr. Christian Riess.
|
[
{
"code": null,
"e": 623,
"s": 172,
"text": "Digital signatures are on the rise. Since many of us are working now from home, a lot of confidential company E-Mails need to be signed online. Ian Goodfellows' invention of Generative Adversarial Networks (GANβs) showed how easy it is nowadays to generate fake numbers on the MNIST dataset. It is actually just a tiny step from that, to also be able to generate imitated signatures with the handwriting style of any person. But isnβt that dangerous?"
},
{
"code": null,
"e": 986,
"s": 623,
"text": "Can we distinguish with Machine Learning between an original and an artificially crafted signature? Indeed we can! We donβt necessarily even need one of those fancy neural network approaches, we can go totally classic with Hidden Markov Models (HMM). I will show in this post how we can incorporate HMMβs to classify whether a signature was original or imitated."
},
{
"code": null,
"e": 1124,
"s": 986,
"text": "This project is loosely inspired by the paper of Julian Fierrez et. al. published 2007, called: HMM-Based On-Line Signature Verification."
},
{
"code": null,
"e": 1548,
"s": 1124,
"text": "Even though Hidden Markov Models are not state-of-the-art, as the publishing date β2007β of the paper above already suggests, they are still a fundamental concept every Data Scientist should at least have heard about. Understanding the way an HMM works can be enlightening when you want to understand more recent technologies like Recurrent Neural Networks, because many techniques have evolved out of the HMMβs basic idea."
},
{
"code": null,
"e": 1986,
"s": 1548,
"text": "Hidden Markov Models can include time dependency in their computations. In Figure 1 below we can see, that from each state (Rainy, Sunny) we can transit into Rainy or Sunny back and forth and each of them has a certain probability to emit the three possible output states at every time step (Walk, Shop, Clean). The start probability always needs to be provided as well (60% for Rainy and 40% for Sunny) to start the computational chain."
},
{
"code": null,
"e": 2389,
"s": 1986,
"text": "In our case this means, that a signature is written from left to right with one letter after another. So the time dependency involves the speed, pressure and coordinates of the pen moving around to form a letter. All of this information can be taken into consideration to make an estimate of how likely it is going to be that a signature has been written by the original person or if it has been faked."
},
{
"code": null,
"e": 2447,
"s": 2389,
"text": "Figure 1 suggests that we need prior knowledge about the:"
},
{
"code": null,
"e": 2497,
"s": 2447,
"text": "start probability (Rainy 60% or Sunny 40%) Vector"
},
{
"code": null,
"e": 2547,
"s": 2497,
"text": "transition (From e.g. Rainy to Rainy 70%) Matrix,"
},
{
"code": null,
"e": 2618,
"s": 2547,
"text": "emission (From Rainy to either Walk 10%, Shop 40% or Clean 50%) Matrix"
},
{
"code": null,
"e": 2735,
"s": 2618,
"text": "Notice that start probability sums up to 100% and for the Matrices transition and emission each row sums up to 100%."
},
{
"code": null,
"e": 3090,
"s": 2735,
"text": "We need time-dependent data and compute features out of them, then we can fit the GMM to find the parameters for our HMM. When we have the parameters of the HMM, we can compute scores for the original and the imitated signatures. Based on the scores, we can make classification estimates of how likely it is going to be that the signature is true or not."
},
{
"code": null,
"e": 3260,
"s": 3090,
"text": "Why should we even use a Gaussian Mixture Model for training the HMM parameters in the first place? Well basically hmmlearn offers us three possibilities to choose from:"
},
{
"code": null,
"e": 3268,
"s": 3260,
"text": "GMM-HMM"
},
{
"code": null,
"e": 3281,
"s": 3268,
"text": "Gaussian HMM"
},
{
"code": null,
"e": 3297,
"s": 3281,
"text": "Multinomial HMM"
},
{
"code": null,
"e": 3534,
"s": 3297,
"text": "The GMM just works the best, because estimating the density of our signature is most likely not just a single Gaussian or single distribution, but the ground truth looks more like a valley, which can be way better approximated by a GMM."
},
{
"code": null,
"e": 3737,
"s": 3534,
"text": "We can exploit GMMβs with the so-called EM (Expectation-Maximization) algorithm let us compute those hidden parameters automatically. What is the EM algorithm expecting to compute the hidden parameters?"
},
{
"code": null,
"e": 3762,
"s": 3737,
"text": "The answer is: features."
},
{
"code": null,
"e": 3819,
"s": 3762,
"text": "The GMM uses the EM Algorithm to compute its parameters:"
},
{
"code": null,
"e": 3950,
"s": 3819,
"text": "E-step: Compute the component occupation probabilities P(M|x) using the current estimates of the GMM parameters (means, variances)"
},
{
"code": null,
"e": 4056,
"s": 3950,
"text": "M-step: Compute the GMM parameters using the current estimates of the component occupation probabilities."
},
{
"code": null,
"e": 4123,
"s": 4056,
"text": "Where we have to choose the Hyperparameters of the GMM, which are:"
},
{
"code": null,
"e": 4158,
"s": 4123,
"text": "M: The Gaussian Mixture components"
},
{
"code": null,
"e": 4191,
"s": 4158,
"text": "S: The HMM States (Sunny, Rainy)"
},
{
"code": null,
"e": 4333,
"s": 4191,
"text": "In reality, we canβt know what the best set of Hyperparameters are, but we could use for example the K-Fold Crossvalidation to find that out."
},
{
"code": null,
"e": 4377,
"s": 4333,
"text": "Wait what, Hyperparameters, HMM parameters?"
},
{
"code": null,
"e": 4580,
"s": 4377,
"text": "Ok, Hyperparameters are values that we as humans need to choose. This is also called the Model Selection problem. The Model parameters are parameters that the GMM with the EM algorithms computes for us."
},
{
"code": null,
"e": 4711,
"s": 4580,
"text": "For measuring those kinds of features (pressure, speed, etc.), we need a device like the one shown on the left-most picture below:"
},
{
"code": null,
"e": 5039,
"s": 4711,
"text": "I am using the mobisig dataset. It contains 83 entries in total (49 male, 34 female), which we later will split into the train-, test-, and imitationset. The signatures were collected by Margit Antal et. al. and was published 2017 in their research paper: Online Signature Verification on MOBISIG Finger-Drawn Signature Corpus."
},
{
"code": null,
"e": 5082,
"s": 5039,
"text": "This paper provides one example signature."
},
{
"code": null,
"e": 5333,
"s": 5082,
"text": "It can be seen that the forgery signature contains more densely connected pressure points. The paper explains how the forgery was created. You can read it if you want, but this post focuses on how we can detect this forgery, not how it was generated."
},
{
"code": null,
"e": 5455,
"s": 5333,
"text": "I am going to use the hmmlearn package for python, so I donβt have to reinvent the wheel for building HMMβs from scratch."
},
{
"code": null,
"e": 5593,
"s": 5455,
"text": "Letβs start by importing the default packages for this project. I set the random seed, so you will have exactly the same plots as I have."
},
{
"code": null,
"e": 5966,
"s": 5593,
"text": "Also, we want to make sure to load the dataset properly, as can be seen in the code snippet above. The data is stored in dictionaries, were each person has two entries (βoriginalβ and βimitatedβ) which are further split into multiple signatures each. Furthermore, all signatures have a few hundred or thousand rows with the timestamp id (which progresses in milliseconds)."
},
{
"code": null,
"e": 6269,
"s": 5966,
"text": "Looking back to Figure 1, the first step to proceed is the feature extraction. Fitting Gaussian, especially Mixture Gaussian is way more effective and efficient if the data points are zero centered and have a normalized standard deviation. From paper [1] we can obtain the following normalization step:"
},
{
"code": null,
"e": 6380,
"s": 6269,
"text": "Next, we extract the four features after the normalization step. The formulas (2. Step) are obtained from [3]:"
},
{
"code": null,
"e": 6717,
"s": 6380,
"text": "The normalization step 1 is shown in the function (lines: 1β2) of the code. This formula in Figure 3 just means to sum over all xβs and yβs and divide them by the number of occurrences N. So just taking the mean. Furthermore, epsilon (e = np.finfo) is added (lines: 2, 21, 22, 24, ... ) to be protected against a division by zero error."
},
{
"code": null,
"e": 7042,
"s": 6717,
"text": "The four features from step 2 are very straightforward computable. The dot over x and y indicate to use the normed x and y we just computed. Apart from that, theta can is calculated exactly like the formula suggests in line 24 of the code. The path velocity is calculated in line 27 the same way. It is just the square root!"
},
{
"code": null,
"e": 7279,
"s": 7042,
"text": "Special attention goes to the Log curvature radius, because if you look closely, you can see that the authors want theta also to be normalized. Therefore in line 30 where Ο (rho) is computed, we also call the norm function on ΞΈ (theta)."
},
{
"code": null,
"e": 7435,
"s": 7279,
"text": "The last feature I called alpha in the code, because it sounds nicer than just a. It is as straightforwardly calculated as the rest in line 33 of the code."
},
{
"code": null,
"e": 7585,
"s": 7435,
"text": "I appended all of the features to their according lists, because we need that in order to feed these features in the hidden Markov learning function."
},
{
"code": null,
"e": 8143,
"s": 7585,
"text": "So, we are done with the feature extraction step. Now letβs build the model.Oh no! We need to split the data into train-, test- and imitation datasets. From the mentioned entries I am using the first 25 people as training examples, this is the minimum amount to prevent overfitting, where one entry corresponds to multiple signatures by one person. So the trainset contains 25 different people with many according true and fake signatures. The testset contains another 20 different people and the validationset (X_val) set holds all the imitated signatures."
},
{
"code": null,
"e": 8196,
"s": 8143,
"text": "X_train: (3940, 8)X_test: (3140, 8)X_val: (10338, 8)"
},
{
"code": null,
"e": 8487,
"s": 8196,
"text": "Since I said that the row length of all of the signatures were different, I always needed to keep track of the current length and append it to the new data frame. That were quite a hustle to program properly. In line 51, I renamed the features to the names from the feature extraction step."
},
{
"code": null,
"e": 8598,
"s": 8487,
"text": "Important to note is that I am calling the feature extraction function in line 47β49, to compute the features."
},
{
"code": null,
"e": 8679,
"s": 8598,
"text": "To train the GMM HMM, we need to have a look at the documentation from hmmlearn."
},
{
"code": null,
"e": 8712,
"s": 8679,
"text": "We need two essential variables:"
},
{
"code": null,
"e": 8761,
"s": 8712,
"text": "transmat ( the transition matrix) (Rainy, Sunny)"
},
{
"code": null,
"e": 8871,
"s": 8761,
"text": "startprob (the initial probability matrix for the start)(60% 40% β according to the number of S (HMM States))"
},
{
"code": null,
"e": 9162,
"s": 8871,
"text": "The transition matrix will be parameterized such that it is diagonally filled with a 50% probability (0.5), except for the first and the last entry. This is suggested by hmmlearn in the documentation. The same goes for the startprob matrix, I chose the default initialization from hmmlearn."
},
{
"code": null,
"e": 9258,
"s": 9162,
"text": "The features variables X_train are now containing one timestamp and the seven features per row:"
},
{
"code": null,
"e": 9275,
"s": 9258,
"text": "X and Y location"
},
{
"code": null,
"e": 9288,
"s": 9275,
"text": "The pressure"
},
{
"code": null,
"e": 9316,
"s": 9288,
"text": "The four extracted features"
},
{
"code": null,
"e": 9722,
"s": 9316,
"text": "Now we can create the model in line 20 of the code below. The number of components and the number of mixtures play an essential role in how good the estimation of imitated signatures will be, but we canβt know what the best values will be as already said. For that reason, I tried different combinations against each other. So let us have a look at how these two hyperparameters behave against each other."
},
{
"code": null,
"e": 9918,
"s": 9722,
"text": "The score function in line 35, 39 and 43 evaluates the scores for the three different sets. Those scores are calculated by the objective function of the GMM, which is the negative log-likelihood."
},
{
"code": null,
"e": 10007,
"s": 9918,
"text": "Alright, letβs call the fit_hmm function with different values for components and GMMβs:"
},
{
"code": null,
"e": 10151,
"s": 10007,
"text": "We call it Success when we are having a set of imitated signatures with different or lower scores than the original (blue or green) signatures."
},
{
"code": null,
"e": 10497,
"s": 10151,
"text": "We can see that the number of HMM states have the highest influence on the scores. We want scores that separate the red dots (imitation) as far as possible from the original blue and green dots. Seven or fewer HMM states appear to separate the red dots pretty well from the rest and the GMM components have apparently a low impact on the output."
},
{
"code": null,
"e": 10563,
"s": 10497,
"text": "If we draw a linear classification line between the colored dots,"
},
{
"code": null,
"e": 10847,
"s": 10563,
"text": "we can see how well the HMM is able to detect if the signature is fake or not. We would for example set a threshold value at -2200 and then score a new signature. If the value of the score is less than -2200 we claim it to be fake, if it is bigger we say it is an original signature."
},
{
"code": null,
"e": 11177,
"s": 10847,
"text": "What we could do now is save up the scores and train for example a Logistic Regression to predict the probability (0β100%) based on the score on how likely it is that the signature is original or not. This Logistic Regression can be further extended with the accuracy score from sklearn, to estimate the uncertainty of the model."
},
{
"code": null,
"e": 11445,
"s": 11177,
"text": "Success! We can successfully distinguish between imitated and original signatures. Some state-of-the-art approaches to also map time constraints are Recurrent Neural Networks. But for now, we saw that this is also possible with very classical approaches like the HMM."
},
{
"code": null,
"e": 11600,
"s": 11445,
"text": "For more information, you can visit my website and add me in the social media I linked there. I would be happy if you give me a clap on this blog post :)."
},
{
"code": null,
"e": 12013,
"s": 11600,
"text": "[1] Julian Fierrez et. al., HMM-based on-line signature verification: Feature extraction and signature modeling (2007), Science Direct[2] Margit Antal, LaΜszloΜ Zsolt SzaboΜ and TuΜnde Tordai, Online Signature Verification on MOBISIG Finger-Drawn Signature Corpus (2017), Hindawi[3] Julian Fierrez et. al., An On-Line Signature Verification System Based on Fusion of Local and Global Information (2005), Springer"
}
] |
DynamoDB - Creating Items
|
Creating an item in DynamoDB consists primarily of item and attribute specification, and the option of specifying conditions. Each item exists as a set of attributes, with each attribute named and assigned a value of a certain type.
Value types include scalar, document, or set. Items carry a 400KB size limit, with the possibility of any amount of attributes capable of fitting within that limit. Name and value sizes (binary and UTF-8 lengths) determine item size. Using short attribute names aids in minimizing item size.
Note β You must specify all primary key attributes, with primary keys only requiring the partition key; and composite keys requiring both the partition and sort key.
Also, remember tables possess no predefined schema. You can store dramatically different datasets in one table.
Use the GUI console, Java, or another tool to perform this task.
Navigate to the console. In the navigation pane on the left side, select Tables. Choose the table name for use as the destination, and then select the Items tab as shown in the following screenshot.
Select Create Item. The Create Item screen provides an interface for entering the required attribute values. Any secondary indices must also be entered.
If you require more attributes, select the action menu on the left of the Message. Then select Append, and the desired data type.
After entering all essential information, select Save to add the item.
Using Java in item creation operations consists of creating a DynamoDB class instance, Table class instance, Item class instance, and specifying the primary key and attributes of the item you will create. Then add your new item with the putItem method.
DynamoDB dynamoDB = new DynamoDB (new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
Table table = dynamoDB.getTable("ProductList");
// Spawn a related items list
List<Number> RELItems = new ArrayList<Number>();
RELItems.add(123);
RELItems.add(456);
RELItems.add(789);
//Spawn a product picture map
Map<String, String> photos = new HashMap<String, String>();
photos.put("Anterior", "http://xyz.com/products/101_front.jpg");
photos.put("Posterior", "http://xyz.com/products/101_back.jpg");
photos.put("Lateral", "http://xyz.com/products/101_LFTside.jpg");
//Spawn a product review map
Map<String, List<String>> prodReviews = new HashMap<String, List<String>>();
List<String> fiveStarRVW = new ArrayList<String>();
fiveStarRVW.add("Shocking high performance.");
fiveStarRVW.add("Unparalleled in its market.");
prodReviews.put("5 Star", fiveStarRVW);
List<String> oneStarRVW = new ArrayList<String>();
oneStarRVW.add("The worst offering in its market.");
prodReviews.put("1 Star", oneStarRVW);
// Generate the item
Item item = new Item()
.withPrimaryKey("Id", 101)
.withString("Nomenclature", "PolyBlaster 101")
.withString("Description", "101 description")
.withString("Category", "Hybrid Power Polymer Cutter")
.withString("Make", "Brand β XYZ")
.withNumber("Price", 50000)
.withString("ProductCategory", "Laser Cutter")
.withBoolean("Availability", true)
.withNull("Qty")
.withList("ItemsRelated", RELItems)
.withMap("Images", photos)
.withMap("Reviews", prodReviews);
// Add item to the table
PutItemOutcome outcome = table.putItem(item);
You can also look at the following larger example.
Note β The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).
The following sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.
package com.amazonaws.codesamples.document;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
public class CreateItemOpSample {
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
new ProfileCredentialsProvider()));
static String tblName = "ProductList";
public static void main(String[] args) throws IOException {
createItems();
retrieveItem();
// Execute updates
updateMultipleAttributes();
updateAddNewAttribute();
updateExistingAttributeConditionally();
// Item deletion
deleteItem();
}
private static void createItems() {
Table table = dynamoDB.getTable(tblName);
try {
Item item = new Item()
.withPrimaryKey("ID", 303)
.withString("Nomenclature", "Polymer Blaster 4000")
.withStringSet( "Manufacturers",
new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
.withNumber("Price", 50000)
.withBoolean("InProduction", true)
.withString("Category", "Laser Cutter");
table.putItem(item);
item = new Item()
.withPrimaryKey("ID", 313)
.withString("Nomenclature", "Agitatatron 2000")
.withStringSet( "Manufacturers",
new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
.withNumber("Price", 40000)
.withBoolean("InProduction", true)
.withString("Category", "Agitator");
table.putItem(item);
} catch (Exception e) {
System.err.println("Cannot create items.");
System.err.println(e.getMessage());
}
}
}
16 Lectures
1.5 hours
Harshit Srivastava
49 Lectures
3.5 hours
Niyazi Erdogan
48 Lectures
3 hours
Niyazi Erdogan
13 Lectures
1 hours
Harshit Srivastava
45 Lectures
4 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2624,
"s": 2391,
"text": "Creating an item in DynamoDB consists primarily of item and attribute specification, and the option of specifying conditions. Each item exists as a set of attributes, with each attribute named and assigned a value of a certain type."
},
{
"code": null,
"e": 2916,
"s": 2624,
"text": "Value types include scalar, document, or set. Items carry a 400KB size limit, with the possibility of any amount of attributes capable of fitting within that limit. Name and value sizes (binary and UTF-8 lengths) determine item size. Using short attribute names aids in minimizing item size."
},
{
"code": null,
"e": 3082,
"s": 2916,
"text": "Note β You must specify all primary key attributes, with primary keys only requiring the partition key; and composite keys requiring both the partition and sort key."
},
{
"code": null,
"e": 3194,
"s": 3082,
"text": "Also, remember tables possess no predefined schema. You can store dramatically different datasets in one table."
},
{
"code": null,
"e": 3259,
"s": 3194,
"text": "Use the GUI console, Java, or another tool to perform this task."
},
{
"code": null,
"e": 3458,
"s": 3259,
"text": "Navigate to the console. In the navigation pane on the left side, select Tables. Choose the table name for use as the destination, and then select the Items tab as shown in the following screenshot."
},
{
"code": null,
"e": 3611,
"s": 3458,
"text": "Select Create Item. The Create Item screen provides an interface for entering the required attribute values. Any secondary indices must also be entered."
},
{
"code": null,
"e": 3741,
"s": 3611,
"text": "If you require more attributes, select the action menu on the left of the Message. Then select Append, and the desired data type."
},
{
"code": null,
"e": 3812,
"s": 3741,
"text": "After entering all essential information, select Save to add the item."
},
{
"code": null,
"e": 4065,
"s": 3812,
"text": "Using Java in item creation operations consists of creating a DynamoDB class instance, Table class instance, Item class instance, and specifying the primary key and attributes of the item you will create. Then add your new item with the putItem method."
},
{
"code": null,
"e": 5706,
"s": 4065,
"text": "DynamoDB dynamoDB = new DynamoDB (new AmazonDynamoDBClient(\n new ProfileCredentialsProvider()));\nTable table = dynamoDB.getTable(\"ProductList\");\n \n// Spawn a related items list \nList<Number> RELItems = new ArrayList<Number>(); \nRELItems.add(123); \nRELItems.add(456); \nRELItems.add(789); \n \n//Spawn a product picture map \nMap<String, String> photos = new HashMap<String, String>(); \nphotos.put(\"Anterior\", \"http://xyz.com/products/101_front.jpg\"); \nphotos.put(\"Posterior\", \"http://xyz.com/products/101_back.jpg\"); \nphotos.put(\"Lateral\", \"http://xyz.com/products/101_LFTside.jpg\"); \n\n//Spawn a product review map \nMap<String, List<String>> prodReviews = new HashMap<String, List<String>>(); \nList<String> fiveStarRVW = new ArrayList<String>(); \nfiveStarRVW.add(\"Shocking high performance.\"); \nfiveStarRVW.add(\"Unparalleled in its market.\"); \nprodReviews.put(\"5 Star\", fiveStarRVW); \nList<String> oneStarRVW = new ArrayList<String>(); \noneStarRVW.add(\"The worst offering in its market.\"); \nprodReviews.put(\"1 Star\", oneStarRVW); \n\n// Generate the item \nItem item = new Item()\n .withPrimaryKey(\"Id\", 101) \n .withString(\"Nomenclature\", \"PolyBlaster 101\") \n .withString(\"Description\", \"101 description\") \n .withString(\"Category\", \"Hybrid Power Polymer Cutter\") \n .withString(\"Make\", \"Brand β XYZ\") \n .withNumber(\"Price\", 50000) \n .withString(\"ProductCategory\", \"Laser Cutter\") \n .withBoolean(\"Availability\", true) \n .withNull(\"Qty\") \n .withList(\"ItemsRelated\", RELItems) \n .withMap(\"Images\", photos) \n .withMap(\"Reviews\", prodReviews);\n\n// Add item to the table \nPutItemOutcome outcome = table.putItem(item);"
},
{
"code": null,
"e": 5757,
"s": 5706,
"text": "You can also look at the following larger example."
},
{
"code": null,
"e": 5992,
"s": 5757,
"text": "Note β The following sample may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources)."
},
{
"code": null,
"e": 6117,
"s": 5992,
"text": "The following sample also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project."
},
{
"code": null,
"e": 8713,
"s": 6117,
"text": "package com.amazonaws.codesamples.document;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\n\nimport com.amazonaws.auth.profile.ProfileCredentialsProvider;\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\nimport com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.Table;\n\nimport com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;\nimport com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;\nimport com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;\nimport com.amazonaws.services.dynamodbv2.document.utils.NameMap;\nimport com.amazonaws.services.dynamodbv2.document.utils.ValueMap;\nimport com.amazonaws.services.dynamodbv2.model.ReturnValue;\n\npublic class CreateItemOpSample { \n static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient ( \n new ProfileCredentialsProvider())); \n static String tblName = \"ProductList\"; \n \n public static void main(String[] args) throws IOException { \n createItems(); \n retrieveItem(); \n \n // Execute updates \n updateMultipleAttributes(); \n updateAddNewAttribute(); \n updateExistingAttributeConditionally(); \n \n // Item deletion \n deleteItem(); \n }\n private static void createItems() { \n Table table = dynamoDB.getTable(tblName); \n try { \n Item item = new Item() \n .withPrimaryKey(\"ID\", 303)\n .withString(\"Nomenclature\", \"Polymer Blaster 4000\") \n .withStringSet( \"Manufacturers\", \n new HashSet<String>(Arrays.asList(\"XYZ Inc.\", \"LMNOP Inc.\"))) \n .withNumber(\"Price\", 50000) \n .withBoolean(\"InProduction\", true) \n .withString(\"Category\", \"Laser Cutter\"); \n \n table.putItem(item); \n item = new Item() \n .withPrimaryKey(\"ID\", 313) \n .withString(\"Nomenclature\", \"Agitatatron 2000\") \n .withStringSet( \"Manufacturers\", \n new HashSet<String>(Arrays.asList(\"XYZ Inc,\", \"CDE Inc.\"))) \n .withNumber(\"Price\", 40000) \n .withBoolean(\"InProduction\", true) \n .withString(\"Category\", \"Agitator\"); \n \n table.putItem(item); \n } catch (Exception e) { \n System.err.println(\"Cannot create items.\"); \n System.err.println(e.getMessage()); \n } \n } \n}"
},
{
"code": null,
"e": 8748,
"s": 8713,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8768,
"s": 8748,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 8803,
"s": 8768,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8819,
"s": 8803,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 8852,
"s": 8819,
"text": "\n 48 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8868,
"s": 8852,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 8901,
"s": 8868,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8921,
"s": 8901,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 8954,
"s": 8921,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8994,
"s": 8954,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 9001,
"s": 8994,
"text": " Print"
},
{
"code": null,
"e": 9012,
"s": 9001,
"text": " Add Notes"
}
] |
Introduction to One-Way ANOVA: A Test to Compare the Means between More than Two Groups | by Khuyen Tran | Towards Data Science
|
A t-test is useful to find out whether there is a significant difference between two groups. However, a t-test cannot be used to compare between three or more independent groups.
For example, if you are a product developer, you might want to know whether the change in the percentage of cotton used in the synthetic fiber will result in an increase in the tensile strength of the fiber.
To find out, you can conduct a completely randomized experiment with five levels of cotton content and replicate the experiment five times representing five trials. The data might look like the following table:
By looking at the table alone, it is difficult to know whether there are statistically significant differences between the means of these 5 levels of cotton content. Since there are more than 2 groups being compared, a t-test cannot be used in this case.
Is there a way that you can determine whether any of these means are statistically different from each other and produces meaningful outputs like below?
Pairs of levels of cotton content that are not statistically different:
(15, 20)
(15, 25)
(15, 30)
(20, 30)
(25, 35)
(30, 35)
Pairs of levels of cotton content that are statistically different:
(15, 35)
(20, 25)
(20, 35)
(25, 30)
That is when one-way ANOVA comes in handy.
The one-way ANOVA compares the means of the groups you are interested in and determines whether any of those means are statistically different from each other. A one-way ANOVA has one independent variable while a two-way ANOVA has two independent variables.
Since there is only one independent variable in our problem, which is tensile strength, we will use a one-way ANOVA.
To perform a one-way ANOVA in Python, we will install and use statsmodels package:
pip install statsmodels
We will create data that is shown in the introduction.
Nice! The data is set up. Now we are ready to use the one-way ANOVA test.
We start with testing whether the means of some levels of cotton content are statistically different.
Null hypothesis: There is no difference in means
Alternate hypothesis: The means are not all equal
Since anova-lm requires one or more fitted linear models, we start with fitting the Ordinary Least Squares (OLS) model to our data then use it as an argument foranova_lm .
The F-statistic of the model is 14.962217. The p-value of the model is 8e-06.
Since the p-value is less than the significance level of 0.05, there is enough evidence to claim that some of the means of different levels of cotton content are statistically different.
Even though we know some of the means are statistically different overall, which specific two levels of cotton content are different? That is when Tukeyβs HSD (Honest Significant Difference) comes in handy.
Tukeyβs HSD finds out which specific groupsβ means are different. The test compares all possible pairs of means.
Letβs use MultiComparision and itsturkeyhsd() method to test for multiple comparisons.
Explanation of the table above:
group1 is compared to group2
meandiff : the mean difference between group1 and group2
p-adj : how likely group1 and group2 to have the same means
lower and upper : lower and upper bound of the confidence interval.
reject : If it is True , the null hypothesis is rejected. There is enough evidence to claim that the means of the two levels of cotton being compared are significantly different.
Pairs of levels of cotton content that are statistically different:
(15, 35)
(20, 25)
(20, 35)
(25, 30)
To understand the results better, letβs look at the plots that visualize significant differences with one confidence interval per group.
The plot above compares the mean of group 15 (fiber with 15% cotton) colored in blue and the means of other groups.
Since group 35βs mean is not statistically different from group 15βs mean, group 35 is colored gray.
Since the mean of group 20, 25, and 30 are significantly different from the mean of group 15, they are colored red.
Select other options in the dropdown bar for other comparisons.
ANOVA assumes that each sample was drawn from a normally distributed population. To use ANOVA at all, we need to make sure that this assumption is met.
To test for normality, we will create a Q-Q plot of residuals. The Q-Q plot plots quantiles of the data versus quantiles of a normal distribution.
Since the data points fall along a straight diagonal line in a Q-Q plot, the dataset is likely to follow a normal distribution. Thus, the data satisfies ANOVAβs assumption of normality.
Congratulations! You have just learned how to use one-way ANOVA to compare the means of three or more independent groups. No matter how good your data is, if you donβt have a good testing technique, you wonβt be able to extract meaningful insights from your data.
With ANOVA, you will be able to determine if differences in mean values between three or more groups are by chance or if they are indeed significantly different. Eventually, it will help you decide if it is beneficial to choose one group over others.
The source code of this article could be found here:
github.com
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
https://towardsdatascience.com/top-6-python-libraries-for-visualization-which-one-to-use-fe43381cd658
towardsdatascience.com
βOne-Way ANOVA.β One-Way ANOVA β An Introduction to When You Should Run This Test and the Test Hypothesis | Laerd Statistics, statistics.laerd.com/statistical-guides/one-way-anova-statistical-guide.php.
|
[
{
"code": null,
"e": 351,
"s": 172,
"text": "A t-test is useful to find out whether there is a significant difference between two groups. However, a t-test cannot be used to compare between three or more independent groups."
},
{
"code": null,
"e": 559,
"s": 351,
"text": "For example, if you are a product developer, you might want to know whether the change in the percentage of cotton used in the synthetic fiber will result in an increase in the tensile strength of the fiber."
},
{
"code": null,
"e": 770,
"s": 559,
"text": "To find out, you can conduct a completely randomized experiment with five levels of cotton content and replicate the experiment five times representing five trials. The data might look like the following table:"
},
{
"code": null,
"e": 1025,
"s": 770,
"text": "By looking at the table alone, it is difficult to know whether there are statistically significant differences between the means of these 5 levels of cotton content. Since there are more than 2 groups being compared, a t-test cannot be used in this case."
},
{
"code": null,
"e": 1178,
"s": 1025,
"text": "Is there a way that you can determine whether any of these means are statistically different from each other and produces meaningful outputs like below?"
},
{
"code": null,
"e": 1250,
"s": 1178,
"text": "Pairs of levels of cotton content that are not statistically different:"
},
{
"code": null,
"e": 1259,
"s": 1250,
"text": "(15, 20)"
},
{
"code": null,
"e": 1268,
"s": 1259,
"text": "(15, 25)"
},
{
"code": null,
"e": 1277,
"s": 1268,
"text": "(15, 30)"
},
{
"code": null,
"e": 1286,
"s": 1277,
"text": "(20, 30)"
},
{
"code": null,
"e": 1295,
"s": 1286,
"text": "(25, 35)"
},
{
"code": null,
"e": 1304,
"s": 1295,
"text": "(30, 35)"
},
{
"code": null,
"e": 1372,
"s": 1304,
"text": "Pairs of levels of cotton content that are statistically different:"
},
{
"code": null,
"e": 1381,
"s": 1372,
"text": "(15, 35)"
},
{
"code": null,
"e": 1390,
"s": 1381,
"text": "(20, 25)"
},
{
"code": null,
"e": 1399,
"s": 1390,
"text": "(20, 35)"
},
{
"code": null,
"e": 1408,
"s": 1399,
"text": "(25, 30)"
},
{
"code": null,
"e": 1451,
"s": 1408,
"text": "That is when one-way ANOVA comes in handy."
},
{
"code": null,
"e": 1709,
"s": 1451,
"text": "The one-way ANOVA compares the means of the groups you are interested in and determines whether any of those means are statistically different from each other. A one-way ANOVA has one independent variable while a two-way ANOVA has two independent variables."
},
{
"code": null,
"e": 1826,
"s": 1709,
"text": "Since there is only one independent variable in our problem, which is tensile strength, we will use a one-way ANOVA."
},
{
"code": null,
"e": 1909,
"s": 1826,
"text": "To perform a one-way ANOVA in Python, we will install and use statsmodels package:"
},
{
"code": null,
"e": 1933,
"s": 1909,
"text": "pip install statsmodels"
},
{
"code": null,
"e": 1988,
"s": 1933,
"text": "We will create data that is shown in the introduction."
},
{
"code": null,
"e": 2062,
"s": 1988,
"text": "Nice! The data is set up. Now we are ready to use the one-way ANOVA test."
},
{
"code": null,
"e": 2164,
"s": 2062,
"text": "We start with testing whether the means of some levels of cotton content are statistically different."
},
{
"code": null,
"e": 2213,
"s": 2164,
"text": "Null hypothesis: There is no difference in means"
},
{
"code": null,
"e": 2263,
"s": 2213,
"text": "Alternate hypothesis: The means are not all equal"
},
{
"code": null,
"e": 2435,
"s": 2263,
"text": "Since anova-lm requires one or more fitted linear models, we start with fitting the Ordinary Least Squares (OLS) model to our data then use it as an argument foranova_lm ."
},
{
"code": null,
"e": 2513,
"s": 2435,
"text": "The F-statistic of the model is 14.962217. The p-value of the model is 8e-06."
},
{
"code": null,
"e": 2700,
"s": 2513,
"text": "Since the p-value is less than the significance level of 0.05, there is enough evidence to claim that some of the means of different levels of cotton content are statistically different."
},
{
"code": null,
"e": 2907,
"s": 2700,
"text": "Even though we know some of the means are statistically different overall, which specific two levels of cotton content are different? That is when Tukeyβs HSD (Honest Significant Difference) comes in handy."
},
{
"code": null,
"e": 3020,
"s": 2907,
"text": "Tukeyβs HSD finds out which specific groupsβ means are different. The test compares all possible pairs of means."
},
{
"code": null,
"e": 3107,
"s": 3020,
"text": "Letβs use MultiComparision and itsturkeyhsd() method to test for multiple comparisons."
},
{
"code": null,
"e": 3139,
"s": 3107,
"text": "Explanation of the table above:"
},
{
"code": null,
"e": 3168,
"s": 3139,
"text": "group1 is compared to group2"
},
{
"code": null,
"e": 3225,
"s": 3168,
"text": "meandiff : the mean difference between group1 and group2"
},
{
"code": null,
"e": 3285,
"s": 3225,
"text": "p-adj : how likely group1 and group2 to have the same means"
},
{
"code": null,
"e": 3353,
"s": 3285,
"text": "lower and upper : lower and upper bound of the confidence interval."
},
{
"code": null,
"e": 3532,
"s": 3353,
"text": "reject : If it is True , the null hypothesis is rejected. There is enough evidence to claim that the means of the two levels of cotton being compared are significantly different."
},
{
"code": null,
"e": 3600,
"s": 3532,
"text": "Pairs of levels of cotton content that are statistically different:"
},
{
"code": null,
"e": 3609,
"s": 3600,
"text": "(15, 35)"
},
{
"code": null,
"e": 3618,
"s": 3609,
"text": "(20, 25)"
},
{
"code": null,
"e": 3627,
"s": 3618,
"text": "(20, 35)"
},
{
"code": null,
"e": 3636,
"s": 3627,
"text": "(25, 30)"
},
{
"code": null,
"e": 3773,
"s": 3636,
"text": "To understand the results better, letβs look at the plots that visualize significant differences with one confidence interval per group."
},
{
"code": null,
"e": 3889,
"s": 3773,
"text": "The plot above compares the mean of group 15 (fiber with 15% cotton) colored in blue and the means of other groups."
},
{
"code": null,
"e": 3990,
"s": 3889,
"text": "Since group 35βs mean is not statistically different from group 15βs mean, group 35 is colored gray."
},
{
"code": null,
"e": 4106,
"s": 3990,
"text": "Since the mean of group 20, 25, and 30 are significantly different from the mean of group 15, they are colored red."
},
{
"code": null,
"e": 4170,
"s": 4106,
"text": "Select other options in the dropdown bar for other comparisons."
},
{
"code": null,
"e": 4322,
"s": 4170,
"text": "ANOVA assumes that each sample was drawn from a normally distributed population. To use ANOVA at all, we need to make sure that this assumption is met."
},
{
"code": null,
"e": 4469,
"s": 4322,
"text": "To test for normality, we will create a Q-Q plot of residuals. The Q-Q plot plots quantiles of the data versus quantiles of a normal distribution."
},
{
"code": null,
"e": 4655,
"s": 4469,
"text": "Since the data points fall along a straight diagonal line in a Q-Q plot, the dataset is likely to follow a normal distribution. Thus, the data satisfies ANOVAβs assumption of normality."
},
{
"code": null,
"e": 4919,
"s": 4655,
"text": "Congratulations! You have just learned how to use one-way ANOVA to compare the means of three or more independent groups. No matter how good your data is, if you donβt have a good testing technique, you wonβt be able to extract meaningful insights from your data."
},
{
"code": null,
"e": 5170,
"s": 4919,
"text": "With ANOVA, you will be able to determine if differences in mean values between three or more groups are by chance or if they are indeed significantly different. Eventually, it will help you decide if it is beneficial to choose one group over others."
},
{
"code": null,
"e": 5223,
"s": 5170,
"text": "The source code of this article could be found here:"
},
{
"code": null,
"e": 5234,
"s": 5223,
"text": "github.com"
},
{
"code": null,
"e": 5394,
"s": 5234,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
},
{
"code": null,
"e": 5570,
"s": 5394,
"text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:"
},
{
"code": null,
"e": 5593,
"s": 5570,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5616,
"s": 5593,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5718,
"s": 5616,
"text": "https://towardsdatascience.com/top-6-python-libraries-for-visualization-which-one-to-use-fe43381cd658"
},
{
"code": null,
"e": 5741,
"s": 5718,
"text": "towardsdatascience.com"
}
] |
Format specifiers in C - GeeksforGeeks
|
28 Aug, 2021
The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.The format specifier in printf() and scanf() are mostly the same but there is some difference which we will see.
This function prints the character on standard output and returns the number of character printed the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.). Between both, there can be elements governing the printing format. Below is its description
A minus(-) sign tells left alignment.A number after % specifies the minimum field width to be printed if the characters are less than the size of width the remaining space is filled with space and if it is greater than it printed as it is without truncation.A period( . ) symbol separate field width with the precision.
A minus(-) sign tells left alignment.
A number after % specifies the minimum field width to be printed if the characters are less than the size of width the remaining space is filled with space and if it is greater than it printed as it is without truncation.
A period( . ) symbol separate field width with the precision.
Precision tells the minimum number of digits in integer, maximum number of characters in string and number of digits after decimal part in floating value. Lets see these.. Character format specifier : %c
C
#include <stdio.h>int main(){ char ch = 'A'; printf("%c\n", ch); return 0;}
A
For Signed Integer format specifier : %d, %i
C
#include <stdio.h>int main(){ int x = 45, y = 90; printf("%d\n", x); printf("%i\n", x); return 0;}
45
45
Unsigned Integer Format Specifier: %u:
C
#include <stdio.h>int main(){ // The -10 value is converted into it's positive // equivalent by %u printf("%u\n", -10); printf("%u\n", 10); return 0;}
Output: 4294967286
10
Floating-point format specifier : %f, %e or %E
C
#include <stdio.h>int main(){ float a = 12.67; printf("%f\n", a); printf("%e\n", a); return 0;}
12.670000
1.267000e+01
Unsigned Octal number for integer : %o
C
#include <stdio.h>int main(){ int a = 67; printf("%o\n", a); return 0;}
103
Unsigned Hexadecimal for integer: %x, %X
C
#include <stdio.h>int main(){ int a = 15; printf("%x\n", a); return 0;}
f
String printing: %s
C
#include <stdio.h>int main(){ char a[] = "geeksforgeeks"; printf("%s\n", a); return 0;}
geeksforgeeks
Address Printing: %p
When our intention is to print the memory address of a variable/pointer β%dβ will not work because β%dβ will try to format an address into a number and values like 0xbfdd812 is clearly not a number, ie we MUST use %p.
C
#include <stdio.h>int main(){ int a = 10; printf("The Memory Address of a: %p\n",(void*)&a); return 0;}
Output: The Memory Address of a: 0x7ffc85861624
C
#include <stdio.h>int main(){ char str[] = "geeksforgeeks"; printf("%20s\n", str); printf("%-20s\n", str); printf("%20.5s\n", str); printf("%-20.5s\n", str); return 0;}
geeksforgeeks
geeksforgeeks
geeks
geeks
This function take input using standard input (keyboard) and store it in variable accordingly. It returns the number of items successfully read. Formal parameter arg1, agr2, .. must be a pointerdecimal integer : %d
C
#include <stdio.h>int main(){ int a = 0; scanf("%d", &a); // input is 45 printf("%d\n", a); return 0;}
Integer may be octal or in hexadecimal : %i
C
#include <stdio.h>int main(){ int a = 0; scanf("%i", &a); // input is 017 (octal of 15 ) printf("%d\n", a); scanf("%i", &a); // input is 0xf (hexadecimal of 15 ) printf("%d\n", a); return 0;}
Double floating-point number : %lf
C
#include <stdio.h>int main(){ double a = 0.0; scanf("%lf", &a); // input is 45.65 printf("%lf\n", a); return 0;}
45.650000
String input : %s
C
#include <stdio.h>int main(){ char str[20]; scanf("%s", str); // input is geeksforgeeks printf("%s\n", str); return 0;}
P@
Character input : %c
C
#include <stdio.h>int main(){ char ch; scanf("%c", &ch); // input is A printf("%c\n", ch); return 0;}
Many other format specifiers are also there 1.%u for an unsigned integer. 2.%lld for long long int. 3.%o octal integer without leading zero 4.%x hexadecimal integer without 0x before the number.
mandarautade
Code_Mech
DMichaelPaxton
nidhi_biet
arun singh
txgb942kl8v0xd0jq7yl807ivw12kt3rh4jlkqez
c-input-output
cpp-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
|
[
{
"code": null,
"e": 24029,
"s": 24001,
"text": "\n28 Aug, 2021"
},
{
"code": null,
"e": 24361,
"s": 24029,
"text": "The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.The format specifier in printf() and scanf() are mostly the same but there is some difference which we will see. "
},
{
"code": null,
"e": 24651,
"s": 24361,
"text": "This function prints the character on standard output and returns the number of character printed the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.). Between both, there can be elements governing the printing format. Below is its description "
},
{
"code": null,
"e": 24971,
"s": 24651,
"text": "A minus(-) sign tells left alignment.A number after % specifies the minimum field width to be printed if the characters are less than the size of width the remaining space is filled with space and if it is greater than it printed as it is without truncation.A period( . ) symbol separate field width with the precision."
},
{
"code": null,
"e": 25009,
"s": 24971,
"text": "A minus(-) sign tells left alignment."
},
{
"code": null,
"e": 25231,
"s": 25009,
"text": "A number after % specifies the minimum field width to be printed if the characters are less than the size of width the remaining space is filled with space and if it is greater than it printed as it is without truncation."
},
{
"code": null,
"e": 25293,
"s": 25231,
"text": "A period( . ) symbol separate field width with the precision."
},
{
"code": null,
"e": 25498,
"s": 25293,
"text": "Precision tells the minimum number of digits in integer, maximum number of characters in string and number of digits after decimal part in floating value. Lets see these.. Character format specifier : %c "
},
{
"code": null,
"e": 25500,
"s": 25498,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ char ch = 'A'; printf(\"%c\\n\", ch); return 0;}",
"e": 25585,
"s": 25500,
"text": null
},
{
"code": null,
"e": 25587,
"s": 25585,
"text": "A"
},
{
"code": null,
"e": 25635,
"s": 25589,
"text": "For Signed Integer format specifier : %d, %i "
},
{
"code": null,
"e": 25637,
"s": 25635,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int x = 45, y = 90; printf(\"%d\\n\", x); printf(\"%i\\n\", x); return 0;}",
"e": 25748,
"s": 25637,
"text": null
},
{
"code": null,
"e": 25754,
"s": 25748,
"text": "45\n45"
},
{
"code": null,
"e": 25795,
"s": 25756,
"text": "Unsigned Integer Format Specifier: %u:"
},
{
"code": null,
"e": 25797,
"s": 25795,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ // The -10 value is converted into it's positive // equivalent by %u printf(\"%u\\n\", -10); printf(\"%u\\n\", 10); return 0;}",
"e": 25963,
"s": 25797,
"text": null
},
{
"code": null,
"e": 25993,
"s": 25963,
"text": "Output: 4294967286\n 10"
},
{
"code": null,
"e": 26041,
"s": 25993,
"text": "Floating-point format specifier : %f, %e or %E "
},
{
"code": null,
"e": 26043,
"s": 26041,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ float a = 12.67; printf(\"%f\\n\", a); printf(\"%e\\n\", a); return 0;}",
"e": 26151,
"s": 26043,
"text": null
},
{
"code": null,
"e": 26174,
"s": 26151,
"text": "12.670000\n1.267000e+01"
},
{
"code": null,
"e": 26216,
"s": 26176,
"text": "Unsigned Octal number for integer : %o "
},
{
"code": null,
"e": 26218,
"s": 26216,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int a = 67; printf(\"%o\\n\", a); return 0;}",
"e": 26299,
"s": 26218,
"text": null
},
{
"code": null,
"e": 26303,
"s": 26299,
"text": "103"
},
{
"code": null,
"e": 26347,
"s": 26305,
"text": "Unsigned Hexadecimal for integer: %x, %X "
},
{
"code": null,
"e": 26349,
"s": 26347,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int a = 15; printf(\"%x\\n\", a); return 0;}",
"e": 26430,
"s": 26349,
"text": null
},
{
"code": null,
"e": 26432,
"s": 26430,
"text": "f"
},
{
"code": null,
"e": 26455,
"s": 26434,
"text": "String printing: %s "
},
{
"code": null,
"e": 26457,
"s": 26455,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ char a[] = \"geeksforgeeks\"; printf(\"%s\\n\", a); return 0;}",
"e": 26554,
"s": 26457,
"text": null
},
{
"code": null,
"e": 26568,
"s": 26554,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 26591,
"s": 26570,
"text": "Address Printing: %p"
},
{
"code": null,
"e": 26809,
"s": 26591,
"text": "When our intention is to print the memory address of a variable/pointer β%dβ will not work because β%dβ will try to format an address into a number and values like 0xbfdd812 is clearly not a number, ie we MUST use %p."
},
{
"code": null,
"e": 26811,
"s": 26809,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int a = 10; printf(\"The Memory Address of a: %p\\n\",(void*)&a); return 0;}",
"e": 26924,
"s": 26811,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26924,
"text": "Output: The Memory Address of a: 0x7ffc85861624"
},
{
"code": null,
"e": 26974,
"s": 26972,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ char str[] = \"geeksforgeeks\"; printf(\"%20s\\n\", str); printf(\"%-20s\\n\", str); printf(\"%20.5s\\n\", str); printf(\"%-20.5s\\n\", str); return 0;}",
"e": 27161,
"s": 26974,
"text": null
},
{
"code": null,
"e": 27230,
"s": 27161,
"text": " geeksforgeeks\ngeeksforgeeks \n geeks\ngeeks"
},
{
"code": null,
"e": 27448,
"s": 27232,
"text": "This function take input using standard input (keyboard) and store it in variable accordingly. It returns the number of items successfully read. Formal parameter arg1, agr2, .. must be a pointerdecimal integer : %d "
},
{
"code": null,
"e": 27450,
"s": 27448,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int a = 0; scanf(\"%d\", &a); // input is 45 printf(\"%d\\n\", a); return 0;}",
"e": 27565,
"s": 27450,
"text": null
},
{
"code": null,
"e": 27610,
"s": 27565,
"text": "Integer may be octal or in hexadecimal : %i "
},
{
"code": null,
"e": 27612,
"s": 27610,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ int a = 0; scanf(\"%i\", &a); // input is 017 (octal of 15 ) printf(\"%d\\n\", a); scanf(\"%i\", &a); // input is 0xf (hexadecimal of 15 ) printf(\"%d\\n\", a); return 0;}",
"e": 27822,
"s": 27612,
"text": null
},
{
"code": null,
"e": 27858,
"s": 27822,
"text": "Double floating-point number : %lf "
},
{
"code": null,
"e": 27860,
"s": 27858,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ double a = 0.0; scanf(\"%lf\", &a); // input is 45.65 printf(\"%lf\\n\", a); return 0;}",
"e": 27985,
"s": 27860,
"text": null
},
{
"code": null,
"e": 27995,
"s": 27985,
"text": "45.650000"
},
{
"code": null,
"e": 28016,
"s": 27997,
"text": "String input : %s "
},
{
"code": null,
"e": 28018,
"s": 28016,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ char str[20]; scanf(\"%s\", str); // input is geeksforgeeks printf(\"%s\\n\", str); return 0;}",
"e": 28150,
"s": 28018,
"text": null
},
{
"code": null,
"e": 28153,
"s": 28150,
"text": "P@"
},
{
"code": null,
"e": 28177,
"s": 28155,
"text": "Character input : %c "
},
{
"code": null,
"e": 28179,
"s": 28177,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ char ch; scanf(\"%c\", &ch); // input is A printf(\"%c\\n\", ch); return 0;}",
"e": 28293,
"s": 28179,
"text": null
},
{
"code": null,
"e": 28489,
"s": 28293,
"text": "Many other format specifiers are also there 1.%u for an unsigned integer. 2.%lld for long long int. 3.%o octal integer without leading zero 4.%x hexadecimal integer without 0x before the number. "
},
{
"code": null,
"e": 28502,
"s": 28489,
"text": "mandarautade"
},
{
"code": null,
"e": 28512,
"s": 28502,
"text": "Code_Mech"
},
{
"code": null,
"e": 28527,
"s": 28512,
"text": "DMichaelPaxton"
},
{
"code": null,
"e": 28538,
"s": 28527,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28549,
"s": 28538,
"text": "arun singh"
},
{
"code": null,
"e": 28590,
"s": 28549,
"text": "txgb942kl8v0xd0jq7yl807ivw12kt3rh4jlkqez"
},
{
"code": null,
"e": 28605,
"s": 28590,
"text": "c-input-output"
},
{
"code": null,
"e": 28622,
"s": 28605,
"text": "cpp-input-output"
},
{
"code": null,
"e": 28633,
"s": 28622,
"text": "C Language"
},
{
"code": null,
"e": 28731,
"s": 28633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28740,
"s": 28731,
"text": "Comments"
},
{
"code": null,
"e": 28753,
"s": 28740,
"text": "Old Comments"
},
{
"code": null,
"e": 28788,
"s": 28753,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28816,
"s": 28788,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28862,
"s": 28816,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28874,
"s": 28862,
"text": "fork() in C"
},
{
"code": null,
"e": 28914,
"s": 28874,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 28946,
"s": 28914,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 28963,
"s": 28946,
"text": "Substring in C++"
},
{
"code": null,
"e": 28985,
"s": 28963,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 29032,
"s": 28985,
"text": "Different methods to reverse a string in C/C++"
}
] |
Framework7 - Refresh
|
It is a special component used to refresh (reload) the page contents by pulling it.
The following code shows how to refresh the page content β
<div class = "page">
<!-- Page content should have additional "pull-to-refresh-content" class -->
<div class = "page-content pull-to-refresh-content" data-ptr-distance = "55">
<!-- Default pull to refresh layer-->
<div class = "pull-to-refresh-layer">
<div class = "preloader"></div>
<div class = "pull-to-refresh-arrow"></div>
</div>
<!-- usual content below -->
<div class = "list-block">
...
</div>
</div>
The following classes are used in refresh β
page-content β It has an additional pull-to-refresh-content class and its required to enable pull to refresh.
page-content β It has an additional pull-to-refresh-content class and its required to enable pull to refresh.
pull-to-refresh-layer β It is a hidden layer, which is used to pull to refresh visual element and it is just a preloader and an arrow.
pull-to-refresh-layer β It is a hidden layer, which is used to pull to refresh visual element and it is just a preloader and an arrow.
data-ptr-distance = "55" β This is additional attribute that allows you to set custom 'pull to refresh' trigger distance and its default value is 44px.
data-ptr-distance = "55" β This is additional attribute that allows you to set custom 'pull to refresh' trigger distance and its default value is 44px.
In βPull to Refreshβ there are some JavaScript events, which are given in the following table β
pullstart
It will be triggered whenever you start pulling to refresh content.
Pull To Refresh content.
<div class = "pull-to-refresh-content">
pullmove
It is triggered when you are pulling to refresh content.
Pull To Refresh content.
<div class="pull-to-refresh-content">
pullend
It will be triggered whenever you release pull to refresh content.
Pull To Refresh content.
<div class="pull-to-refresh-content">
refresh
This event will be triggered when the pull to refresh enters in the "refreshing" state.
Pull To Refresh content.
<div class="pull-to-refresh-content">
refreshdone
It will be triggered after it is refreshed and it goes back to the initial state. This will be done after calling pullToRefreshDone method.
Pull To Refresh content.
<div class="pull-to-refresh-content">
There are App's methods that can be used with Pull to Refresh.
myApp.pullToRefreshDone(ptrContent)
It is used to reset pull-to-refresh content.
myApp.pullToRefreshTrigger(ptrContent)
It is used to trigger to refresh on specified pull to refresh content.
myApp.destroyPullToRefresh(ptrContent)
It is used to destroy/disable pull to refresh on specified pull to refresh content.
myApp.initPullToRefresh(ptrContent)
It is used to initialize/enable pull to refresh content.
Where ptrContent is used to HTMLElement or string to pull-to-refresh-content to reset/trigger or disable/enable.
The following example demonstrates the use of refresh component that initiates the refreshing of a page contents β
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>Pull To Refresh</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.colors.min.css">
</head>
<div class="views">
<div class="view view-main">
<div class="pages">
<div data-page="home" class="page navbar-fixed">
<div class="navbar">
<div class="navbar-inner">
<div class="left"> </div>
<div class="center">Pull To Refresh</div>
<div class="right"> </div>
</div>
</div>
<div class="page-content pull-to-refresh-content">
<div class="pull-to-refresh-layer">
<div class="preloader"></div>
<div class="pull-to-refresh-arrow"></div>
</div>
<div class="list-block media-list">
<ul>
<li class="item-content">
<div class="item-media"><img src="/framework7/images/apple.png" width="44"></div>
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">apple</div>
</div>
</div>
</li>
<li class="item-content">
<div class="item-media"><img src="/framework7/images/froots_img.jpg" width="44"></div>
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">strawberry</div>
</div>
</div>
</li>
<li class="item-content">
<div class="item-media"><img src="/framework7/images/mango.jpg" width="44"></div>
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">Mango</div>
</div>
</div>
</li>
</ul>
<div class="list-block-label">
<p>Just pull page down to let the magic happen.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/js/framework7.min.js"></script>
<script>
var myApp = new Framework7();
var $$ = Dom7;
// Dummy Content
var fruits = ['mango', 'orange', 'watermelon', 'banana'];
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content');
// Add 'refresh' listener on it
ptrContent.on('refresh', function (e) {
// Emulate 2s loading
setTimeout(function () {
var picURL = 'images/Fruit.jpg' + Math.round(Math.random() * 100);
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
var itemHTML = '<li class="item-content">' +
'<div class="item-media"><img src="/framework7/images/Fruit.jpg" width="44"/></div>' +
'<div class="item-inner">' +
'<div class="item-title-row">' +
'<div class="item-title">' + fruit + '</div>' +
'</div>' + '</div>' + '</li>';
// Prepend new list element
ptrContent.find('ul').prepend(itemHTML);
// When loading done, we need to reset it
myApp.pullToRefreshDone();
}, 2000);
});
</script>
</html>
Let us carry out the following steps to see how the above given code works β
Save the above given HTML code as pull_to_refresh.html file in your server root folder.
Save the above given HTML code as pull_to_refresh.html file in your server root folder.
Open this HTML file as http://localhost/pull_to_refresh.html and the output is displayed as shown below.
Open this HTML file as http://localhost/pull_to_refresh.html and the output is displayed as shown below.
When the user pulls down, the page will be refreshed with the contents.
When the user pulls down, the page will be refreshed with the contents.
apple
strawberry
Mango
Just pull page down to let the magic happen.
7 Lectures
1 hours
Anadi Sharma
22 Lectures
6 hours
Malhar Lathkar
102 Lectures
8 hours
Karthikeya T
19 Lectures
5 hours
Trevoir Williams
20 Lectures
1 hours
John Elder
13 Lectures
3 hours
Darwish
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2735,
"s": 2651,
"text": "It is a special component used to refresh (reload) the page contents by pulling it."
},
{
"code": null,
"e": 2794,
"s": 2735,
"text": "The following code shows how to refresh the page content β"
},
{
"code": null,
"e": 3255,
"s": 2794,
"text": "<div class = \"page\">\n <!-- Page content should have additional \"pull-to-refresh-content\" class -->\n <div class = \"page-content pull-to-refresh-content\" data-ptr-distance = \"55\">\n <!-- Default pull to refresh layer-->\n <div class = \"pull-to-refresh-layer\">\n <div class = \"preloader\"></div>\n <div class = \"pull-to-refresh-arrow\"></div>\n </div>\n\n <!-- usual content below -->\n <div class = \"list-block\">\n ...\n </div>\n</div>"
},
{
"code": null,
"e": 3299,
"s": 3255,
"text": "The following classes are used in refresh β"
},
{
"code": null,
"e": 3409,
"s": 3299,
"text": "page-content β It has an additional pull-to-refresh-content class and its required to enable pull to refresh."
},
{
"code": null,
"e": 3519,
"s": 3409,
"text": "page-content β It has an additional pull-to-refresh-content class and its required to enable pull to refresh."
},
{
"code": null,
"e": 3654,
"s": 3519,
"text": "pull-to-refresh-layer β It is a hidden layer, which is used to pull to refresh visual element and it is just a preloader and an arrow."
},
{
"code": null,
"e": 3789,
"s": 3654,
"text": "pull-to-refresh-layer β It is a hidden layer, which is used to pull to refresh visual element and it is just a preloader and an arrow."
},
{
"code": null,
"e": 3941,
"s": 3789,
"text": "data-ptr-distance = \"55\" β This is additional attribute that allows you to set custom 'pull to refresh' trigger distance and its default value is 44px."
},
{
"code": null,
"e": 4093,
"s": 3941,
"text": "data-ptr-distance = \"55\" β This is additional attribute that allows you to set custom 'pull to refresh' trigger distance and its default value is 44px."
},
{
"code": null,
"e": 4189,
"s": 4093,
"text": "In βPull to Refreshβ there are some JavaScript events, which are given in the following table β"
},
{
"code": null,
"e": 4199,
"s": 4189,
"text": "pullstart"
},
{
"code": null,
"e": 4267,
"s": 4199,
"text": "It will be triggered whenever you start pulling to refresh content."
},
{
"code": null,
"e": 4292,
"s": 4267,
"text": "Pull To Refresh content."
},
{
"code": null,
"e": 4332,
"s": 4292,
"text": "<div class = \"pull-to-refresh-content\">"
},
{
"code": null,
"e": 4341,
"s": 4332,
"text": "pullmove"
},
{
"code": null,
"e": 4398,
"s": 4341,
"text": "It is triggered when you are pulling to refresh content."
},
{
"code": null,
"e": 4423,
"s": 4398,
"text": "Pull To Refresh content."
},
{
"code": null,
"e": 4461,
"s": 4423,
"text": "<div class=\"pull-to-refresh-content\">"
},
{
"code": null,
"e": 4469,
"s": 4461,
"text": "pullend"
},
{
"code": null,
"e": 4536,
"s": 4469,
"text": "It will be triggered whenever you release pull to refresh content."
},
{
"code": null,
"e": 4561,
"s": 4536,
"text": "Pull To Refresh content."
},
{
"code": null,
"e": 4599,
"s": 4561,
"text": "<div class=\"pull-to-refresh-content\">"
},
{
"code": null,
"e": 4607,
"s": 4599,
"text": "refresh"
},
{
"code": null,
"e": 4695,
"s": 4607,
"text": "This event will be triggered when the pull to refresh enters in the \"refreshing\" state."
},
{
"code": null,
"e": 4720,
"s": 4695,
"text": "Pull To Refresh content."
},
{
"code": null,
"e": 4758,
"s": 4720,
"text": "<div class=\"pull-to-refresh-content\">"
},
{
"code": null,
"e": 4770,
"s": 4758,
"text": "refreshdone"
},
{
"code": null,
"e": 4910,
"s": 4770,
"text": "It will be triggered after it is refreshed and it goes back to the initial state. This will be done after calling pullToRefreshDone method."
},
{
"code": null,
"e": 4935,
"s": 4910,
"text": "Pull To Refresh content."
},
{
"code": null,
"e": 4973,
"s": 4935,
"text": "<div class=\"pull-to-refresh-content\">"
},
{
"code": null,
"e": 5036,
"s": 4973,
"text": "There are App's methods that can be used with Pull to Refresh."
},
{
"code": null,
"e": 5072,
"s": 5036,
"text": "myApp.pullToRefreshDone(ptrContent)"
},
{
"code": null,
"e": 5117,
"s": 5072,
"text": "It is used to reset pull-to-refresh content."
},
{
"code": null,
"e": 5156,
"s": 5117,
"text": "myApp.pullToRefreshTrigger(ptrContent)"
},
{
"code": null,
"e": 5227,
"s": 5156,
"text": "It is used to trigger to refresh on specified pull to refresh content."
},
{
"code": null,
"e": 5266,
"s": 5227,
"text": "myApp.destroyPullToRefresh(ptrContent)"
},
{
"code": null,
"e": 5350,
"s": 5266,
"text": "It is used to destroy/disable pull to refresh on specified pull to refresh content."
},
{
"code": null,
"e": 5386,
"s": 5350,
"text": "myApp.initPullToRefresh(ptrContent)"
},
{
"code": null,
"e": 5443,
"s": 5386,
"text": "It is used to initialize/enable pull to refresh content."
},
{
"code": null,
"e": 5556,
"s": 5443,
"text": "Where ptrContent is used to HTMLElement or string to pull-to-refresh-content to reset/trigger or disable/enable."
},
{
"code": null,
"e": 5671,
"s": 5556,
"text": "The following example demonstrates the use of refresh component that initiates the refreshing of a page contents β"
},
{
"code": null,
"e": 9946,
"s": 5671,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui\">\n <meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\">\n <title>Pull To Refresh</title>\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.min.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.colors.min.css\">\n </head>\n <div class=\"views\">\n <div class=\"view view-main\">\n <div class=\"pages\">\n <div data-page=\"home\" class=\"page navbar-fixed\">\n <div class=\"navbar\">\n <div class=\"navbar-inner\">\n <div class=\"left\"> </div>\n <div class=\"center\">Pull To Refresh</div>\n <div class=\"right\"> </div>\n </div>\n </div>\n <div class=\"page-content pull-to-refresh-content\">\n <div class=\"pull-to-refresh-layer\">\n <div class=\"preloader\"></div>\n <div class=\"pull-to-refresh-arrow\"></div>\n </div>\n <div class=\"list-block media-list\">\n <ul>\n <li class=\"item-content\">\n <div class=\"item-media\"><img src=\"/framework7/images/apple.png\" width=\"44\"></div>\n <div class=\"item-inner\">\n <div class=\"item-title-row\">\n <div class=\"item-title\">apple</div>\n </div>\n </div>\n </li>\n <li class=\"item-content\">\n <div class=\"item-media\"><img src=\"/framework7/images/froots_img.jpg\" width=\"44\"></div>\n <div class=\"item-inner\">\n <div class=\"item-title-row\">\n <div class=\"item-title\">strawberry</div>\n </div>\n </div>\n </li>\n <li class=\"item-content\">\n <div class=\"item-media\"><img src=\"/framework7/images/mango.jpg\" width=\"44\"></div>\n <div class=\"item-inner\">\n <div class=\"item-title-row\">\n <div class=\"item-title\">Mango</div>\n </div>\n </div>\n </li>\n </ul>\n <div class=\"list-block-label\">\n <p>Just pull page down to let the magic happen.</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/js/framework7.min.js\"></script>\n <script>\n var myApp = new Framework7();\n\n var $$ = Dom7;\n\n // Dummy Content\n var fruits = ['mango', 'orange', 'watermelon', 'banana'];\n // Pull to refresh content\n var ptrContent = $$('.pull-to-refresh-content');\n // Add 'refresh' listener on it\n ptrContent.on('refresh', function (e) {\n // Emulate 2s loading\n setTimeout(function () {\n var picURL = 'images/Fruit.jpg' + Math.round(Math.random() * 100);\n var fruit = fruits[Math.floor(Math.random() * fruits.length)];\n var itemHTML = '<li class=\"item-content\">' +\n '<div class=\"item-media\"><img src=\"/framework7/images/Fruit.jpg\" width=\"44\"/></div>' +\n '<div class=\"item-inner\">' +\n '<div class=\"item-title-row\">' +\n '<div class=\"item-title\">' + fruit + '</div>' +\n '</div>' + '</div>' + '</li>';\n // Prepend new list element\n ptrContent.find('ul').prepend(itemHTML);\n\t\t\t\t\n // When loading done, we need to reset it\n myApp.pullToRefreshDone();\n }, 2000);\n });\n </script>\n</html>"
},
{
"code": null,
"e": 10023,
"s": 9946,
"text": "Let us carry out the following steps to see how the above given code works β"
},
{
"code": null,
"e": 10111,
"s": 10023,
"text": "Save the above given HTML code as pull_to_refresh.html file in your server root folder."
},
{
"code": null,
"e": 10199,
"s": 10111,
"text": "Save the above given HTML code as pull_to_refresh.html file in your server root folder."
},
{
"code": null,
"e": 10304,
"s": 10199,
"text": "Open this HTML file as http://localhost/pull_to_refresh.html and the output is displayed as shown below."
},
{
"code": null,
"e": 10409,
"s": 10304,
"text": "Open this HTML file as http://localhost/pull_to_refresh.html and the output is displayed as shown below."
},
{
"code": null,
"e": 10481,
"s": 10409,
"text": "When the user pulls down, the page will be refreshed with the contents."
},
{
"code": null,
"e": 10553,
"s": 10481,
"text": "When the user pulls down, the page will be refreshed with the contents."
},
{
"code": null,
"e": 10566,
"s": 10553,
"text": "\n\n\n\napple\n\n\n"
},
{
"code": null,
"e": 10584,
"s": 10566,
"text": "\n\n\n\nstrawberry\n\n\n"
},
{
"code": null,
"e": 10597,
"s": 10584,
"text": "\n\n\n\nMango\n\n\n"
},
{
"code": null,
"e": 10642,
"s": 10597,
"text": "Just pull page down to let the magic happen."
},
{
"code": null,
"e": 10674,
"s": 10642,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10688,
"s": 10674,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10721,
"s": 10688,
"text": "\n 22 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10737,
"s": 10721,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10771,
"s": 10737,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10785,
"s": 10771,
"text": " Karthikeya T"
},
{
"code": null,
"e": 10818,
"s": 10785,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 10836,
"s": 10818,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 10869,
"s": 10836,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10881,
"s": 10869,
"text": " John Elder"
},
{
"code": null,
"e": 10914,
"s": 10881,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 10923,
"s": 10914,
"text": " Darwish"
},
{
"code": null,
"e": 10930,
"s": 10923,
"text": " Print"
},
{
"code": null,
"e": 10941,
"s": 10930,
"text": " Add Notes"
}
] |
Lagged Variable Regressions and Truth | by Ben Ogorek | Towards Data Science
|
Turn a nonlinear structural time-series model into a regression on lagged variables using rational transfer functions and common filters,
See bias in an ordinary least squares lagged variable regression due to remaining serial correlation in the errors,
Use generalized least squares to eliminate the bias and recover the process parameters, i.e., the βtruth.β
βNear things are more related than distant things,β states Toblerβs (very believable) first law of geography. However little we know about an underlying data generating mechanism, we can often exploit sheer nearness β in time or space β to gain an advantage. But we also know that regressing on a time-shifted copy of the dependent variable, one that is affected by all the same factors, comes with caveats.
The biggest caveat is the potential for asymptotic bias in ordinary least squares (OLS) regression that no amount of additional data can alleviate. This happens when regressors are contemporaneously correlated with the error term. As explained by Peter Kennedy in A Guide to Econometrics, βThis is because the OLS procedure, in assigning βcreditβ to regressors for explaining variation in the dependent variable, assigns, in error, some of the disturbance-generated variation of the dependent variable to the regressor with which that disturbance is contemporaneously correlated.β In short, OLS canβt separate the effects of regressor and error when the two are correlated.
From a passive prediction standpoint, the bias might not matter, and βtruth,β in this articleβs title, refers to the true data generating process underlying a time series. Henceforth, our goal is quality estimation of the process parameters. For both an objective truth and a case where parameters have scientific meaning, Iβll turn to a nonlinear, nonstationary, structural time-series model, the βfitness-fatigueβ model of athletic performance. This model relates training history to athletic performance via latent fitness and fatigue constructs and is tuned by scientifically meaningful parameters.
By rewriting this model using rational transfer functions of input to output, a set of βcommon filteringβ operations will become apparent. Applying these filters will transform the model into a dynamic linear regression, but the filtering operations will also have a side effect: errors with an MA(2) correlation structure. We will see the destructive power of contemporaneous correlation between regressors and error in OLS regression, but in the end, we will get to the truth via a GLS regression that accommodates that structure.
The βfitness-fatigueβ model of athletic performance has the form:
where p_t is a numeric measure of (athletic) performance, w_t is training βdose,β and Ξ΅_t is i.i.d. Gaussian error. The model can be viewed as a linear regression with two nonlinear features,
latent representations of athletic βfitnessβ and βfatigue,β respectively. These features are convolutions of athletic training history with exponential decay, differing only in the decay rate. Typically, fatigue (g_t) is relatively transient and associated with a faster exponential decay, but also has a relatively large regression weight compared to fitness.
With a bit of algebra, fitness and fatigue can be put into the dynamic form:
where ΞΈ_1 = exp(-1 / Ο_1) and ΞΈ_2 = exp(-1 / Ο_2).
If we plug the dynamic representation of fitness and fatigue into the original model, we arrive at
which looks nicer but is not immediately useful as h_t and g_t depend on unknown parameters.
Working a little harder, we can use the βbackshift operatorβ B defined by B y_t = y_{t-1} for any time-indexed variable y, and arrive at
Solving for h_t and g_t and plugging them back into the original model, we arrive at:
Thus we have two rational transfer functions operating on the exogenous input series w_t. With rational transfer functions, denominator terms of the form (1- ΞΈ B) correspond to an autoregressive impulse response, i.e., a process with a long memory, and this is a nuisance to us. There is an option to rid ourselves of the denominator component, but not one without a cost.
A βcommon filter,β as discussed in Identification of Multiple-Input Transfer Function Models (Liu & Hanssens, 1982) premultiplies the right and left-hand side of a time-series equation by (1- ΞΈB). It does not change the transfer function weights, so you can apply multiple common filters in succession, and besides causing complexity and losing some rows due to lags, you have not destroyed the relationship between the input and output series.
The point is, if we were to use the common filter (1- ΞΈ_1 B) (1 -ΞΈ_2 B), we rid ourselves of the autoregressive components:
The above still looks ugly, but after expanding the polynomials applying the backshift operations, we arrive at:
This is a regression of performance on two lagged versions of itself and on the external training input, but one with a twist. There is the issue of the MA(2) error structure induced by the common filters, and it has real consequences.
This section will use simulated data that can be reproduced from an R gist or downloaded directly as a csv file. To run the R code below, change the file path in the following R code block:
train_df <- read.csv("c:/devl/data/train_df.csv")head(train_df)
The following calculations show the theoretical values of all the coefficients in the lagged variable model as simulated:
# True parameter values:mu <- 496theta1 <- exp(-1 / 60)theta2 <- exp(-1 / 13)k1 <- .07k2 <- .27#Theoretical coefficient for intercept is(1 - theta1) * (1 - theta2) * mu#Theoretical coefficient for performance lagged once istheta1 + theta2#Theoretical coefficient for performance lagged twice is-theta1 * theta2#Theoretical coefficient for training lagged once isk1 * theta1 - k2 * theta2#Theoretical coefficient for training lagged twice is-theta1 * theta2 * (k1 - k2)
And thus the goal is to recover the following equation:
Side note: To go the opposite direction, solve for ΞΈ_1 and ΞΈ_2 by substitution, which leads to a quadratic equation in one of the two parameters. They lead to the same two roots, so choose ΞΈ_1 to be the larger of the two. With ΞΈ_1 and ΞΈ_2 in hand, solving for ΞΌ is trivial and k_1 and k_2 constitute a linear system with two equations and two unknowns.
To prepare for the regression, the code below lags performance and training variables once and twice each. The dplyr package makes it easy:
library(dplyr)train_aug <- train_df %>% mutate(perf_lag1 = lag(perf, n = 1, order_by = day), perf_lag2 = lag(perf, n = 2, order_by = day), train_lag1 = lag(w, n = 1, order_by = day), train_lag2 = lag(w, n = 2, order_by = day))
Letβs see what happens when we regress performance on these lagged variables using OLS:
my_lm <- lm(perf ~ perf_lag1 + perf_lag2 + train_lag1 + train_lag2, data = train_aug[3:nrow(train_aug), ])summary(my_lm)
The above code results in the partial output:
Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 33.99821 12.09470 2.811 0.005327 ** perf_lag1 0.48066 0.05619 8.553 1.18e-15 ***perf_lag2 0.46189 0.05504 8.393 3.45e-15 ***train_lag1 -0.15602 0.04406 -3.541 0.000475 ***train_lag2 -0.02346 0.04516 -0.520 0.603807 ---Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1Residual standard error: 8.518 on 252 degrees of freedomMultiple R-squared: 0.9117, Adjusted R-squared: 0.9103 F-statistic: 650.4 on 4 and 252 DF, p-value: < 2.2e-16
There is clearly bias in the OLS coefficient estimates as a results of the serial correlation remaining in the residuals.
Fortunately, Rβs nlme package offers generalized least squares (GLS) model fitting via the gls function, which handles the MA(2) error structure:
library(nlme)my_gls <- gls(perf ~ perf_lag1 + perf_lag2 + train_lag1 + train_lag2, data = train_aug[3:nrow(train_aug), ], corARMA(form = ~day, p = 0, q = 2))summary(my_gls)
The following partial output comes from the above code:
Correlation Structure: ARMA(0,2) Formula: ~day Parameter estimate(s): Theta1 Theta2 -1.9059497 0.9117409 Coefficients: Value Std.Error t-value p-value(Intercept) 0.6571088 0.11700730 5.61596 0perf_lag1 1.9187158 0.00815689 235.22646 0perf_lag2 -0.9200058 0.00815495 -112.81568 0train_lag1 -0.1662026 0.02238219 -7.42566 0train_lag2 0.1664704 0.02241510 7.42671 0
Via GLS regression, weβve recovered the true parameter values to within plausible estimation error.
Previous articles on the fitness-fatigue model have used heavy machinery to estimate the parameters: nonlinear least squares, linear regression with complex spline-convolution features and the Kalman Filter, to name three. That a linear regression (fit via GLS) on a few lagged variables was able to recover the theoretical underlying process speaks to the expressive power of the dynamic regression model
What is the cost of blindly regressing on a few lags of input and output each? Focusing only on one-step ahead forecast accuracy, probably not much. The OLS regression with lagged variables βexplainedβ most of the variation in the next performance value, but itβs also suggesting a quite different process than the one used to simulate the data. The internals of this process were recovered by the GLS regression, and this speaks of getting to the βtruthβ that the title mentioned.
A topic for further research and discussion would be whether it is wise to use GLS regression with an MA(q) error structure for all dynamic regressions. It is easy enough to implement in R via nlme. On the other hand, its prediction function did not use the error structure, and it would thus require additional effort from the user to make the GLS forecasts competitive with those of OLS. For out-of-the-box, one-step-ahead prediction, may be difficult to justify the added complexity of the GLS procedure. For getting to the true underlying system parameters, incorporating an MA(q) error structure via GLS may very well bring us closer to the truth.
|
[
{
"code": null,
"e": 310,
"s": 172,
"text": "Turn a nonlinear structural time-series model into a regression on lagged variables using rational transfer functions and common filters,"
},
{
"code": null,
"e": 426,
"s": 310,
"text": "See bias in an ordinary least squares lagged variable regression due to remaining serial correlation in the errors,"
},
{
"code": null,
"e": 533,
"s": 426,
"text": "Use generalized least squares to eliminate the bias and recover the process parameters, i.e., the βtruth.β"
},
{
"code": null,
"e": 941,
"s": 533,
"text": "βNear things are more related than distant things,β states Toblerβs (very believable) first law of geography. However little we know about an underlying data generating mechanism, we can often exploit sheer nearness β in time or space β to gain an advantage. But we also know that regressing on a time-shifted copy of the dependent variable, one that is affected by all the same factors, comes with caveats."
},
{
"code": null,
"e": 1615,
"s": 941,
"text": "The biggest caveat is the potential for asymptotic bias in ordinary least squares (OLS) regression that no amount of additional data can alleviate. This happens when regressors are contemporaneously correlated with the error term. As explained by Peter Kennedy in A Guide to Econometrics, βThis is because the OLS procedure, in assigning βcreditβ to regressors for explaining variation in the dependent variable, assigns, in error, some of the disturbance-generated variation of the dependent variable to the regressor with which that disturbance is contemporaneously correlated.β In short, OLS canβt separate the effects of regressor and error when the two are correlated."
},
{
"code": null,
"e": 2218,
"s": 1615,
"text": "From a passive prediction standpoint, the bias might not matter, and βtruth,β in this articleβs title, refers to the true data generating process underlying a time series. Henceforth, our goal is quality estimation of the process parameters. For both an objective truth and a case where parameters have scientific meaning, Iβll turn to a nonlinear, nonstationary, structural time-series model, the βfitness-fatigueβ model of athletic performance. This model relates training history to athletic performance via latent fitness and fatigue constructs and is tuned by scientifically meaningful parameters."
},
{
"code": null,
"e": 2751,
"s": 2218,
"text": "By rewriting this model using rational transfer functions of input to output, a set of βcommon filteringβ operations will become apparent. Applying these filters will transform the model into a dynamic linear regression, but the filtering operations will also have a side effect: errors with an MA(2) correlation structure. We will see the destructive power of contemporaneous correlation between regressors and error in OLS regression, but in the end, we will get to the truth via a GLS regression that accommodates that structure."
},
{
"code": null,
"e": 2817,
"s": 2751,
"text": "The βfitness-fatigueβ model of athletic performance has the form:"
},
{
"code": null,
"e": 3009,
"s": 2817,
"text": "where p_t is a numeric measure of (athletic) performance, w_t is training βdose,β and Ξ΅_t is i.i.d. Gaussian error. The model can be viewed as a linear regression with two nonlinear features,"
},
{
"code": null,
"e": 3370,
"s": 3009,
"text": "latent representations of athletic βfitnessβ and βfatigue,β respectively. These features are convolutions of athletic training history with exponential decay, differing only in the decay rate. Typically, fatigue (g_t) is relatively transient and associated with a faster exponential decay, but also has a relatively large regression weight compared to fitness."
},
{
"code": null,
"e": 3447,
"s": 3370,
"text": "With a bit of algebra, fitness and fatigue can be put into the dynamic form:"
},
{
"code": null,
"e": 3498,
"s": 3447,
"text": "where ΞΈ_1 = exp(-1 / Ο_1) and ΞΈ_2 = exp(-1 / Ο_2)."
},
{
"code": null,
"e": 3597,
"s": 3498,
"text": "If we plug the dynamic representation of fitness and fatigue into the original model, we arrive at"
},
{
"code": null,
"e": 3690,
"s": 3597,
"text": "which looks nicer but is not immediately useful as h_t and g_t depend on unknown parameters."
},
{
"code": null,
"e": 3827,
"s": 3690,
"text": "Working a little harder, we can use the βbackshift operatorβ B defined by B y_t = y_{t-1} for any time-indexed variable y, and arrive at"
},
{
"code": null,
"e": 3913,
"s": 3827,
"text": "Solving for h_t and g_t and plugging them back into the original model, we arrive at:"
},
{
"code": null,
"e": 4286,
"s": 3913,
"text": "Thus we have two rational transfer functions operating on the exogenous input series w_t. With rational transfer functions, denominator terms of the form (1- ΞΈ B) correspond to an autoregressive impulse response, i.e., a process with a long memory, and this is a nuisance to us. There is an option to rid ourselves of the denominator component, but not one without a cost."
},
{
"code": null,
"e": 4731,
"s": 4286,
"text": "A βcommon filter,β as discussed in Identification of Multiple-Input Transfer Function Models (Liu & Hanssens, 1982) premultiplies the right and left-hand side of a time-series equation by (1- ΞΈB). It does not change the transfer function weights, so you can apply multiple common filters in succession, and besides causing complexity and losing some rows due to lags, you have not destroyed the relationship between the input and output series."
},
{
"code": null,
"e": 4855,
"s": 4731,
"text": "The point is, if we were to use the common filter (1- ΞΈ_1 B) (1 -ΞΈ_2 B), we rid ourselves of the autoregressive components:"
},
{
"code": null,
"e": 4968,
"s": 4855,
"text": "The above still looks ugly, but after expanding the polynomials applying the backshift operations, we arrive at:"
},
{
"code": null,
"e": 5204,
"s": 4968,
"text": "This is a regression of performance on two lagged versions of itself and on the external training input, but one with a twist. There is the issue of the MA(2) error structure induced by the common filters, and it has real consequences."
},
{
"code": null,
"e": 5394,
"s": 5204,
"text": "This section will use simulated data that can be reproduced from an R gist or downloaded directly as a csv file. To run the R code below, change the file path in the following R code block:"
},
{
"code": null,
"e": 5458,
"s": 5394,
"text": "train_df <- read.csv(\"c:/devl/data/train_df.csv\")head(train_df)"
},
{
"code": null,
"e": 5580,
"s": 5458,
"text": "The following calculations show the theoretical values of all the coefficients in the lagged variable model as simulated:"
},
{
"code": null,
"e": 6049,
"s": 5580,
"text": "# True parameter values:mu <- 496theta1 <- exp(-1 / 60)theta2 <- exp(-1 / 13)k1 <- .07k2 <- .27#Theoretical coefficient for intercept is(1 - theta1) * (1 - theta2) * mu#Theoretical coefficient for performance lagged once istheta1 + theta2#Theoretical coefficient for performance lagged twice is-theta1 * theta2#Theoretical coefficient for training lagged once isk1 * theta1 - k2 * theta2#Theoretical coefficient for training lagged twice is-theta1 * theta2 * (k1 - k2)"
},
{
"code": null,
"e": 6105,
"s": 6049,
"text": "And thus the goal is to recover the following equation:"
},
{
"code": null,
"e": 6458,
"s": 6105,
"text": "Side note: To go the opposite direction, solve for ΞΈ_1 and ΞΈ_2 by substitution, which leads to a quadratic equation in one of the two parameters. They lead to the same two roots, so choose ΞΈ_1 to be the larger of the two. With ΞΈ_1 and ΞΈ_2 in hand, solving for ΞΌ is trivial and k_1 and k_2 constitute a linear system with two equations and two unknowns."
},
{
"code": null,
"e": 6598,
"s": 6458,
"text": "To prepare for the regression, the code below lags performance and training variables once and twice each. The dplyr package makes it easy:"
},
{
"code": null,
"e": 6850,
"s": 6598,
"text": "library(dplyr)train_aug <- train_df %>% mutate(perf_lag1 = lag(perf, n = 1, order_by = day), perf_lag2 = lag(perf, n = 2, order_by = day), train_lag1 = lag(w, n = 1, order_by = day), train_lag2 = lag(w, n = 2, order_by = day))"
},
{
"code": null,
"e": 6938,
"s": 6850,
"text": "Letβs see what happens when we regress performance on these lagged variables using OLS:"
},
{
"code": null,
"e": 7070,
"s": 6938,
"text": "my_lm <- lm(perf ~ perf_lag1 + perf_lag2 + train_lag1 + train_lag2, data = train_aug[3:nrow(train_aug), ])summary(my_lm)"
},
{
"code": null,
"e": 7116,
"s": 7070,
"text": "The above code results in the partial output:"
},
{
"code": null,
"e": 7675,
"s": 7116,
"text": "Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 33.99821 12.09470 2.811 0.005327 ** perf_lag1 0.48066 0.05619 8.553 1.18e-15 ***perf_lag2 0.46189 0.05504 8.393 3.45e-15 ***train_lag1 -0.15602 0.04406 -3.541 0.000475 ***train_lag2 -0.02346 0.04516 -0.520 0.603807 ---Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1Residual standard error: 8.518 on 252 degrees of freedomMultiple R-squared: 0.9117,\tAdjusted R-squared: 0.9103 F-statistic: 650.4 on 4 and 252 DF, p-value: < 2.2e-16"
},
{
"code": null,
"e": 7797,
"s": 7675,
"text": "There is clearly bias in the OLS coefficient estimates as a results of the serial correlation remaining in the residuals."
},
{
"code": null,
"e": 7943,
"s": 7797,
"text": "Fortunately, Rβs nlme package offers generalized least squares (GLS) model fitting via the gls function, which handles the MA(2) error structure:"
},
{
"code": null,
"e": 8155,
"s": 7943,
"text": "library(nlme)my_gls <- gls(perf ~ perf_lag1 + perf_lag2 + train_lag1 + train_lag2, data = train_aug[3:nrow(train_aug), ], corARMA(form = ~day, p = 0, q = 2))summary(my_gls)"
},
{
"code": null,
"e": 8211,
"s": 8155,
"text": "The following partial output comes from the above code:"
},
{
"code": null,
"e": 8651,
"s": 8211,
"text": "Correlation Structure: ARMA(0,2) Formula: ~day Parameter estimate(s): Theta1 Theta2 -1.9059497 0.9117409 Coefficients: Value Std.Error t-value p-value(Intercept) 0.6571088 0.11700730 5.61596 0perf_lag1 1.9187158 0.00815689 235.22646 0perf_lag2 -0.9200058 0.00815495 -112.81568 0train_lag1 -0.1662026 0.02238219 -7.42566 0train_lag2 0.1664704 0.02241510 7.42671 0"
},
{
"code": null,
"e": 8751,
"s": 8651,
"text": "Via GLS regression, weβve recovered the true parameter values to within plausible estimation error."
},
{
"code": null,
"e": 9157,
"s": 8751,
"text": "Previous articles on the fitness-fatigue model have used heavy machinery to estimate the parameters: nonlinear least squares, linear regression with complex spline-convolution features and the Kalman Filter, to name three. That a linear regression (fit via GLS) on a few lagged variables was able to recover the theoretical underlying process speaks to the expressive power of the dynamic regression model"
},
{
"code": null,
"e": 9639,
"s": 9157,
"text": "What is the cost of blindly regressing on a few lags of input and output each? Focusing only on one-step ahead forecast accuracy, probably not much. The OLS regression with lagged variables βexplainedβ most of the variation in the next performance value, but itβs also suggesting a quite different process than the one used to simulate the data. The internals of this process were recovered by the GLS regression, and this speaks of getting to the βtruthβ that the title mentioned."
}
] |
PySpark - StorageLevel
|
StorageLevel decides how RDD should be stored. In Apache Spark, StorageLevel decides whether RDD should be stored in the memory or should it be stored over the disk, or both. It also decides whether to serialize RDD and whether to replicate RDD partitions.
The following code block has the class definition of a StorageLevel β
class pyspark.StorageLevel(useDisk, useMemory, useOffHeap, deserialized, replication = 1)
Now, to decide the storage of RDD, there are different storage levels, which are given below β
DISK_ONLY = StorageLevel(True, False, False, False, 1)
DISK_ONLY = StorageLevel(True, False, False, False, 1)
DISK_ONLY_2 = StorageLevel(True, False, False, False, 2)
DISK_ONLY_2 = StorageLevel(True, False, False, False, 2)
MEMORY_AND_DISK = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK_2 = StorageLevel(True, True, False, False, 2)
MEMORY_AND_DISK_2 = StorageLevel(True, True, False, False, 2)
MEMORY_AND_DISK_SER = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK_SER = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK_SER_2 = StorageLevel(True, True, False, False, 2)
MEMORY_AND_DISK_SER_2 = StorageLevel(True, True, False, False, 2)
MEMORY_ONLY = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY_2 = StorageLevel(False, True, False, False, 2)
MEMORY_ONLY_2 = StorageLevel(False, True, False, False, 2)
MEMORY_ONLY_SER = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY_SER = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY_SER_2 = StorageLevel(False, True, False, False, 2)
MEMORY_ONLY_SER_2 = StorageLevel(False, True, False, False, 2)
OFF_HEAP = StorageLevel(True, True, True, False, 1)
OFF_HEAP = StorageLevel(True, True, True, False, 1)
Let us consider the following example of StorageLevel, where we use the storage level MEMORY_AND_DISK_2, which means RDD partitions will have replication of 2.
------------------------------------storagelevel.py-------------------------------------
from pyspark import SparkContext
import pyspark
sc = SparkContext (
"local",
"storagelevel app"
)
rdd1 = sc.parallelize([1,2])
rdd1.persist( pyspark.StorageLevel.MEMORY_AND_DISK_2 )
rdd1.getStorageLevel()
print(rdd1.getStorageLevel())
------------------------------------storagelevel.py-------------------------------------
Command β The command is as follows β
$SPARK_HOME/bin/spark-submit storagelevel.py
Output β The output for the above command is given below β
Disk Memory Serialized 2x Replicated
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2062,
"s": 1805,
"text": "StorageLevel decides how RDD should be stored. In Apache Spark, StorageLevel decides whether RDD should be stored in the memory or should it be stored over the disk, or both. It also decides whether to serialize RDD and whether to replicate RDD partitions."
},
{
"code": null,
"e": 2132,
"s": 2062,
"text": "The following code block has the class definition of a StorageLevel β"
},
{
"code": null,
"e": 2223,
"s": 2132,
"text": "class pyspark.StorageLevel(useDisk, useMemory, useOffHeap, deserialized, replication = 1)\n"
},
{
"code": null,
"e": 2318,
"s": 2223,
"text": "Now, to decide the storage of RDD, there are different storage levels, which are given below β"
},
{
"code": null,
"e": 2373,
"s": 2318,
"text": "DISK_ONLY = StorageLevel(True, False, False, False, 1)"
},
{
"code": null,
"e": 2428,
"s": 2373,
"text": "DISK_ONLY = StorageLevel(True, False, False, False, 1)"
},
{
"code": null,
"e": 2485,
"s": 2428,
"text": "DISK_ONLY_2 = StorageLevel(True, False, False, False, 2)"
},
{
"code": null,
"e": 2542,
"s": 2485,
"text": "DISK_ONLY_2 = StorageLevel(True, False, False, False, 2)"
},
{
"code": null,
"e": 2602,
"s": 2542,
"text": "MEMORY_AND_DISK = StorageLevel(True, True, False, False, 1)"
},
{
"code": null,
"e": 2662,
"s": 2602,
"text": "MEMORY_AND_DISK = StorageLevel(True, True, False, False, 1)"
},
{
"code": null,
"e": 2724,
"s": 2662,
"text": "MEMORY_AND_DISK_2 = StorageLevel(True, True, False, False, 2)"
},
{
"code": null,
"e": 2786,
"s": 2724,
"text": "MEMORY_AND_DISK_2 = StorageLevel(True, True, False, False, 2)"
},
{
"code": null,
"e": 2850,
"s": 2786,
"text": "MEMORY_AND_DISK_SER = StorageLevel(True, True, False, False, 1)"
},
{
"code": null,
"e": 2914,
"s": 2850,
"text": "MEMORY_AND_DISK_SER = StorageLevel(True, True, False, False, 1)"
},
{
"code": null,
"e": 2980,
"s": 2914,
"text": "MEMORY_AND_DISK_SER_2 = StorageLevel(True, True, False, False, 2)"
},
{
"code": null,
"e": 3046,
"s": 2980,
"text": "MEMORY_AND_DISK_SER_2 = StorageLevel(True, True, False, False, 2)"
},
{
"code": null,
"e": 3103,
"s": 3046,
"text": "MEMORY_ONLY = StorageLevel(False, True, False, False, 1)"
},
{
"code": null,
"e": 3160,
"s": 3103,
"text": "MEMORY_ONLY = StorageLevel(False, True, False, False, 1)"
},
{
"code": null,
"e": 3219,
"s": 3160,
"text": "MEMORY_ONLY_2 = StorageLevel(False, True, False, False, 2)"
},
{
"code": null,
"e": 3278,
"s": 3219,
"text": "MEMORY_ONLY_2 = StorageLevel(False, True, False, False, 2)"
},
{
"code": null,
"e": 3339,
"s": 3278,
"text": "MEMORY_ONLY_SER = StorageLevel(False, True, False, False, 1)"
},
{
"code": null,
"e": 3400,
"s": 3339,
"text": "MEMORY_ONLY_SER = StorageLevel(False, True, False, False, 1)"
},
{
"code": null,
"e": 3463,
"s": 3400,
"text": "MEMORY_ONLY_SER_2 = StorageLevel(False, True, False, False, 2)"
},
{
"code": null,
"e": 3526,
"s": 3463,
"text": "MEMORY_ONLY_SER_2 = StorageLevel(False, True, False, False, 2)"
},
{
"code": null,
"e": 3578,
"s": 3526,
"text": "OFF_HEAP = StorageLevel(True, True, True, False, 1)"
},
{
"code": null,
"e": 3630,
"s": 3578,
"text": "OFF_HEAP = StorageLevel(True, True, True, False, 1)"
},
{
"code": null,
"e": 3790,
"s": 3630,
"text": "Let us consider the following example of StorageLevel, where we use the storage level MEMORY_AND_DISK_2, which means RDD partitions will have replication of 2."
},
{
"code": null,
"e": 4211,
"s": 3790,
"text": "------------------------------------storagelevel.py-------------------------------------\nfrom pyspark import SparkContext\nimport pyspark\nsc = SparkContext (\n \"local\", \n \"storagelevel app\"\n)\nrdd1 = sc.parallelize([1,2])\nrdd1.persist( pyspark.StorageLevel.MEMORY_AND_DISK_2 )\nrdd1.getStorageLevel()\nprint(rdd1.getStorageLevel())\n------------------------------------storagelevel.py-------------------------------------\n"
},
{
"code": null,
"e": 4249,
"s": 4211,
"text": "Command β The command is as follows β"
},
{
"code": null,
"e": 4295,
"s": 4249,
"text": "$SPARK_HOME/bin/spark-submit storagelevel.py\n"
},
{
"code": null,
"e": 4354,
"s": 4295,
"text": "Output β The output for the above command is given below β"
},
{
"code": null,
"e": 4392,
"s": 4354,
"text": "Disk Memory Serialized 2x Replicated\n"
},
{
"code": null,
"e": 4399,
"s": 4392,
"text": " Print"
},
{
"code": null,
"e": 4410,
"s": 4399,
"text": " Add Notes"
}
] |
Row with max 1s | Practice | GeeksforGeeks
|
Given a boolean 2D array of n x m dimensions where each row is sorted. Find the 0-based index of the first row that has the maximum number of 1's.
Example 1:
Input:
N = 4 , M = 4
Arr[][] = {{0, 1, 1, 1},
{0, 0, 1, 1},
{1, 1, 1, 1},
{0, 0, 0, 0}}
Output: 2
Explanation: Row 2 contains 4 1's (0-based
indexing).
Example 2:
Input:
N = 2, M = 2
Arr[][] = {{0, 0}, {1, 1}}
Output: 1
Explanation: Row 1 contains 2 1's (0-based
indexing).
Your Task:
You don't need to read input or print anything. Your task is to complete the function rowWithMax1s() which takes the array of booleans arr[][], n and m as input parameters and returns the 0-based index of the first row that has the most number of 1s. If no such row exists, return -1.
Expected Time Complexity: O(N+M)
Expected Auxiliary Space: O(1)
Constraints:
1 β€ N, M β€ 103
0 β€ Arr[i][j] β€ 1
+1
krunalpabari2012in 9 hours
Time Complexity O(N).
Space Complexity O(1).
class Solution { int rowWithMax1s(int arr[][], int n, int m) { int row=0; int counter=0; int idx=-1; int max=0; for(int i=m-1;i>=0 && row<n;i--) { if(arr[row][i]==1) { counter++; idx=row; } else{ row++; i++; } } return idx; }}
0
aman hamid20 hours ago
USING BINARY SEARCH
int rowWithMax1s(vector<vector<int> > arr, int n, int m) { // code here int i; int ans = -1; int max = INT_MIN; for(i=0;i<n;i++) { int start=0,end=m-1,index=-1,count=0; while(start<=end) { int mid = (start+end)/2; if(arr[i][mid]==1) { index = mid; end = mid-1; } else { start = mid+1; } } if(index!=-1) { count = (m-index); if(count>max) { max = count; ans = i; } } } return ans;}
0
priyansh7089021 hours ago
Time Complexity O(n*m)
Token β 0.21/1.74
Simple Solution
int max = 0; int count = 0; int ans = -1; for(int i =0;i<n;i++) { count = 0; for(int j=0;j<m;j++) { if(arr[i][j] == 1) { count++; } } if(count>max) { max = count; ans = i; } } return ans;;}
0
riyaraip084 days ago
C++ soln
Time takes = 0.22s
int rowWithMax1s(vector<vector<int> > arr, int n, int m) { // code here for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(arr[j][i]==1){ return j; } } } return -1;}
+1
mannukhurana103975 days ago
Java
int rowWithMax1s(int arr[][], int n, int m) {
// space : O(1)
// time: O(n*m) || 0.74/2.2
int max = 0;
int index=-1;
for(int i=0;i<n;i++){
int sum=0;
for(int ii: arr[i])
sum+=ii;
if(sum>max){
max = sum;
index=i;
}
}
// -------------------------------------------------------------------
// space : O(1)
// time: O(n+m) || 1.25/2.2
int index=-1;
int x=0;
for(int i=m-1;i>=0;i--){
if(arr[x][i]==1){
index=x;
}
else{
if(x<n-1){
i++;x++;}
}
}
return index;
}
0
aniket6518gadhe6 days ago
JAVA SOLUTION
Total Time Taken:0.82/2.2
int rowWithMax1s(int arr[][], int n, int m) { boolean isEmpty= true; for(int i=0;i<n;i++){ if(arr[i][m-1]==1){ isEmpty=false; break;} } if(isEmpty==false){ for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(arr[j][i]==1) return j; } }} return -1; }
0
raghavendra7776 days ago
Python 0.54 S
a=0 p=-1 g=0 l=[] for i in range(0,len(arr)): k=arr[i].count(1) g=i if k>a: a=k p=g return p
+1
avinav26116 days ago
Easy C++ Solution ( 0.2 / 1.74 sec)
+1
kshitij14101 week ago
int rowWithMax1s(vector<vector<int> > arr, int n, int m) { int ans=-1; int r=0; int top=m-1; while(top>=0 and r<n) { if(arr[r][top]==1) { ans=r; top--; } else r++; } return ans;}
+1
vcreateforme91 week ago
class Solution{public:int rowWithMax1s(vector<vector<int> > arr, int n, int m) { // code here for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(arr[j][i]==1) return j; } } return -1;}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 385,
"s": 238,
"text": "Given a boolean 2D array of n x m dimensions where each row is sorted. Find the 0-based index of the first row that has the maximum number of 1's."
},
{
"code": null,
"e": 396,
"s": 385,
"text": "Example 1:"
},
{
"code": null,
"e": 583,
"s": 396,
"text": "Input: \nN = 4 , M = 4\nArr[][] = {{0, 1, 1, 1},\n {0, 0, 1, 1},\n {1, 1, 1, 1},\n {0, 0, 0, 0}}\nOutput: 2\nExplanation: Row 2 contains 4 1's (0-based\nindexing).\n"
},
{
"code": null,
"e": 595,
"s": 583,
"text": "\nExample 2:"
},
{
"code": null,
"e": 708,
"s": 595,
"text": "Input: \nN = 2, M = 2\nArr[][] = {{0, 0}, {1, 1}}\nOutput: 1\nExplanation: Row 1 contains 2 1's (0-based\nindexing).\n"
},
{
"code": null,
"e": 1009,
"s": 708,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function rowWithMax1s() which takes the array of booleans arr[][], n and m as input parameters and returns the 0-based index of the first row that has the most number of 1s. If no such row exists, return -1.\n "
},
{
"code": null,
"e": 1073,
"s": 1009,
"text": "Expected Time Complexity: O(N+M)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1121,
"s": 1073,
"text": "\nConstraints:\n1 β€ N, M β€ 103\n0 β€ Arr[i][j] β€ 1 "
},
{
"code": null,
"e": 1126,
"s": 1123,
"text": "+1"
},
{
"code": null,
"e": 1153,
"s": 1126,
"text": "krunalpabari2012in 9 hours"
},
{
"code": null,
"e": 1175,
"s": 1153,
"text": "Time Complexity O(N)."
},
{
"code": null,
"e": 1198,
"s": 1175,
"text": "Space Complexity O(1)."
},
{
"code": null,
"e": 1658,
"s": 1200,
"text": "class Solution { int rowWithMax1s(int arr[][], int n, int m) { int row=0; int counter=0; int idx=-1; int max=0; for(int i=m-1;i>=0 && row<n;i--) { if(arr[row][i]==1) { counter++; idx=row; } else{ row++; i++; } } return idx; }}"
},
{
"code": null,
"e": 1660,
"s": 1658,
"text": "0"
},
{
"code": null,
"e": 1683,
"s": 1660,
"text": "aman hamid20 hours ago"
},
{
"code": null,
"e": 1703,
"s": 1683,
"text": "USING BINARY SEARCH"
},
{
"code": null,
"e": 2294,
"s": 1705,
"text": "int rowWithMax1s(vector<vector<int> > arr, int n, int m) { // code here int i; int ans = -1; int max = INT_MIN; for(i=0;i<n;i++) { int start=0,end=m-1,index=-1,count=0; while(start<=end) { int mid = (start+end)/2; if(arr[i][mid]==1) { index = mid; end = mid-1; } else { start = mid+1; } } if(index!=-1) { count = (m-index); if(count>max) { max = count; ans = i; } } } return ans;}"
},
{
"code": null,
"e": 2296,
"s": 2294,
"text": "0"
},
{
"code": null,
"e": 2322,
"s": 2296,
"text": "priyansh7089021 hours ago"
},
{
"code": null,
"e": 2345,
"s": 2322,
"text": "Time Complexity O(n*m)"
},
{
"code": null,
"e": 2363,
"s": 2345,
"text": "Token β 0.21/1.74"
},
{
"code": null,
"e": 2379,
"s": 2363,
"text": "Simple Solution"
},
{
"code": null,
"e": 2715,
"s": 2381,
"text": " int max = 0; int count = 0; int ans = -1; for(int i =0;i<n;i++) { count = 0; for(int j=0;j<m;j++) { if(arr[i][j] == 1) { count++; } } if(count>max) { max = count; ans = i; } } return ans;;} "
},
{
"code": null,
"e": 2719,
"s": 2717,
"text": "0"
},
{
"code": null,
"e": 2740,
"s": 2719,
"text": "riyaraip084 days ago"
},
{
"code": null,
"e": 2749,
"s": 2740,
"text": "C++ soln"
},
{
"code": null,
"e": 2770,
"s": 2749,
"text": "Time takes = 0.22s "
},
{
"code": null,
"e": 3007,
"s": 2770,
"text": "int rowWithMax1s(vector<vector<int> > arr, int n, int m) { // code here for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(arr[j][i]==1){ return j; } } } return -1;}"
},
{
"code": null,
"e": 3010,
"s": 3007,
"text": "+1"
},
{
"code": null,
"e": 3038,
"s": 3010,
"text": "mannukhurana103975 days ago"
},
{
"code": null,
"e": 3043,
"s": 3038,
"text": "Java"
},
{
"code": null,
"e": 3891,
"s": 3043,
"text": "int rowWithMax1s(int arr[][], int n, int m) {\n // space : O(1)\n // time: O(n*m) || 0.74/2.2\n \n int max = 0;\n int index=-1;\n \n for(int i=0;i<n;i++){\n int sum=0;\n for(int ii: arr[i])\n sum+=ii;\n if(sum>max){\n max = sum;\n index=i;\n }\n \n }\n \n \n // -------------------------------------------------------------------\n \n // space : O(1)\n // time: O(n+m) || 1.25/2.2\n \n int index=-1;\n int x=0;\n \n for(int i=m-1;i>=0;i--){\n if(arr[x][i]==1){\n index=x;\n }\n else{\n if(x<n-1){\n i++;x++;}\n }\n }\n \n return index;\n }"
},
{
"code": null,
"e": 3893,
"s": 3891,
"text": "0"
},
{
"code": null,
"e": 3919,
"s": 3893,
"text": "aniket6518gadhe6 days ago"
},
{
"code": null,
"e": 3933,
"s": 3919,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 3959,
"s": 3933,
"text": "Total Time Taken:0.82/2.2"
},
{
"code": null,
"e": 4337,
"s": 3961,
"text": "int rowWithMax1s(int arr[][], int n, int m) { boolean isEmpty= true; for(int i=0;i<n;i++){ if(arr[i][m-1]==1){ isEmpty=false; break;} } if(isEmpty==false){ for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(arr[j][i]==1) return j; } }} return -1; }"
},
{
"code": null,
"e": 4339,
"s": 4337,
"text": "0"
},
{
"code": null,
"e": 4364,
"s": 4339,
"text": "raghavendra7776 days ago"
},
{
"code": null,
"e": 4378,
"s": 4364,
"text": "Python 0.54 S"
},
{
"code": null,
"e": 4500,
"s": 4378,
"text": "a=0 p=-1 g=0 l=[] for i in range(0,len(arr)): k=arr[i].count(1) g=i if k>a: a=k p=g return p"
},
{
"code": null,
"e": 4503,
"s": 4500,
"text": "+1"
},
{
"code": null,
"e": 4524,
"s": 4503,
"text": "avinav26116 days ago"
},
{
"code": null,
"e": 4560,
"s": 4524,
"text": "Easy C++ Solution ( 0.2 / 1.74 sec)"
},
{
"code": null,
"e": 4565,
"s": 4562,
"text": "+1"
},
{
"code": null,
"e": 4587,
"s": 4565,
"text": "kshitij14101 week ago"
},
{
"code": null,
"e": 4837,
"s": 4587,
"text": " int rowWithMax1s(vector<vector<int> > arr, int n, int m) { int ans=-1; int r=0; int top=m-1; while(top>=0 and r<n) { if(arr[r][top]==1) { ans=r; top--; } else r++; } return ans;}"
},
{
"code": null,
"e": 4840,
"s": 4837,
"text": "+1"
},
{
"code": null,
"e": 4864,
"s": 4840,
"text": "vcreateforme91 week ago"
},
{
"code": null,
"e": 5105,
"s": 4864,
"text": "class Solution{public:int rowWithMax1s(vector<vector<int> > arr, int n, int m) { // code here for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(arr[j][i]==1) return j; } } return -1;}"
},
{
"code": null,
"e": 5108,
"s": 5105,
"text": "};"
},
{
"code": null,
"e": 5254,
"s": 5108,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5290,
"s": 5254,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5300,
"s": 5290,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5310,
"s": 5300,
"text": "\nContest\n"
},
{
"code": null,
"e": 5373,
"s": 5310,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5521,
"s": 5373,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5729,
"s": 5521,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5835,
"s": 5729,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to delete multiple files in a directory in Python?
|
You can delete a single file or a single empty folder with functions in the os module.
For example, if you want to delete a file my_file.txt,
>>> import os
>>> os.remove('my_file.txt')
The argument to os.remove must be absolute or relative path.
To delete multiple files, just loop over your list of files and use the above function. If you want to delete a folder containing all files you want to remove, you can remove the folder as follows:
>>> import shutil
>>> shutil.rmtree('my_folder')
You can also use regex to delete the files matching a pattern. For example,
import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
for file in filter(lambda x: re.match(pattern, x), files):
os.remove(os.path.join(root, file))
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "You can delete a single file or a single empty folder with functions in the os module."
},
{
"code": null,
"e": 1204,
"s": 1149,
"text": "For example, if you want to delete a file my_file.txt,"
},
{
"code": null,
"e": 1247,
"s": 1204,
"text": ">>> import os\n>>> os.remove('my_file.txt')"
},
{
"code": null,
"e": 1308,
"s": 1247,
"text": "The argument to os.remove must be absolute or relative path."
},
{
"code": null,
"e": 1506,
"s": 1308,
"text": "To delete multiple files, just loop over your list of files and use the above function. If you want to delete a folder containing all files you want to remove, you can remove the folder as follows:"
},
{
"code": null,
"e": 1555,
"s": 1506,
"text": ">>> import shutil\n>>> shutil.rmtree('my_folder')"
},
{
"code": null,
"e": 1631,
"s": 1555,
"text": "You can also use regex to delete the files matching a pattern. For example,"
},
{
"code": null,
"e": 1854,
"s": 1631,
"text": "import os, re, os.path\npattern = \"^your_regex_here$\"\nmypath = \"my_folder\"\nfor root, dirs, files in os.walk(mypath):\n for file in filter(lambda x: re.match(pattern, x), files):\n os.remove(os.path.join(root, file))"
}
] |
How to Setup and Configure Postfix on Ubuntu 16.04
|
In this article we will learn about how to set up Postfix on Ubuntu 16.04, Postfix is a very popular open-source MTA (Mail Transfer Agent) which can be used to relay the emails on Ubuntu Linux systems, most of the public mail servers over the real world use the postfix only.
To complete this demo we needed the following
A machine with Ubuntu 16.04 installed and a non-root user with sudo permissions on the machine.
A (FQDN) fully Qualified Domain Name points to the machine.
We assume the Domain FQDN mail.mydomain.com
As Postfix is available with Ubuntu default repository we can directly go for installation.
Before we start the installation, we will first update the using the below command with apt-get.
$ sudo apt-get update
Now we will install postfix with the below command.
$ sudo apt-get install postfix
Output:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed: ssl-cert
Suggested packages:
procmail postfix-mysql postfix-pgsql postfix-ldap postfix-pcre sasl2-bin dovecot-common
postfix-cdb mail-reader postfix-doc openssl-blacklist
The following NEW packages will be installed:
postfix ssl-cert
0 upgraded, 2 newly installed, 0 to remove and 19 not upgraded.
Need to get 1,169 kB of archives.
After this operation, 3,759 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 ssl-cert all 1.0.37 [16.9 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 postfix amd64 3.1.0-3 [1,152 kB]
Fetched 1,169 kB in 2s (434 kB/s)
Preconfiguring packages ...
Selecting previously unselected package ssl-cert.
(Reading database ... 59373 files and directories currently installed.)
Preparing to unpack .../ssl-cert_1.0.37_all.deb ...
Unpacking ssl-cert (1.0.37) ...
Selecting previously unselected package postfix.
Preparing to unpack .../postfix_3.1.0-3_amd64.deb ...
Unpacking postfix (3.1.0-3) ...
Processing triggers for man-db (2.7.5-1) ...
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu7) ...
...
...
...
/etc/aliases does not exist, creating it.
WARNING: /etc/aliases exists, but does not have a root alias.
Postfix is now set up with a default configuration. If you need to make
changes, edit
/etc/postfix/main.cf (and others) as needed. To view Postfix configuration
values, see postconf(1).
After modifying main.cf, be sure to run '/etc/init.d/postfix reload'.
Running newaliases
Processing triggers for libc-bin (2.23-0ubuntu3) ...
Processing triggers for systemd (229-4ubuntu7) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for ufw (0.35-0ubuntu2) ...
Once the installation is started it will ask for the following.
General type of mail configuration. we have to select the Internet site.
Enter the domain name which we want to use with the postfix, System mail name (Ex mail.mydomain.com).
Once the installation is completed, we will check whether the services started or not to confirm we will run the below command.
$ netstat βntlp
netstat -ntlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 4212/sshd
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 5747/master
tcp6 0 0 :::22 :::* LISTEN 4212/sshd
tcp6 0 0 :::25 :::* LISTEN 5747/master
We should see that port 25 is open.
The postfix configuration is at the location /etc/postfix/main.cf
$ sudo vi /etc/postfix/main.cf
Output:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific: Specifying a file name will cause the first
# line of that file to be used as the name. The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no
# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = ubuntu16.mydomain.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, mail.mydomain.com, localhost.mydomain.com, , localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
General type of mail configuration?: Internet Site
System mail name: mydomain.com (not mail.mydomain.com)
Root and postmaster mail recipient: root
Other destinations to accept mail for: $myhostname, mydomain.com, mail.mydomain.com, localhost.mydomain.com, localhost
Force synchronous updates on mail queue?: No
Local networks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
Mailbox size limit: 0
Local address extension character: +
Internet protocols to use: all
If you want to reconfigure any time we can use the below command to make changes in the postfix configuration.
$ sudo dpkg-reconfigure postfix
Mapping Mail Boxes to the Linux Accounts.
We have to edit the virtual map files to map the mailboxes to the local Linux accounts, for that we needed to edit the below file.
$ sudo nano /etc/postfix/virtual
For example, if we want to accept the mails for noreply@mydomain.com and admin@mydomain.com we needed to add the below lines to the /etc/postfix/virtual file.
roreply@mydomain.com ubuntu
admin@mydomain.com ubuntu
Once the we add the setting to the configuration file we needed to apply these changes with the below command
$ sudo postmap /etc/postfix/virtual
After applying the settings we needed to restart the postfix services.
$ sudo systemctl restart postfix.
Before we start to install the mail client, we need to make sure that Mail environment is configured correctly. We have to set the variables in a few locations /etc/bash.bashrc and /etc/profile.d to make sure that user has the configured for Mail.
$ echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/mail.sh
Once the setting are configured we needed to load these settings to the current session.
$ source /etc/profile.d/mail.sh
By default the mail client is not installed, we needed to install the mail client with the following command β
$ apt install mailutils βy
To test the mail, we will login as a root and send email to the βubuntuβ user for that, we can use the below command β
# echo "test " | mail -s 'Test email subject line' ubuntu@mail.mydomain.com
To verify the email we have sent the email from root to ubuntu user on the local system
$ mail
Output:
"/var/mail/ubuntu": 2 messages 2 new
>N 1 Mail Delivery Syst Wed Oct 19 09:44 67/2299 Undelivered Mail Returned to Sender
N 2 root Wed Oct 19 09:45 12/490
? 2
Return-Path: <root@ubuntu16.example.com>
X-Original-To: ubuntu@ubuntu16.example.com
Delivered-To: ubuntu@ubuntu16.example.com
Received: by ubuntu16.example.com (Postfix, from userid 0)
id 5C631FF732; Wed, 19 Oct 2016 09:45:30 +0530 (IST)
To: <test@ubuntu16.example.com>,<ubuntu@ubuntu16.example.com>
X-Mailer: mail (GNU Mailutils 2.99.99)
Message-Id: <20161019041530.5C631FF732@ubuntu16.example.com>
Date: Wed, 19 Oct 2016 09:45:30 +0530 (IST)
From: root@ubuntu16.example.com (root)
test
?
You now see that we can receive emails from the root user.
In the above article, we have learned how to setup and configure a Postfix MTA (Mail Transport Agent) on Ubuntu 16.04, which can be used to send emails, using the above configuration we have the basic mail functionality to get started.
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "In this article we will learn about how to set up Postfix on Ubuntu 16.04, Postfix is a very popular open-source MTA (Mail Transfer Agent) which can be used to relay the emails on Ubuntu Linux systems, most of the public mail servers over the real world use the postfix only."
},
{
"code": null,
"e": 1384,
"s": 1338,
"text": "To complete this demo we needed the following"
},
{
"code": null,
"e": 1480,
"s": 1384,
"text": "A machine with Ubuntu 16.04 installed and a non-root user with sudo permissions on the machine."
},
{
"code": null,
"e": 1540,
"s": 1480,
"text": "A (FQDN) fully Qualified Domain Name points to the machine."
},
{
"code": null,
"e": 1584,
"s": 1540,
"text": "We assume the Domain FQDN mail.mydomain.com"
},
{
"code": null,
"e": 1676,
"s": 1584,
"text": "As Postfix is available with Ubuntu default repository we can directly go for installation."
},
{
"code": null,
"e": 1773,
"s": 1676,
"text": "Before we start the installation, we will first update the using the below command with apt-get."
},
{
"code": null,
"e": 1795,
"s": 1773,
"text": "$ sudo apt-get update"
},
{
"code": null,
"e": 1847,
"s": 1795,
"text": "Now we will install postfix with the below command."
},
{
"code": null,
"e": 3793,
"s": 1847,
"text": "$ sudo apt-get install postfix\nOutput:\nReading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following additional packages will be installed: ssl-cert\nSuggested packages:\nprocmail postfix-mysql postfix-pgsql postfix-ldap postfix-pcre sasl2-bin dovecot-common\npostfix-cdb mail-reader postfix-doc openssl-blacklist\nThe following NEW packages will be installed:\npostfix ssl-cert\n0 upgraded, 2 newly installed, 0 to remove and 19 not upgraded.\nNeed to get 1,169 kB of archives.\nAfter this operation, 3,759 kB of additional disk space will be used.\nDo you want to continue? [Y/n] y\nGet:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 ssl-cert all 1.0.37 [16.9 kB]\nGet:2 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 postfix amd64 3.1.0-3 [1,152 kB]\nFetched 1,169 kB in 2s (434 kB/s)\nPreconfiguring packages ...\nSelecting previously unselected package ssl-cert.\n(Reading database ... 59373 files and directories currently installed.)\nPreparing to unpack .../ssl-cert_1.0.37_all.deb ...\nUnpacking ssl-cert (1.0.37) ...\nSelecting previously unselected package postfix.\nPreparing to unpack .../postfix_3.1.0-3_amd64.deb ...\nUnpacking postfix (3.1.0-3) ...\nProcessing triggers for man-db (2.7.5-1) ...\nProcessing triggers for libc-bin (2.23-0ubuntu3) ...\nProcessing triggers for systemd (229-4ubuntu7) ...\n...\n...\n...\n/etc/aliases does not exist, creating it.\nWARNING: /etc/aliases exists, but does not have a root alias.\nPostfix is now set up with a default configuration. If you need to make\nchanges, edit\n/etc/postfix/main.cf (and others) as needed. To view Postfix configuration\nvalues, see postconf(1).\nAfter modifying main.cf, be sure to run '/etc/init.d/postfix reload'.\nRunning newaliases\nProcessing triggers for libc-bin (2.23-0ubuntu3) ...\nProcessing triggers for systemd (229-4ubuntu7) ...\nProcessing triggers for ureadahead (0.100.0-19) ...\nProcessing triggers for ufw (0.35-0ubuntu2) ..."
},
{
"code": null,
"e": 3857,
"s": 3793,
"text": "Once the installation is started it will ask for the following."
},
{
"code": null,
"e": 3930,
"s": 3857,
"text": "General type of mail configuration. we have to select the Internet site."
},
{
"code": null,
"e": 4032,
"s": 3930,
"text": "Enter the domain name which we want to use with the postfix, System mail name (Ex mail.mydomain.com)."
},
{
"code": null,
"e": 4160,
"s": 4032,
"text": "Once the installation is completed, we will check whether the services started or not to confirm we will run the below command."
},
{
"code": null,
"e": 4668,
"s": 4160,
"text": "$ netstat βntlp\nnetstat -ntlp\nActive Internet connections (only servers)\nProto Recv-Q Send-Q Local Address Foreign Address State PID/Program name\ntcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 4212/sshd\ntcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 5747/master\ntcp6 0 0 :::22 :::* LISTEN 4212/sshd\ntcp6 0 0 :::25 :::* LISTEN 5747/master"
},
{
"code": null,
"e": 4704,
"s": 4668,
"text": "We should see that port 25 is open."
},
{
"code": null,
"e": 4770,
"s": 4704,
"text": "The postfix configuration is at the location /etc/postfix/main.cf"
},
{
"code": null,
"e": 6175,
"s": 4770,
"text": "$ sudo vi /etc/postfix/main.cf\nOutput:\n# See /usr/share/postfix/main.cf.dist for a commented, more complete version\n# Debian specific: Specifying a file name will cause the first\n# line of that file to be used as the name. The Debian default\n# is /etc/mailname.\n#myorigin = /etc/mailname\nsmtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)\nbiff = no\n# appending .domain is the MUA's job.\nappend_dot_mydomain = no\n# Uncomment the next line to generate \"delayed mail\" warnings\n#delay_warning_time = 4h\nreadme_directory = no\n# TLS parameters\nsmtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem\nsmtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key\nsmtpd_use_tls=yes\nsmtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache\nsmtp_tls_session_cache_database = btree:${data_directory}/smtp_scache\n# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for\n# information on enabling SSL in the smtp client.\nsmtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination\nmyhostname = ubuntu16.mydomain.com\nalias_maps = hash:/etc/aliases\nalias_database = hash:/etc/aliases\nmyorigin = /etc/mailname\nmydestination = $myhostname, mail.mydomain.com, localhost.mydomain.com, , localhost\nrelayhost =\nmynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128\nmailbox_size_limit = 0\nrecipient_delimiter = +\ninet_interfaces = all\ninet_protocols = all"
},
{
"code": null,
"e": 6226,
"s": 6175,
"text": "General type of mail configuration?: Internet Site"
},
{
"code": null,
"e": 6281,
"s": 6226,
"text": "System mail name: mydomain.com (not mail.mydomain.com)"
},
{
"code": null,
"e": 6322,
"s": 6281,
"text": "Root and postmaster mail recipient: root"
},
{
"code": null,
"e": 6441,
"s": 6322,
"text": "Other destinations to accept mail for: $myhostname, mydomain.com, mail.mydomain.com, localhost.mydomain.com, localhost"
},
{
"code": null,
"e": 6486,
"s": 6441,
"text": "Force synchronous updates on mail queue?: No"
},
{
"code": null,
"e": 6547,
"s": 6486,
"text": "Local networks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128"
},
{
"code": null,
"e": 6569,
"s": 6547,
"text": "Mailbox size limit: 0"
},
{
"code": null,
"e": 6606,
"s": 6569,
"text": "Local address extension character: +"
},
{
"code": null,
"e": 6637,
"s": 6606,
"text": "Internet protocols to use: all"
},
{
"code": null,
"e": 6748,
"s": 6637,
"text": "If you want to reconfigure any time we can use the below command to make changes in the postfix configuration."
},
{
"code": null,
"e": 6780,
"s": 6748,
"text": "$ sudo dpkg-reconfigure postfix"
},
{
"code": null,
"e": 6822,
"s": 6780,
"text": "Mapping Mail Boxes to the Linux Accounts."
},
{
"code": null,
"e": 6953,
"s": 6822,
"text": "We have to edit the virtual map files to map the mailboxes to the local Linux accounts, for that we needed to edit the below file."
},
{
"code": null,
"e": 6986,
"s": 6953,
"text": "$ sudo nano /etc/postfix/virtual"
},
{
"code": null,
"e": 7145,
"s": 6986,
"text": "For example, if we want to accept the mails for noreply@mydomain.com and admin@mydomain.com we needed to add the below lines to the /etc/postfix/virtual file."
},
{
"code": null,
"e": 7199,
"s": 7145,
"text": "roreply@mydomain.com ubuntu\nadmin@mydomain.com ubuntu"
},
{
"code": null,
"e": 7309,
"s": 7199,
"text": "Once the we add the setting to the configuration file we needed to apply these changes with the below command"
},
{
"code": null,
"e": 7345,
"s": 7309,
"text": "$ sudo postmap /etc/postfix/virtual"
},
{
"code": null,
"e": 7416,
"s": 7345,
"text": "After applying the settings we needed to restart the postfix services."
},
{
"code": null,
"e": 7450,
"s": 7416,
"text": "$ sudo systemctl restart postfix."
},
{
"code": null,
"e": 7698,
"s": 7450,
"text": "Before we start to install the mail client, we need to make sure that Mail environment is configured correctly. We have to set the variables in a few locations /etc/bash.bashrc and /etc/profile.d to make sure that user has the configured for Mail."
},
{
"code": null,
"e": 7797,
"s": 7698,
"text": "$ echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/mail.sh"
},
{
"code": null,
"e": 7886,
"s": 7797,
"text": "Once the setting are configured we needed to load these settings to the current session."
},
{
"code": null,
"e": 7918,
"s": 7886,
"text": "$ source /etc/profile.d/mail.sh"
},
{
"code": null,
"e": 8029,
"s": 7918,
"text": "By default the mail client is not installed, we needed to install the mail client with the following command β"
},
{
"code": null,
"e": 8056,
"s": 8029,
"text": "$ apt install mailutils βy"
},
{
"code": null,
"e": 8175,
"s": 8056,
"text": "To test the mail, we will login as a root and send email to the βubuntuβ user for that, we can use the below command β"
},
{
"code": null,
"e": 8251,
"s": 8175,
"text": "# echo \"test \" | mail -s 'Test email subject line' ubuntu@mail.mydomain.com"
},
{
"code": null,
"e": 8339,
"s": 8251,
"text": "To verify the email we have sent the email from root to ubuntu user on the local system"
},
{
"code": null,
"e": 9003,
"s": 8339,
"text": "$ mail\nOutput:\n\"/var/mail/ubuntu\": 2 messages 2 new\n>N 1 Mail Delivery Syst Wed Oct 19 09:44 67/2299 Undelivered Mail Returned to Sender\nN 2 root Wed Oct 19 09:45 12/490\n? 2\nReturn-Path: <root@ubuntu16.example.com>\nX-Original-To: ubuntu@ubuntu16.example.com\nDelivered-To: ubuntu@ubuntu16.example.com\nReceived: by ubuntu16.example.com (Postfix, from userid 0)\nid 5C631FF732; Wed, 19 Oct 2016 09:45:30 +0530 (IST)\nTo: <test@ubuntu16.example.com>,<ubuntu@ubuntu16.example.com>\nX-Mailer: mail (GNU Mailutils 2.99.99)\nMessage-Id: <20161019041530.5C631FF732@ubuntu16.example.com>\nDate: Wed, 19 Oct 2016 09:45:30 +0530 (IST)\nFrom: root@ubuntu16.example.com (root)\ntest\n?"
},
{
"code": null,
"e": 9062,
"s": 9003,
"text": "You now see that we can receive emails from the root user."
},
{
"code": null,
"e": 9298,
"s": 9062,
"text": "In the above article, we have learned how to setup and configure a Postfix MTA (Mail Transport Agent) on Ubuntu 16.04, which can be used to send emails, using the above configuration we have the basic mail functionality to get started."
}
] |
Pairs with difference k | Practice | GeeksforGeeks
|
Given an array Arr of N positive integers. Find the number of pairs of integers whose difference is equal to a given number K.
Note: (a, b) and (b, a) are considered same. Also, same numbers at different indices are considered different.
Example 1:
Input:
N = 5
Arr[] = {1, 5, 3, 4, 2}
K = 3
Output: 2
Explanation: There are 2 pairs with difference 3,
the pairs are {1, 4} and {5, 2}
Example 2:
Input:
N = 6
Arr[] = {8, 12, 16, 4, 0, 20}
K = 4
Output: 5
Explanation: There are 5 pairs with difference 4,
the pairs are {0, 4}, {4, 8},
{8, 12}, {12, 16} and {16, 20}
Your Task:
You don't need to read input or print anything. Your task is to complete the function countPairsWithDiffK() which takes the array arr[], n and k as inputs and returns an integer denoting the answer.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(max(Arri))
Constraints:
1 <= N <= 105
0 <= K <= 105
0 <= Arri <= 105
-1
soumyabrata0242 months ago
Given input is wrong seems
3 0
2 3
leading test case failure
-1
chessnoobdj4 months ago
C++
int countPairsWithDiffK(int arr[], int n, int k) {
int maxEle = *max_element(arr, arr+n);
vector <int> hash(maxEle + 1, 0);
for (int i = 0; i < n; i++)
hash[arr[i]]++;
int count = 0;
for (int i = 0; i <= maxEle; i++) {
if (hash[i]) {
if (k == 0)
count += (hash[i] * (hash[i] - 1)) / 2;
else if (i + k <= maxEle)
count += (hash[i] * hash[i + k]);
}
}
return count;
}
0
shahzdor8 months ago
shahzdor
Python solution:Execution time:1.4 sec
from collections import Counterclass Solution: def countPairsWithDiffK(self,arr, n, k): if k==0: dict1=Counter(arr) count=0 for i in dict1: if dict1[i]>1: count+=(dict1[i]*(dict1[i]-1))/2 return int(count) else: arr.sort() dict1=dict() count=0 for i in arr: if i not in dict1: dict1[i]=1 if i-k in dict1: count+=dict1[i-k] else: dict1[i]+=1 if i-k in dict1: count+=dict1[i-k] return count
0
Arnav Singh11 months ago
Arnav Singh
int maxEle = 0; for (int i = 0; i < n; i++) { maxEle = max(maxEle, arr[i]); } vector<int> hash(maxEle + 1, 0); for (int i = 0; i < n; i++) { hash[arr[i]]++; } int count = 0; for (int i = 0; i <= maxEle; i++) { if (hash[i]) { if (i == i + k) { count += (hash[i] * (hash[i] - 1)) / 2; } else if (i + k <= maxEle) { count += (hash[i] * hash[i + k]); } } } return count;}
0
Hemakshi Manchandia2 years ago
Hemakshi Manchandia
I am getting TLE by using map. Is there any other better approach to solve this
0
shourya2 years ago
shourya
I am getting segmentation fault please tell ??int countPairsWithDiffK(int arr[], int n, int k) { int maxi =0 ; for(int i=0 ; i<n ;i++){="" if(arr[i]="">maxi) maxi=arr[i]; } int a[maxi+1]={0}; for(int i=0 ; i<n ;i++){="" a[arr[i]]++;="" }="" int="" count="0" ;="" for(int="" i="0" ;="" i<maxi+1="" ;i++){="" if(i+k="">maxi) break; if(k==0 && a[i]>0){ count+=(int)(a[i]*(a[i]-1))/2; } else if(k!=0 && a[i]>0 && a[i+k]>0 ){ count+=a[i]*a[i+k]; } } return count;}
0
Goutham Reddy2 years ago
Goutham Reddy
@GeeksforGeeks
I have a doubt
when input is:15 02 2 2 2 2is the output:20(or)output:25??
0
krishnaballabh2 years ago
krishnaballabh
for i in range(int(input())): n,k = map(int,input().split()) l = list(map(int,input().split())) c = 0 for i in range(0,len(l)-1): for j in range(i+1,len(l)): if abs(l[i]-l[j]) == k: c+=1 print(c)
0
krishnaballabh2 years ago
krishnaballabh
#code#time 0.05for i in range(int(input())): n,k = map(int,input().split()) l = list(map(int,input().split())) c = 0 for i in range(0,len(l)-1): for j in range(i+1,len(l)): if abs(l[i]-l[j]) == k: c+=1 print(c)
0
Shivam Bhardwaj2 years ago
Shivam Bhardwaj
simple c++ solution using differencetime: 0.01https://ide.geeksforgeeks.o...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 476,
"s": 238,
"text": "Given an array Arr of N positive integers. Find the number of pairs of integers whose difference is equal to a given number K.\nNote: (a, b) and (b, a) are considered same. Also, same numbers at different indices are considered different."
},
{
"code": null,
"e": 487,
"s": 476,
"text": "Example 1:"
},
{
"code": null,
"e": 638,
"s": 487,
"text": "Input: \nN = 5\nArr[] = {1, 5, 3, 4, 2}\nK = 3\nOutput: 2\nExplanation: There are 2 pairs with difference 3, \n the pairs are {1, 4} and {5, 2} "
},
{
"code": null,
"e": 649,
"s": 638,
"text": "Example 2:"
},
{
"code": null,
"e": 849,
"s": 649,
"text": "Input: \nN = 6\nArr[] = {8, 12, 16, 4, 0, 20}\nK = 4\nOutput: 5\nExplanation: There are 5 pairs with difference 4, \n the pairs are {0, 4}, {4, 8}, \n {8, 12}, {12, 16} and {16, 20} "
},
{
"code": null,
"e": 1132,
"s": 849,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function countPairsWithDiffK() which takes the array arr[], n and k as inputs and returns an integer denoting the answer.\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(max(Arri))"
},
{
"code": null,
"e": 1190,
"s": 1132,
"text": "Constraints:\n1 <= N <= 105\n0 <= K <= 105\n0 <= Arri <= 105"
},
{
"code": null,
"e": 1195,
"s": 1192,
"text": "-1"
},
{
"code": null,
"e": 1222,
"s": 1195,
"text": "soumyabrata0242 months ago"
},
{
"code": null,
"e": 1249,
"s": 1222,
"text": "Given input is wrong seems"
},
{
"code": null,
"e": 1254,
"s": 1249,
"text": "3 0 "
},
{
"code": null,
"e": 1258,
"s": 1254,
"text": "2 3"
},
{
"code": null,
"e": 1286,
"s": 1260,
"text": "leading test case failure"
},
{
"code": null,
"e": 1289,
"s": 1286,
"text": "-1"
},
{
"code": null,
"e": 1313,
"s": 1289,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 1317,
"s": 1313,
"text": "C++"
},
{
"code": null,
"e": 1785,
"s": 1317,
"text": "int countPairsWithDiffK(int arr[], int n, int k) {\n\tint maxEle = *max_element(arr, arr+n);\n\tvector <int> hash(maxEle + 1, 0);\n for (int i = 0; i < n; i++)\n hash[arr[i]]++;\n int count = 0;\n for (int i = 0; i <= maxEle; i++) {\n if (hash[i]) {\n if (k == 0)\n count += (hash[i] * (hash[i] - 1)) / 2;\n else if (i + k <= maxEle)\n count += (hash[i] * hash[i + k]);\n }\n }\n return count;\n}"
},
{
"code": null,
"e": 1787,
"s": 1785,
"text": "0"
},
{
"code": null,
"e": 1808,
"s": 1787,
"text": "shahzdor8 months ago"
},
{
"code": null,
"e": 1817,
"s": 1808,
"text": "shahzdor"
},
{
"code": null,
"e": 1856,
"s": 1817,
"text": "Python solution:Execution time:1.4 sec"
},
{
"code": null,
"e": 2387,
"s": 1856,
"text": "from collections import Counterclass Solution: def countPairsWithDiffK(self,arr, n, k): if k==0: dict1=Counter(arr) count=0 for i in dict1: if dict1[i]>1: count+=(dict1[i]*(dict1[i]-1))/2 return int(count) else: arr.sort() dict1=dict() count=0 for i in arr: if i not in dict1: dict1[i]=1 if i-k in dict1: count+=dict1[i-k] else: dict1[i]+=1 if i-k in dict1: count+=dict1[i-k] return count"
},
{
"code": null,
"e": 2389,
"s": 2387,
"text": "0"
},
{
"code": null,
"e": 2414,
"s": 2389,
"text": "Arnav Singh11 months ago"
},
{
"code": null,
"e": 2426,
"s": 2414,
"text": "Arnav Singh"
},
{
"code": null,
"e": 2912,
"s": 2426,
"text": "int maxEle = 0; for (int i = 0; i < n; i++) { maxEle = max(maxEle, arr[i]); } vector<int> hash(maxEle + 1, 0); for (int i = 0; i < n; i++) { hash[arr[i]]++; } int count = 0; for (int i = 0; i <= maxEle; i++) { if (hash[i]) { if (i == i + k) { count += (hash[i] * (hash[i] - 1)) / 2; } else if (i + k <= maxEle) { count += (hash[i] * hash[i + k]); } } } return count;}"
},
{
"code": null,
"e": 2914,
"s": 2912,
"text": "0"
},
{
"code": null,
"e": 2945,
"s": 2914,
"text": "Hemakshi Manchandia2 years ago"
},
{
"code": null,
"e": 2965,
"s": 2945,
"text": "Hemakshi Manchandia"
},
{
"code": null,
"e": 3045,
"s": 2965,
"text": "I am getting TLE by using map. Is there any other better approach to solve this"
},
{
"code": null,
"e": 3047,
"s": 3045,
"text": "0"
},
{
"code": null,
"e": 3066,
"s": 3047,
"text": "shourya2 years ago"
},
{
"code": null,
"e": 3074,
"s": 3066,
"text": "shourya"
},
{
"code": null,
"e": 3627,
"s": 3074,
"text": "I am getting segmentation fault please tell ??int countPairsWithDiffK(int arr[], int n, int k) { int maxi =0 ; for(int i=0 ; i<n ;i++){=\"\" if(arr[i]=\"\">maxi) maxi=arr[i]; } int a[maxi+1]={0}; for(int i=0 ; i<n ;i++){=\"\" a[arr[i]]++;=\"\" }=\"\" int=\"\" count=\"0\" ;=\"\" for(int=\"\" i=\"0\" ;=\"\" i<maxi+1=\"\" ;i++){=\"\" if(i+k=\"\">maxi) break; if(k==0 && a[i]>0){ count+=(int)(a[i]*(a[i]-1))/2; } else if(k!=0 && a[i]>0 && a[i+k]>0 ){ count+=a[i]*a[i+k]; } } return count;}"
},
{
"code": null,
"e": 3629,
"s": 3627,
"text": "0"
},
{
"code": null,
"e": 3654,
"s": 3629,
"text": "Goutham Reddy2 years ago"
},
{
"code": null,
"e": 3668,
"s": 3654,
"text": "Goutham Reddy"
},
{
"code": null,
"e": 3683,
"s": 3668,
"text": "@GeeksforGeeks"
},
{
"code": null,
"e": 3698,
"s": 3683,
"text": "I have a doubt"
},
{
"code": null,
"e": 3757,
"s": 3698,
"text": "when input is:15 02 2 2 2 2is the output:20(or)output:25??"
},
{
"code": null,
"e": 3759,
"s": 3757,
"text": "0"
},
{
"code": null,
"e": 3785,
"s": 3759,
"text": "krishnaballabh2 years ago"
},
{
"code": null,
"e": 3800,
"s": 3785,
"text": "krishnaballabh"
},
{
"code": null,
"e": 4044,
"s": 3800,
"text": "for i in range(int(input())): n,k = map(int,input().split()) l = list(map(int,input().split())) c = 0 for i in range(0,len(l)-1): for j in range(i+1,len(l)): if abs(l[i]-l[j]) == k: c+=1 print(c)"
},
{
"code": null,
"e": 4046,
"s": 4044,
"text": "0"
},
{
"code": null,
"e": 4072,
"s": 4046,
"text": "krishnaballabh2 years ago"
},
{
"code": null,
"e": 4087,
"s": 4072,
"text": "krishnaballabh"
},
{
"code": null,
"e": 4346,
"s": 4087,
"text": "#code#time 0.05for i in range(int(input())): n,k = map(int,input().split()) l = list(map(int,input().split())) c = 0 for i in range(0,len(l)-1): for j in range(i+1,len(l)): if abs(l[i]-l[j]) == k: c+=1 print(c)"
},
{
"code": null,
"e": 4348,
"s": 4346,
"text": "0"
},
{
"code": null,
"e": 4375,
"s": 4348,
"text": "Shivam Bhardwaj2 years ago"
},
{
"code": null,
"e": 4391,
"s": 4375,
"text": "Shivam Bhardwaj"
},
{
"code": null,
"e": 4468,
"s": 4391,
"text": "simple c++ solution using differencetime: 0.01https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4614,
"s": 4468,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4650,
"s": 4614,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4660,
"s": 4650,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4670,
"s": 4660,
"text": "\nContest\n"
},
{
"code": null,
"e": 4733,
"s": 4670,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4881,
"s": 4733,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5089,
"s": 4881,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5195,
"s": 5089,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JSON Parsing in Android using Retrofit Library - GeeksforGeeks
|
23 Nov, 2021
JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using the Retrofit library in Android.
Note: To parse JSON object in android using Voley library please refer to JSON Parsing in Android using Volley Library
JSON Object: Json Object can be easily identified with β{β braces opening and β}β braces closing. We can fetch data from JSON objects with their key value. From that key, we can access the value of that key.
We will be building a simple application in which we will be displaying a simple CardView in which we will display a single course that is available on Geeks for Geeks. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Below is the JSON object from which we will be displaying the data in our Android App.
{
βcourseNameβ:βFork CPPβ,
βcourseimgβ:βhttps://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.pngβ,
βcourseModeβ:βOnline Batchβ,
βcourseTracksβ:β6 Tracksβ
}
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below dependency for using retrofit.
implementation βcom.squareup.retrofit2:retrofit:2.9.0β
implementation βcom.squareup.retrofit2:converter-gson:2.5.0β
// below dependency for using picasso image loading library
implementation βcom.squareup.picasso:picasso:2.71828β
After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <androidx.cardview.widget.CardView android:id="@+id/idCVCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:elevation="10dp" android:visibility="gone" app:cardCornerRadius="8dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/idIVCourse" android:layout_width="match_parent" android:layout_height="300dp" android:layout_margin="5dp" /> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="5dp" android:text="Course Name " android:textColor="@color/black" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" android:weightSum="2"> <TextView android:id="@+id/idTVBatch" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Batch" android:textColor="@color/black" /> <TextView android:id="@+id/idTVTracks" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" android:text="Tracks" android:textColor="@color/black" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <ProgressBar android:id="@+id/idLoadingPB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="visible" /> </RelativeLayout>
Step 5: Creating a modal class for storing our data
Navigate to the app > java > your appβs package name > Right-click on it > New > Java class and name it as RecyclerData and add the below code to it. Comments are added inside the code to understand the code in more detail.
Java
public class RecyclerData { // string variables for our data // make sure that the variable name // must be similar to that of key value // which we are getting from our json file. private String courseName; private String courseimg; private String courseMode; private String courseTracks; public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseimg() { return courseimg; } public void setCourseimg(String courseimg) { this.courseimg = courseimg; } public String getCourseMode() { return courseMode; } public void setCourseMode(String courseMode) { this.courseMode = courseMode; } public String getCourseTracks() { return courseTracks; } public void setCourseTracks(String courseTracks) { this.courseTracks = courseTracks; } public RecyclerData(String courseName, String courseimg, String courseMode, String courseTracks) { this.courseName = courseName; this.courseimg = courseimg; this.courseMode = courseMode; this.courseTracks = courseTracks; }}
Step 6: Creating an Interface class for our API Call
Navigate to the app > java > your appβs package name > Right-click on it > New > Java class select it as Interface and name the file as RetrofitAPI and add below code to it. Comments are added inside the code to understand the code in more detail.
Java
import retrofit2.Call;import retrofit2.http.GET; public interface RetrofitAPI { // as we are making get request // so we are displaying GET as annotation. // and inside we are passing // last parameter for our url. @GET("63OH") // as we are calling data from array // so we are calling it with json object // and naming that method as getCourse(); Call<RecyclerData> getCourse();}
Step 7: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; import com.squareup.picasso.Picasso; import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { // creating variables for our textview, // imageview,cardview and progressbar. private TextView courseNameTV, courseTracksTV, courseBatchTV; private ImageView courseIV; private ProgressBar loadingPB; private CardView courseCV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. loadingPB = findViewById(R.id.idLoadingPB); courseCV = findViewById(R.id.idCVCourse); courseNameTV = findViewById(R.id.idTVCourseName); courseTracksTV = findViewById(R.id.idTVTracks); courseBatchTV = findViewById(R.id.idTVBatch); courseIV = findViewById(R.id.idIVCourse); getCourse(); } private void getCourse() { // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://jsonkeeper.com/b/") // on below line we are calling add Converter // factory as GSON converter factory. .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); Call<RecyclerData> call = retrofitAPI.getCourse(); call.enqueue(new Callback<RecyclerData>() { @Override public void onResponse(Call<RecyclerData> call, Response<RecyclerData> response) { if (response.isSuccessful()) { // inside the on response method. // we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // in below line we are making our card // view visible after we get all the data. courseCV.setVisibility(View.VISIBLE); RecyclerData modal = response.body(); // after extracting all the data we are // setting that data to all our views. courseNameTV.setText(modal.getCourseName()); courseTracksTV.setText(modal.getCourseTracks()); courseBatchTV.setText(modal.getCourseMode()); // we are using picasso to load the image from url. Picasso.get().load(modal.getCourseimg()).into(courseIV); } } @Override public void onFailure(Call<RecyclerData> call, Throwable t) { // displaying an error message in toast Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show(); } }); }}
Now run your app and see the output of the app.
kapoorsagar226
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
CardView in Android With Example
Content Providers in Android with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24671,
"s": 24643,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 25067,
"s": 24671,
"text": "JSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using the Retrofit library in Android. "
},
{
"code": null,
"e": 25186,
"s": 25067,
"text": "Note: To parse JSON object in android using Voley library please refer to JSON Parsing in Android using Volley Library"
},
{
"code": null,
"e": 25396,
"s": 25186,
"text": "JSON Object: Json Object can be easily identified with β{β braces opening and β}β braces closing. We can fetch data from JSON objects with their key value. From that key, we can access the value of that key. "
},
{
"code": null,
"e": 25733,
"s": 25396,
"text": "We will be building a simple application in which we will be displaying a simple CardView in which we will display a single course that is available on Geeks for Geeks. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25822,
"s": 25733,
"text": "Below is the JSON object from which we will be displaying the data in our Android App. "
},
{
"code": null,
"e": 25824,
"s": 25822,
"text": "{"
},
{
"code": null,
"e": 25850,
"s": 25824,
"text": " βcourseNameβ:βFork CPPβ,"
},
{
"code": null,
"e": 25941,
"s": 25850,
"text": " βcourseimgβ:βhttps://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.pngβ,"
},
{
"code": null,
"e": 25971,
"s": 25941,
"text": " βcourseModeβ:βOnline Batchβ,"
},
{
"code": null,
"e": 25998,
"s": 25971,
"text": " βcourseTracksβ:β6 Tracksβ"
},
{
"code": null,
"e": 26000,
"s": 25998,
"text": "}"
},
{
"code": null,
"e": 26029,
"s": 26000,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26191,
"s": 26029,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26250,
"s": 26191,
"text": "Step 2: Add the below dependency in your build.gradle file"
},
{
"code": null,
"e": 26548,
"s": 26250,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. "
},
{
"code": null,
"e": 26588,
"s": 26548,
"text": "// below dependency for using retrofit."
},
{
"code": null,
"e": 26643,
"s": 26588,
"text": "implementation βcom.squareup.retrofit2:retrofit:2.9.0β"
},
{
"code": null,
"e": 26704,
"s": 26643,
"text": "implementation βcom.squareup.retrofit2:converter-gson:2.5.0β"
},
{
"code": null,
"e": 26764,
"s": 26704,
"text": "// below dependency for using picasso image loading library"
},
{
"code": null,
"e": 26818,
"s": 26764,
"text": "implementation βcom.squareup.picasso:picasso:2.71828β"
},
{
"code": null,
"e": 26918,
"s": 26818,
"text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. "
},
{
"code": null,
"e": 26993,
"s": 26918,
"text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file"
},
{
"code": null,
"e": 27066,
"s": 26993,
"text": "Navigate to the app > AndroidManifest.xml and add the below code to it. "
},
{
"code": null,
"e": 27070,
"s": 27066,
"text": "XML"
},
{
"code": "<!--permissions for INTERNET--><uses-permission android:name=\"android.permission.INTERNET\"/>",
"e": 27163,
"s": 27070,
"text": null
},
{
"code": null,
"e": 27211,
"s": 27163,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27354,
"s": 27211,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 27358,
"s": 27354,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <androidx.cardview.widget.CardView android:id=\"@+id/idCVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:elevation=\"10dp\" android:visibility=\"gone\" app:cardCornerRadius=\"8dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <ImageView android:id=\"@+id/idIVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_margin=\"5dp\" /> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:padding=\"5dp\" android:text=\"Course Name \" android:textColor=\"@color/black\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <TextView android:id=\"@+id/idTVBatch\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Batch\" android:textColor=\"@color/black\" /> <TextView android:id=\"@+id/idTVTracks\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:padding=\"5dp\" android:text=\"Tracks\" android:textColor=\"@color/black\" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <ProgressBar android:id=\"@+id/idLoadingPB\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:visibility=\"visible\" /> </RelativeLayout>",
"e": 30206,
"s": 27358,
"text": null
},
{
"code": null,
"e": 30258,
"s": 30206,
"text": "Step 5: Creating a modal class for storing our data"
},
{
"code": null,
"e": 30482,
"s": 30258,
"text": "Navigate to the app > java > your appβs package name > Right-click on it > New > Java class and name it as RecyclerData and add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 30487,
"s": 30482,
"text": "Java"
},
{
"code": "public class RecyclerData { // string variables for our data // make sure that the variable name // must be similar to that of key value // which we are getting from our json file. private String courseName; private String courseimg; private String courseMode; private String courseTracks; public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseimg() { return courseimg; } public void setCourseimg(String courseimg) { this.courseimg = courseimg; } public String getCourseMode() { return courseMode; } public void setCourseMode(String courseMode) { this.courseMode = courseMode; } public String getCourseTracks() { return courseTracks; } public void setCourseTracks(String courseTracks) { this.courseTracks = courseTracks; } public RecyclerData(String courseName, String courseimg, String courseMode, String courseTracks) { this.courseName = courseName; this.courseimg = courseimg; this.courseMode = courseMode; this.courseTracks = courseTracks; }}",
"e": 31717,
"s": 30487,
"text": null
},
{
"code": null,
"e": 31770,
"s": 31717,
"text": "Step 6: Creating an Interface class for our API Call"
},
{
"code": null,
"e": 32018,
"s": 31770,
"text": "Navigate to the app > java > your appβs package name > Right-click on it > New > Java class select it as Interface and name the file as RetrofitAPI and add below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32023,
"s": 32018,
"text": "Java"
},
{
"code": "import retrofit2.Call;import retrofit2.http.GET; public interface RetrofitAPI { // as we are making get request // so we are displaying GET as annotation. // and inside we are passing // last parameter for our url. @GET(\"63OH\") // as we are calling data from array // so we are calling it with json object // and naming that method as getCourse(); Call<RecyclerData> getCourse();}",
"e": 32442,
"s": 32023,
"text": null
},
{
"code": null,
"e": 32490,
"s": 32442,
"text": "Step 7: Working with the MainActivity.java file"
},
{
"code": null,
"e": 32680,
"s": 32490,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 32685,
"s": 32680,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.cardview.widget.CardView; import com.squareup.picasso.Picasso; import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { // creating variables for our textview, // imageview,cardview and progressbar. private TextView courseNameTV, courseTracksTV, courseBatchTV; private ImageView courseIV; private ProgressBar loadingPB; private CardView courseCV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. loadingPB = findViewById(R.id.idLoadingPB); courseCV = findViewById(R.id.idCVCourse); courseNameTV = findViewById(R.id.idTVCourseName); courseTracksTV = findViewById(R.id.idTVTracks); courseBatchTV = findViewById(R.id.idTVBatch); courseIV = findViewById(R.id.idIVCourse); getCourse(); } private void getCourse() { // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit = new Retrofit.Builder() .baseUrl(\"https://jsonkeeper.com/b/\") // on below line we are calling add Converter // factory as GSON converter factory. .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); Call<RecyclerData> call = retrofitAPI.getCourse(); call.enqueue(new Callback<RecyclerData>() { @Override public void onResponse(Call<RecyclerData> call, Response<RecyclerData> response) { if (response.isSuccessful()) { // inside the on response method. // we are hiding our progress bar. loadingPB.setVisibility(View.GONE); // in below line we are making our card // view visible after we get all the data. courseCV.setVisibility(View.VISIBLE); RecyclerData modal = response.body(); // after extracting all the data we are // setting that data to all our views. courseNameTV.setText(modal.getCourseName()); courseTracksTV.setText(modal.getCourseTracks()); courseBatchTV.setText(modal.getCourseMode()); // we are using picasso to load the image from url. Picasso.get().load(modal.getCourseimg()).into(courseIV); } } @Override public void onFailure(Call<RecyclerData> call, Throwable t) { // displaying an error message in toast Toast.makeText(MainActivity.this, \"Fail to get the data..\", Toast.LENGTH_SHORT).show(); } }); }}",
"e": 36079,
"s": 32685,
"text": null
},
{
"code": null,
"e": 36128,
"s": 36079,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 36143,
"s": 36128,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 36151,
"s": 36143,
"text": "android"
},
{
"code": null,
"e": 36175,
"s": 36151,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36183,
"s": 36175,
"text": "Android"
},
{
"code": null,
"e": 36188,
"s": 36183,
"text": "Java"
},
{
"code": null,
"e": 36207,
"s": 36188,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36212,
"s": 36207,
"text": "Java"
},
{
"code": null,
"e": 36220,
"s": 36212,
"text": "Android"
},
{
"code": null,
"e": 36318,
"s": 36220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36327,
"s": 36318,
"text": "Comments"
},
{
"code": null,
"e": 36340,
"s": 36327,
"text": "Old Comments"
},
{
"code": null,
"e": 36398,
"s": 36340,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 36441,
"s": 36398,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 36472,
"s": 36441,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 36505,
"s": 36472,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 36547,
"s": 36505,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 36562,
"s": 36547,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36606,
"s": 36562,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36628,
"s": 36606,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36653,
"s": 36628,
"text": "Reverse a string in Java"
}
] |
Convert VARCHAR data to MySQL date format?
|
To convert VARCHAR data to date format, you can use STR_TO_DATE() β
mysql> create table DemoTable1989
(
DueDate varchar(20)
);
Query OK, 0 rows affected (0.91 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable1989 values('31/01/2015');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1989 values('01/12/2018');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1989 values('25/10/2019');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement β
mysql> select * from DemoTable1989;
This will produce the following output β
+------------+
| DueDate |
+------------+
| 31/01/2015 |
| 01/12/2018 |
| 25/10/2019 |
+------------+
3 rows in set (0.00 sec)
Here is the query to convert date data into MySQL date format:
mysql> select str_to_date(DueDate,'%d/%m/%Y') as MySQLDateFormat from DemoTable1989;
This will produce the following output β
+-----------------+
| MySQLDateFormat |
+-----------------+
| 2015-01-31 |
| 2018-12-01 |
| 2019-10-25 |
+-----------------+
3 rows in set (0.05 sec)
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To convert VARCHAR data to date format, you can use STR_TO_DATE() β"
},
{
"code": null,
"e": 1235,
"s": 1130,
"text": "mysql> create table DemoTable1989\n (\n DueDate varchar(20)\n );\nQuery OK, 0 rows affected (0.91 sec)"
},
{
"code": null,
"e": 1291,
"s": 1235,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1564,
"s": 1291,
"text": "mysql> insert into DemoTable1989 values('31/01/2015');\nQuery OK, 1 row affected (0.52 sec)\nmysql> insert into DemoTable1989 values('01/12/2018');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable1989 values('25/10/2019');\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 1624,
"s": 1564,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1660,
"s": 1624,
"text": "mysql> select * from DemoTable1989;"
},
{
"code": null,
"e": 1701,
"s": 1660,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1831,
"s": 1701,
"text": "+------------+\n| DueDate |\n+------------+\n| 31/01/2015 |\n| 01/12/2018 |\n| 25/10/2019 |\n+------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1894,
"s": 1831,
"text": "Here is the query to convert date data into MySQL date format:"
},
{
"code": null,
"e": 1979,
"s": 1894,
"text": "mysql> select str_to_date(DueDate,'%d/%m/%Y') as MySQLDateFormat from DemoTable1989;"
},
{
"code": null,
"e": 2020,
"s": 1979,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2185,
"s": 2020,
"text": "+-----------------+\n| MySQLDateFormat |\n+-----------------+\n| 2015-01-31 |\n| 2018-12-01 |\n| 2019-10-25 |\n+-----------------+\n3 rows in set (0.05 sec)"
}
] |
Bulma - Hero banner
|
Bulma provides hero banner to specify the full width banner to the webpage. Bulma uses hero class as container and hero-body as child, where you can add your page content.
Let's create a simple example of hero banner by using hero class as shown below β
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Bulma Hero Banner Example</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
</head>
<body>
<section class = "section">
<div class = "container">
<span class = "title">
Simple Hero Banner
</span>
<br>
<br>
<section class = "hero is-info">
<div class = "hero-body">
<div class = "container">
<h1 class = "title">
Tutorialspoint (Main title)
</h1>
<h2 class = "subtitle">
Online Learning (Subtitle)
</h2>
</div>
</div>
</section>
</div>
</section>
</body>
</html>
It displays the below output β
Bulma allows creating transitions between two or more colors, which are used to fill a specified region by using is-bold modifier.
Let's create a simple example for gradients by using is-bold modifier as shown below β
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Bulma Hero Banner Example</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
</head>
<body>
<section class = "section">
<div class = "container">
<span class = "title">
Gradients
</span>
<br>
<br>
<section class = "hero is-warning is-bold">
<div class = "hero-body">
<div class = "container">
<h1 class = "title">Tutorialspoint (Main title)</h1>
<h2 class = "subtitle">Online Learning (Subtitle)</h2>
</div>
</div>
</section>
</div>
</section>
</body>
</html>
It displays the below output β
The full height hero banner contains 3 vertical parts β
hero-head β It specifies top part of the hero banner.
hero-head β It specifies top part of the hero banner.
hero-body β It specifies body part of the hero banner, which is vertically centered.
hero-body β It specifies body part of the hero banner, which is vertically centered.
hero-foot β It specifies bottom part of the hero banner.
hero-foot β It specifies bottom part of the hero banner.
The below example specifies usage of above 3 parts of full height hero as shown below β
Note β Resize the coding-ground output window to see the changes occurring according to window size.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<title>Bulma Hero Banner Example</title>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<script src = "https://use.fontawesome.com/releases/v5.1.0/js/all.js"></script>
</head>
<body>
<section class = "section">
<div class = "container">
<span class = "title">
Full Height Hero
</span>
<br>
<br>
<section class = "hero is-primary is-medium">
<!-- Hero head at the top -->
<div class = "hero-head">
<nav class = "navbar">
<div class = "container">
<div class = "navbar-brand">
<a class = "navbar-item">
<img alt="tutorialspoint" src = "https://www.tutorialspoint.com/bootstrap/images/logo.png" height = "300" width = "200">
</a>
<span class = "navbar-burger burger" data-target = "navbarmenu">
<span></span>
<span></span>
<span></span>
</span>
</div>
<div id = "navbarmenu" class = "navbar-menu">
<div class = "navbar-end">
<a class = "navbar-item is-active">Home</a>
<a class = "navbar-item">AboutUs</a>
<a class = "navbar-item">Services</a>
</div>
</div>
</div>
</nav>
</div>
<!-- Hero content in the middle -->
<div class = "hero-body">
<div class = "container has-text-centered">
<h1 class = "title">Tutorialspoint (Main title)</h1>
<h2 class = "subtitle">Online Learning (Subtitle)</h2>
</div>
</div>
<!-- Hero footer at the bottom -->
<div class = "hero-foot is-info">
<nav class = "tabs">
<div class = "container">
<ul>
<li class = "is-active"><a>Help</a></li>
<li><a>FAQ's</a></li>
<li><a>Privacy</a></li>
<li><a>Feedback</a></li>
<li><a>Terms</a></li>
</ul>
</div>
</nav>
</div>
</section>
</div>
</section>
</body>
</html>
It displays the below output β
Help
FAQ's
Privacy
Feedback
Terms
You can also display the full height hero as large and fullwidth by using is-large and is-fullheight classes. Use these classes by replacing is-medium class in the section tag.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1870,
"s": 1698,
"text": "Bulma provides hero banner to specify the full width banner to the webpage. Bulma uses hero class as container and hero-body as child, where you can add your page content."
},
{
"code": null,
"e": 1952,
"s": 1870,
"text": "Let's create a simple example of hero banner by using hero class as shown below β"
},
{
"code": null,
"e": 3085,
"s": 1952,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Hero Banner Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"title\">\n Simple Hero Banner\n </span>\n <br>\n <br>\n \n <section class = \"hero is-info\">\n <div class = \"hero-body\">\n <div class = \"container\">\n <h1 class = \"title\">\n Tutorialspoint (Main title)\n </h1>\n <h2 class = \"subtitle\">\n Online Learning (Subtitle)\n </h2>\n </div>\n </div>\n </section>\n \n </div>\n </section>\n </body>\n \n</html>"
},
{
"code": null,
"e": 3116,
"s": 3085,
"text": "It displays the below output β"
},
{
"code": null,
"e": 3247,
"s": 3116,
"text": "Bulma allows creating transitions between two or more colors, which are used to fill a specified region by using is-bold modifier."
},
{
"code": null,
"e": 3334,
"s": 3247,
"text": "Let's create a simple example for gradients by using is-bold modifier as shown below β"
},
{
"code": null,
"e": 4375,
"s": 3334,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Hero Banner Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"title\">\n Gradients\n </span>\n <br>\n <br>\n \n <section class = \"hero is-warning is-bold\">\n <div class = \"hero-body\">\n <div class = \"container\">\n <h1 class = \"title\">Tutorialspoint (Main title)</h1>\n <h2 class = \"subtitle\">Online Learning (Subtitle)</h2>\n </div>\n </div>\n </section>\n \n </div>\n </section>\n </body>\n \n</html>"
},
{
"code": null,
"e": 4406,
"s": 4375,
"text": "It displays the below output β"
},
{
"code": null,
"e": 4462,
"s": 4406,
"text": "The full height hero banner contains 3 vertical parts β"
},
{
"code": null,
"e": 4516,
"s": 4462,
"text": "hero-head β It specifies top part of the hero banner."
},
{
"code": null,
"e": 4570,
"s": 4516,
"text": "hero-head β It specifies top part of the hero banner."
},
{
"code": null,
"e": 4655,
"s": 4570,
"text": "hero-body β It specifies body part of the hero banner, which is vertically centered."
},
{
"code": null,
"e": 4740,
"s": 4655,
"text": "hero-body β It specifies body part of the hero banner, which is vertically centered."
},
{
"code": null,
"e": 4797,
"s": 4740,
"text": "hero-foot β It specifies bottom part of the hero banner."
},
{
"code": null,
"e": 4854,
"s": 4797,
"text": "hero-foot β It specifies bottom part of the hero banner."
},
{
"code": null,
"e": 4942,
"s": 4854,
"text": "The below example specifies usage of above 3 parts of full height hero as shown below β"
},
{
"code": null,
"e": 5043,
"s": 4942,
"text": "Note β Resize the coding-ground output window to see the changes occurring according to window size."
},
{
"code": null,
"e": 8064,
"s": 5043,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <title>Bulma Hero Banner Example</title>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css\">\n <script src = \"https://use.fontawesome.com/releases/v5.1.0/js/all.js\"></script>\n </head>\n \n <body>\n <section class = \"section\">\n <div class = \"container\">\n <span class = \"title\">\n Full Height Hero\n </span>\n <br>\n <br>\n \n <section class = \"hero is-primary is-medium\">\n <!-- Hero head at the top -->\n <div class = \"hero-head\">\n <nav class = \"navbar\">\n <div class = \"container\">\n <div class = \"navbar-brand\">\n <a class = \"navbar-item\">\n <img alt=\"tutorialspoint\" src = \"https://www.tutorialspoint.com/bootstrap/images/logo.png\" height = \"300\" width = \"200\">\n </a>\n <span class = \"navbar-burger burger\" data-target = \"navbarmenu\">\n <span></span>\n <span></span>\n <span></span>\n </span>\n </div>\n \n <div id = \"navbarmenu\" class = \"navbar-menu\">\n <div class = \"navbar-end\">\n <a class = \"navbar-item is-active\">Home</a>\n <a class = \"navbar-item\">AboutUs</a>\n <a class = \"navbar-item\">Services</a>\n </div>\n </div>\n \n </div>\n </nav>\n </div>\n \n <!-- Hero content in the middle -->\n <div class = \"hero-body\">\n <div class = \"container has-text-centered\">\n <h1 class = \"title\">Tutorialspoint (Main title)</h1>\n <h2 class = \"subtitle\">Online Learning (Subtitle)</h2>\n </div>\n </div>\n \n <!-- Hero footer at the bottom -->\n <div class = \"hero-foot is-info\">\n <nav class = \"tabs\">\n <div class = \"container\">\n <ul>\n <li class = \"is-active\"><a>Help</a></li>\n <li><a>FAQ's</a></li>\n <li><a>Privacy</a></li>\n <li><a>Feedback</a></li>\n <li><a>Terms</a></li>\n </ul>\n </div>\n </nav>\n </div>\n \n </section>\n </div>\n </section>\n \n </body>\n</html>"
},
{
"code": null,
"e": 8095,
"s": 8064,
"text": "It displays the below output β"
},
{
"code": null,
"e": 8100,
"s": 8095,
"text": "Help"
},
{
"code": null,
"e": 8106,
"s": 8100,
"text": "FAQ's"
},
{
"code": null,
"e": 8114,
"s": 8106,
"text": "Privacy"
},
{
"code": null,
"e": 8123,
"s": 8114,
"text": "Feedback"
},
{
"code": null,
"e": 8129,
"s": 8123,
"text": "Terms"
},
{
"code": null,
"e": 8306,
"s": 8129,
"text": "You can also display the full height hero as large and fullwidth by using is-large and is-fullheight classes. Use these classes by replacing is-medium class in the section tag."
},
{
"code": null,
"e": 8313,
"s": 8306,
"text": " Print"
},
{
"code": null,
"e": 8324,
"s": 8313,
"text": " Add Notes"
}
] |
MomentJS - Day of year
|
This method will take care of getting and setting the day of year. The range given is 0-366. If the input to set is greater than the range, it will show up the next year.
moment().dayOfYear(Number);
moment().dayOfYear();
var m = moment().dayOfYear();
var d = moment().dayOfYear(320);
var a = moment().dayOfYear(400);
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2131,
"s": 1960,
"text": "This method will take care of getting and setting the day of year. The range given is 0-366. If the input to set is greater than the range, it will show up the next year."
},
{
"code": null,
"e": 2182,
"s": 2131,
"text": "moment().dayOfYear(Number);\nmoment().dayOfYear();\n"
},
{
"code": null,
"e": 2278,
"s": 2182,
"text": "var m = moment().dayOfYear();\nvar d = moment().dayOfYear(320);\nvar a = moment().dayOfYear(400);"
},
{
"code": null,
"e": 2285,
"s": 2278,
"text": " Print"
},
{
"code": null,
"e": 2296,
"s": 2285,
"text": " Add Notes"
}
] |
How to declare constant in react class ? - GeeksforGeeks
|
14 Dec, 2020
To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that that constant is accessible class-wide. Constants can be declared in the following two ways:
Create a getter method in the class for getting the constant when required.Assign the class constant after the declaration of the class.
Create a getter method in the class for getting the constant when required.
Assign the class constant after the declaration of the class.
Create a sample project with the following command:
// constantDemo is the name of our folder
npx create-react-app constantDemo
Now move to the constantDemo folder using the following command:
cd constantDemo
The Project Structure will look like the following:
Filename: App.js Now open the App.js file and paste the following code in it:
Javascript
import React, { Component } from "react"; class App extends Component { static get myConstant() { return { name : "GFG", id : 1 } } render() { return ( <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div> ); }} export default App
Now run the project using the following command:
npm start
Output :
Another way of declaring the constants is shown below. Paste down the following code in the App.js file.
Filename: App.js
Javascript
import React, { Component } from "react"; class App extends Component { render() { return ( <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div> ); }} GFG.myConstant = { name : "GeeksForGeeks", id : 2} export default App
Now run the project using the following command:
npm start
Output:
Picked
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25422,
"s": 25394,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 25664,
"s": 25422,
"text": "To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that that constant is accessible class-wide. Constants can be declared in the following two ways:"
},
{
"code": null,
"e": 25802,
"s": 25664,
"text": "Create a getter method in the class for getting the constant when required.Assign the class constant after the declaration of the class. "
},
{
"code": null,
"e": 25878,
"s": 25802,
"text": "Create a getter method in the class for getting the constant when required."
},
{
"code": null,
"e": 25941,
"s": 25878,
"text": "Assign the class constant after the declaration of the class. "
},
{
"code": null,
"e": 25993,
"s": 25941,
"text": "Create a sample project with the following command:"
},
{
"code": null,
"e": 26069,
"s": 25993,
"text": "// constantDemo is the name of our folder\nnpx create-react-app constantDemo"
},
{
"code": null,
"e": 26134,
"s": 26069,
"text": "Now move to the constantDemo folder using the following command:"
},
{
"code": null,
"e": 26150,
"s": 26134,
"text": "cd constantDemo"
},
{
"code": null,
"e": 26202,
"s": 26150,
"text": "The Project Structure will look like the following:"
},
{
"code": null,
"e": 26280,
"s": 26202,
"text": "Filename: App.js Now open the App.js file and paste the following code in it:"
},
{
"code": null,
"e": 26291,
"s": 26280,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\"; class App extends Component { static get myConstant() { return { name : \"GFG\", id : 1 } } render() { return ( <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div> ); }} export default App",
"e": 26621,
"s": 26291,
"text": null
},
{
"code": null,
"e": 26670,
"s": 26621,
"text": "Now run the project using the following command:"
},
{
"code": null,
"e": 26680,
"s": 26670,
"text": "npm start"
},
{
"code": null,
"e": 26690,
"s": 26680,
"text": "Output : "
},
{
"code": null,
"e": 26795,
"s": 26690,
"text": "Another way of declaring the constants is shown below. Paste down the following code in the App.js file."
},
{
"code": null,
"e": 26812,
"s": 26795,
"text": "Filename: App.js"
},
{
"code": null,
"e": 26823,
"s": 26812,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\"; class App extends Component { render() { return ( <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div> ); }} GFG.myConstant = { name : \"GeeksForGeeks\", id : 2} export default App",
"e": 27088,
"s": 26823,
"text": null
},
{
"code": null,
"e": 27137,
"s": 27088,
"text": "Now run the project using the following command:"
},
{
"code": null,
"e": 27147,
"s": 27137,
"text": "npm start"
},
{
"code": null,
"e": 27155,
"s": 27147,
"text": "Output:"
},
{
"code": null,
"e": 27162,
"s": 27155,
"text": "Picked"
},
{
"code": null,
"e": 27171,
"s": 27162,
"text": "react-js"
},
{
"code": null,
"e": 27182,
"s": 27171,
"text": "JavaScript"
},
{
"code": null,
"e": 27199,
"s": 27182,
"text": "Web Technologies"
},
{
"code": null,
"e": 27297,
"s": 27199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27337,
"s": 27297,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27398,
"s": 27337,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27439,
"s": 27398,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27461,
"s": 27439,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 27509,
"s": 27461,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27549,
"s": 27509,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27582,
"s": 27549,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27625,
"s": 27582,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27675,
"s": 27625,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Board Game Image Recognition using Neural Networks | by Andrew Underwood | Towards Data Science
|
Utilizing computer vision techniques and convolutional neural networks (CNN), the algorithms created for this project classify chess pieces and identify their location on a chessboard. The final application saves images throughout to visualize the performance and outputs a 2D image of the chessboard to see the results (see below). The purpose of this article is to step through this project so that it can be used as the βfoundationβ for new iterations. See the code for this project on GitHub.
I had high requirements for this projectβs dataset because I knew it would ultimately drive my results. The chess datasets I found online were created with either a different chess set (Chess Vision), a different camera setup (Chess ID Public Data), or both (Raspberry Turk Project), which led me to create my own. I generated a custom dataset using my chess set and camera setup (GoPro Hero6 Black at a βfirst-person viewβ angle), which allowed my model to be more accurate. The dataset contained 2,406 images classified into 13 categories (see below). Take-away: This took the majority of my time, but ultimately you want to train your model on images that are as close as possible to the ones it will see when used in your application.
To build this dataset, I first created capture_data.py, which takes a frame from a video stream when the S-key is clicked and saves it to the director. This program allowed me to change the pieces on the chessboard seamlessly and capture an image of the board over and over until I had built up a large number of different board configurations. Next, I created create_data.py to crop the frames into separate pieces by using the board detection techniques discussed in the next section. Finally, I classified the cropped images by separating them into labeled folders. And... Voila!
For chessboard detection, I wanted to do something more involved than using findChessboardCorners (OpenCV), but not as high-level as a CNN. Low and mid-level computer vision techniques were used to find features of the chessboard and then turn those features into coordinates of the outer border and 64 individual squares. The process was centered around implementing Canny edge detection and Hough Transform to generate intersecting horizontal and vertical lines. Hierarchical clustering was used to group the intersections by distance and the groups were averaged to create the final coordinates (see below).
When I started this project, I knew I wanted to use Keras/TensorFlow to create a CNN model and classify the chess pieces. However, after creating my dataset, a CNN alone would not give me the results I wanted given the size of my dataset. To overcome this obstacle, I utilized ImageDataGenerator and transfer learning, which augmented my data and used other pre-trained models as a base.
I created and trained the CNN model in the cloud in order to use a GPU, which significantly decreased the training time. Quick Tip: Google Colab is a quick and easy way to get started using a GPU. To increase my dataβs effectiveness, I used ImageDataGenerator to augment my original images and expose my model to different versions of the data. The function ImageDataGenerator randomly rotated, rescaled, and flipped (horizontal) my training data for each epoch, essentially creating more data (see below). While there are many more transformation options, I found that these were the most effective for this project.
from keras.preprocessing.image import ImageDataGeneratordatagen = ImageDataGenerator( rotation_range=5, rescale=1./255, horizontal_flip=True, fill_mode='nearest')test_datagen = ImageDataGenerator(rescale=1./255)train_gen = datagen.flow_from_directory( folder + '/train', target_size = image_size, batch_size = batch_size, class_mode = 'categorical', color_mode = 'rgb', shuffle=True)test_gen = test_datagen.flow_from_directory( folder + '/test', target_size = image_size, batch_size = batch_size, class_mode = 'categorical', color_mode = 'rgb', shuffle=False)
Instead of training a full-scale model from scratch, I implemented transfer learning by leveraging a pre-trained model and added a top-layer model, trained using my custom dataset. I followed the typical transfer learning workflow:
1. Took layers from a previously trained model (VGG16).
from keras.applications.vgg16 import VGG16model = VGG16(weights='imagenet')model.summary()
2. Froze them to avoid destroying any of the information they contained during training rounds.
3. Added new, trainable layers on top of the frozen layers.
from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, MaxPooling2D, Flattenfrom keras.models import Modelbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(224,224,3)) # Freeze convolutional layers from VGG16for layer in base_model.layers: layer.trainable = False# Establish new fully connected blockx = base_model.outputx = Flatten()(x) x = Dense(500, activation='relu')(x) x = Dense(500, activation='relu')(x)predictions = Dense(13, activation='softmax')(x)# This is the model we will trainmodel = Model(inputs=base_model.input, outputs=predictions)model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['categorical_accuracy'])
4. Trained the new layers on the custom dataset.
epochs = 10history = model.fit( train_gen, epochs=epochs, verbose = 1, validation_data=test_gen)model.save_weights('model_VGG16.h5')
While I created models using VGG16 or VGG19 as my pre-trained model, I chose the model using VGG16 due to better validation accuracy. Also, I found that the optimal number of epochs was 10. Any number above ten did not cause an increase in validation accuracy and increased the difference between the train and validation accuracy, which hints at overfitting. Take-away: Transfer learning allowed me to take full advantage of deep learningβs strengths in image classification without requiring a large dataset.
To better visualize the validation accuracy, I created a confusion matrix of the modelβs predictions. From this chart, itβs easy to evaluate the modelβs strengths and weaknesses. Strengths: Empty β precision was 99% and recall was 100%; White and Black Pawns (WP and BP) β had an F1-score of ~95%. Weaknesses: White Knight (WN) β had high recall (98%) but very low precision (65%); White Bishop (WB) β had the lowest recall at 74%.
The goal for the application was to use the CNN model and visualize the performance at each step. I created cv_chess.py (see excerpt below), which clearly shows the steps, and cv_chess_functions.py, which shows each stepβs details. This application saves the original frame from the live video stream, the 64 cropped images for each square, and the final 2D image of the chessboard. I built the application this way to quickly identify areas of strength and weakness for future improvements.
print('Working...') # Save the frame to be analyzed cv2.imwrite('frame.jpeg', frame) # Low-level CV techniques (grayscale & blur) img, gray_blur = read_img('frame.jpeg') # Canny algorithm edges = canny_edge(gray_blur) # Hough Transform lines = hough_line(edges) # Separate the lines into vertical and horizontal lines h_lines, v_lines = h_v_lines(lines) # Find and cluster the intersecting intersection_points = line_intersections(h_lines, v_lines) points = cluster_points(intersection_points) # Final coordinates of the board points = augment_points(points) # Crop the squares of the board a organize into a sorted list x_list = write_crop_images(img, points, 0) img_filename_list = grab_cell_files() img_filename_list.sort(key=natural_keys) # Classify each square and output the board in Forsyth-Edwards Notation (FEN) fen = classify_cells(model, img_filename_list) # Create and save the board image from the FEN board = fen_to_image(fen) # Display the board in ASCII print(board)# Display and save the chessboard image board_image = cv2.imread('current_board.png') cv2.imshow('current board', board_image) print('Completed!')
I hope you enjoyed the demo! For more of my projects, see my website and GitHub. Please feel free to contact me through LinkedIn with ideas for future iterations of this project. Cheers!
|
[
{
"code": null,
"e": 669,
"s": 172,
"text": "Utilizing computer vision techniques and convolutional neural networks (CNN), the algorithms created for this project classify chess pieces and identify their location on a chessboard. The final application saves images throughout to visualize the performance and outputs a 2D image of the chessboard to see the results (see below). The purpose of this article is to step through this project so that it can be used as the βfoundationβ for new iterations. See the code for this project on GitHub."
},
{
"code": null,
"e": 1408,
"s": 669,
"text": "I had high requirements for this projectβs dataset because I knew it would ultimately drive my results. The chess datasets I found online were created with either a different chess set (Chess Vision), a different camera setup (Chess ID Public Data), or both (Raspberry Turk Project), which led me to create my own. I generated a custom dataset using my chess set and camera setup (GoPro Hero6 Black at a βfirst-person viewβ angle), which allowed my model to be more accurate. The dataset contained 2,406 images classified into 13 categories (see below). Take-away: This took the majority of my time, but ultimately you want to train your model on images that are as close as possible to the ones it will see when used in your application."
},
{
"code": null,
"e": 1991,
"s": 1408,
"text": "To build this dataset, I first created capture_data.py, which takes a frame from a video stream when the S-key is clicked and saves it to the director. This program allowed me to change the pieces on the chessboard seamlessly and capture an image of the board over and over until I had built up a large number of different board configurations. Next, I created create_data.py to crop the frames into separate pieces by using the board detection techniques discussed in the next section. Finally, I classified the cropped images by separating them into labeled folders. And... Voila!"
},
{
"code": null,
"e": 2602,
"s": 1991,
"text": "For chessboard detection, I wanted to do something more involved than using findChessboardCorners (OpenCV), but not as high-level as a CNN. Low and mid-level computer vision techniques were used to find features of the chessboard and then turn those features into coordinates of the outer border and 64 individual squares. The process was centered around implementing Canny edge detection and Hough Transform to generate intersecting horizontal and vertical lines. Hierarchical clustering was used to group the intersections by distance and the groups were averaged to create the final coordinates (see below)."
},
{
"code": null,
"e": 2990,
"s": 2602,
"text": "When I started this project, I knew I wanted to use Keras/TensorFlow to create a CNN model and classify the chess pieces. However, after creating my dataset, a CNN alone would not give me the results I wanted given the size of my dataset. To overcome this obstacle, I utilized ImageDataGenerator and transfer learning, which augmented my data and used other pre-trained models as a base."
},
{
"code": null,
"e": 3608,
"s": 2990,
"text": "I created and trained the CNN model in the cloud in order to use a GPU, which significantly decreased the training time. Quick Tip: Google Colab is a quick and easy way to get started using a GPU. To increase my dataβs effectiveness, I used ImageDataGenerator to augment my original images and expose my model to different versions of the data. The function ImageDataGenerator randomly rotated, rescaled, and flipped (horizontal) my training data for each epoch, essentially creating more data (see below). While there are many more transformation options, I found that these were the most effective for this project."
},
{
"code": null,
"e": 4232,
"s": 3608,
"text": "from keras.preprocessing.image import ImageDataGeneratordatagen = ImageDataGenerator( rotation_range=5, rescale=1./255, horizontal_flip=True, fill_mode='nearest')test_datagen = ImageDataGenerator(rescale=1./255)train_gen = datagen.flow_from_directory( folder + '/train', target_size = image_size, batch_size = batch_size, class_mode = 'categorical', color_mode = 'rgb', shuffle=True)test_gen = test_datagen.flow_from_directory( folder + '/test', target_size = image_size, batch_size = batch_size, class_mode = 'categorical', color_mode = 'rgb', shuffle=False)"
},
{
"code": null,
"e": 4464,
"s": 4232,
"text": "Instead of training a full-scale model from scratch, I implemented transfer learning by leveraging a pre-trained model and added a top-layer model, trained using my custom dataset. I followed the typical transfer learning workflow:"
},
{
"code": null,
"e": 4520,
"s": 4464,
"text": "1. Took layers from a previously trained model (VGG16)."
},
{
"code": null,
"e": 4611,
"s": 4520,
"text": "from keras.applications.vgg16 import VGG16model = VGG16(weights='imagenet')model.summary()"
},
{
"code": null,
"e": 4707,
"s": 4611,
"text": "2. Froze them to avoid destroying any of the information they contained during training rounds."
},
{
"code": null,
"e": 4767,
"s": 4707,
"text": "3. Added new, trainable layers on top of the frozen layers."
},
{
"code": null,
"e": 5462,
"s": 4767,
"text": "from keras.models import Sequentialfrom keras.layers import Dense, Conv2D, MaxPooling2D, Flattenfrom keras.models import Modelbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(224,224,3)) # Freeze convolutional layers from VGG16for layer in base_model.layers: layer.trainable = False# Establish new fully connected blockx = base_model.outputx = Flatten()(x) x = Dense(500, activation='relu')(x) x = Dense(500, activation='relu')(x)predictions = Dense(13, activation='softmax')(x)# This is the model we will trainmodel = Model(inputs=base_model.input, outputs=predictions)model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['categorical_accuracy'])"
},
{
"code": null,
"e": 5511,
"s": 5462,
"text": "4. Trained the new layers on the custom dataset."
},
{
"code": null,
"e": 5657,
"s": 5511,
"text": "epochs = 10history = model.fit( train_gen, epochs=epochs, verbose = 1, validation_data=test_gen)model.save_weights('model_VGG16.h5')"
},
{
"code": null,
"e": 6168,
"s": 5657,
"text": "While I created models using VGG16 or VGG19 as my pre-trained model, I chose the model using VGG16 due to better validation accuracy. Also, I found that the optimal number of epochs was 10. Any number above ten did not cause an increase in validation accuracy and increased the difference between the train and validation accuracy, which hints at overfitting. Take-away: Transfer learning allowed me to take full advantage of deep learningβs strengths in image classification without requiring a large dataset."
},
{
"code": null,
"e": 6600,
"s": 6168,
"text": "To better visualize the validation accuracy, I created a confusion matrix of the modelβs predictions. From this chart, itβs easy to evaluate the modelβs strengths and weaknesses. Strengths: Empty β precision was 99% and recall was 100%; White and Black Pawns (WP and BP) β had an F1-score of ~95%. Weaknesses: White Knight (WN) β had high recall (98%) but very low precision (65%); White Bishop (WB) β had the lowest recall at 74%."
},
{
"code": null,
"e": 7092,
"s": 6600,
"text": "The goal for the application was to use the CNN model and visualize the performance at each step. I created cv_chess.py (see excerpt below), which clearly shows the steps, and cv_chess_functions.py, which shows each stepβs details. This application saves the original frame from the live video stream, the 64 cropped images for each square, and the final 2D image of the chessboard. I built the application this way to quickly identify areas of strength and weakness for future improvements."
},
{
"code": null,
"e": 8417,
"s": 7092,
"text": "print('Working...') # Save the frame to be analyzed cv2.imwrite('frame.jpeg', frame) # Low-level CV techniques (grayscale & blur) img, gray_blur = read_img('frame.jpeg') # Canny algorithm edges = canny_edge(gray_blur) # Hough Transform lines = hough_line(edges) # Separate the lines into vertical and horizontal lines h_lines, v_lines = h_v_lines(lines) # Find and cluster the intersecting intersection_points = line_intersections(h_lines, v_lines) points = cluster_points(intersection_points) # Final coordinates of the board points = augment_points(points) # Crop the squares of the board a organize into a sorted list x_list = write_crop_images(img, points, 0) img_filename_list = grab_cell_files() img_filename_list.sort(key=natural_keys) # Classify each square and output the board in Forsyth-Edwards Notation (FEN) fen = classify_cells(model, img_filename_list) # Create and save the board image from the FEN board = fen_to_image(fen) # Display the board in ASCII print(board)# Display and save the chessboard image board_image = cv2.imread('current_board.png') cv2.imshow('current board', board_image) print('Completed!')"
}
] |
C Extension Module using Python - GeeksforGeeks
|
27 Mar, 2019
Writing a simple C extension module directly using Pythonβs extension API and no other tools. It is straightforward to make a handcrafted extension module for a simple C code. But first, we have to make sure that the C code has a proper header file.
Code #1 :
#include <math.h> extern int gcd(int, int);extern int in_mandel(double x0, double y0, int n);extern int divide(int a, int b, int *remainder);extern double avg(double *a, int n); typedef struct Point{ double x, y;} Point; extern double distance(Point *p1, Point *p2);
The header would correspond to a library that has been separately compiled. The code below illustrates the basics of writing extension functions, following this assumption.
Code #2:
# include "Python.h"# include "sample.h" /* int gcd(int, int) */static PyObject * py_gcd(PyObject * self, PyObject * args){ int x, y, result; if (! PyArg_ParseTuple(args, "ii", &x, &y)) { return NULL; } result = gcd(x, y); return Py_BuildValue("i", result);} /* int divide(int, int, int *) */static PyObject * py_divide(PyObject * self, PyObject * args){ int a, b, quotient, remainder; if (! PyArg_ParseTuple(args, "ii", &a, &b)) { return NULL; } quotient = divide(a, b, &remainder); return Py_BuildValue("(ii)", quotient, remainder);}
Code #3 : Module method table and structure
/* Module method table */static PyMethodDef SampleMethods[] ={ {"gcd", py_gcd, METH_VARARGS, "Greatest common divisor"}, {"divide", py_divide, METH_VARARGS, "Integer division"}, { NULL, NULL, 0, NULL}}; /* Module structure */static struct PyModuleDef samplemodule ={ PyModuleDef_HEAD_INIT, "sample", /* name of module */ "A sample module", /* Doc string (may be NULL) */ -1, /* Size of per-interpreter state or -1 */ SampleMethods /* Method table */}; /* Module initialization function */PyMODINIT_FUNCPyInit_sample(void){ return PyModule_Create(&samplemodule);}
Code #4: Creating a setup.py python file for building the extension module.
# setup.pyfrom distutils.core import setup, Extension setup(name='sample', ext_modules=[ Extension('sample', ['pysample.c'], include_dirs = ['/some/dir'], define_macros = [('FOO','1')], undef_macros = ['BAR'], library_dirs = ['/usr/local/lib'], libraries = ['sample'] ) ])
Code #5: Now simply use python3 buildlib.py build_ext --inplace, to build the resulting library.
bash% python3 setup.py build_ext --inplace
running build_ext
building 'sample' extension
gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
-I/usr/local/include/python3.3m -c pysample.c
-o build/temp.macosx-10.6-x86_64-3.3/pysample.o
gcc -bundle -undefined dynamic_lookup
build/temp.macosx-10.6-x86_64-3.3/pysample.o \
-L/usr/local/lib -lsample -o sample.so
bash %
The above code will create a shared library called sample.so. Code #6 :
import sample print ("gcd = ", sample.gcd(35, 42)) print ("\ndistance : ", sample.divide(42, 8))
Output :
gcd = 7
distance = (5, 2)
βExtending and Embedding the Python Interpreterβ is a Pythonβs documentation that can be consulted before attempting any kind of handwritten extension.
In extension modules, functions can be written as shown in code snippet below.
Code #4 :
static PyObject *py_func(PyObject *self, PyObject *args){ ...}
PyObject β C data type that represents any Python object. At a very high level, an extension function is a C function that receives a tuple of Python objects (in PyObject *args) and returns a new Python object as a result. The self argument to the function is unused for simple extension functions, but comes into play should you want to define new classes or object types in C.
The PyArg_ParseTuple() function is used to convert values from Python to a C representation. As input, it takes a format string that indicates the required values, such as βiβ for integer and βdβ for double, as well as the addresses of C variables in which to place the converted results.
Py_BuildValue() function is used to create Python objects from C data types. It also accepts a format code to indicate the desired type. In the extension functions, it is used to return results back to Python. One feature of Py_BuildValue() is that it can build more complicated kinds of objects, such as tuples and dictionaries.
Python-ctype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 26185,
"s": 26157,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 26435,
"s": 26185,
"text": "Writing a simple C extension module directly using Pythonβs extension API and no other tools. It is straightforward to make a handcrafted extension module for a simple C code. But first, we have to make sure that the C code has a proper header file."
},
{
"code": null,
"e": 26445,
"s": 26435,
"text": "Code #1 :"
},
{
"code": "#include <math.h> extern int gcd(int, int);extern int in_mandel(double x0, double y0, int n);extern int divide(int a, int b, int *remainder);extern double avg(double *a, int n); typedef struct Point{ double x, y;} Point; extern double distance(Point *p1, Point *p2);",
"e": 26718,
"s": 26445,
"text": null
},
{
"code": null,
"e": 26892,
"s": 26718,
"text": " The header would correspond to a library that has been separately compiled. The code below illustrates the basics of writing extension functions, following this assumption."
},
{
"code": null,
"e": 26901,
"s": 26892,
"text": "Code #2:"
},
{
"code": "# include \"Python.h\"# include \"sample.h\" /* int gcd(int, int) */static PyObject * py_gcd(PyObject * self, PyObject * args){ int x, y, result; if (! PyArg_ParseTuple(args, \"ii\", &x, &y)) { return NULL; } result = gcd(x, y); return Py_BuildValue(\"i\", result);} /* int divide(int, int, int *) */static PyObject * py_divide(PyObject * self, PyObject * args){ int a, b, quotient, remainder; if (! PyArg_ParseTuple(args, \"ii\", &a, &b)) { return NULL; } quotient = divide(a, b, &remainder); return Py_BuildValue(\"(ii)\", quotient, remainder);}",
"e": 27489,
"s": 26901,
"text": null
},
{
"code": null,
"e": 27534,
"s": 27489,
"text": " Code #3 : Module method table and structure"
},
{
"code": "/* Module method table */static PyMethodDef SampleMethods[] ={ {\"gcd\", py_gcd, METH_VARARGS, \"Greatest common divisor\"}, {\"divide\", py_divide, METH_VARARGS, \"Integer division\"}, { NULL, NULL, 0, NULL}}; /* Module structure */static struct PyModuleDef samplemodule ={ PyModuleDef_HEAD_INIT, \"sample\", /* name of module */ \"A sample module\", /* Doc string (may be NULL) */ -1, /* Size of per-interpreter state or -1 */ SampleMethods /* Method table */}; /* Module initialization function */PyMODINIT_FUNCPyInit_sample(void){ return PyModule_Create(&samplemodule);}",
"e": 28126,
"s": 27534,
"text": null
},
{
"code": null,
"e": 28204,
"s": 28128,
"text": "Code #4: Creating a setup.py python file for building the extension module."
},
{
"code": "# setup.pyfrom distutils.core import setup, Extension setup(name='sample', ext_modules=[ Extension('sample', ['pysample.c'], include_dirs = ['/some/dir'], define_macros = [('FOO','1')], undef_macros = ['BAR'], library_dirs = ['/usr/local/lib'], libraries = ['sample'] ) ])",
"e": 28636,
"s": 28204,
"text": null
},
{
"code": null,
"e": 28735,
"s": 28638,
"text": "Code #5: Now simply use python3 buildlib.py build_ext --inplace, to build the resulting library."
},
{
"code": null,
"e": 29131,
"s": 28735,
"text": "bash% python3 setup.py build_ext --inplace\nrunning build_ext\nbuilding 'sample' extension\ngcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes\n -I/usr/local/include/python3.3m -c pysample.c\n -o build/temp.macosx-10.6-x86_64-3.3/pysample.o\ngcc -bundle -undefined dynamic_lookup\nbuild/temp.macosx-10.6-x86_64-3.3/pysample.o \\\n -L/usr/local/lib -lsample -o sample.so\nbash %\n"
},
{
"code": null,
"e": 29203,
"s": 29131,
"text": "The above code will create a shared library called sample.so. Code #6 :"
},
{
"code": "import sample print (\"gcd = \", sample.gcd(35, 42)) print (\"\\ndistance : \", sample.divide(42, 8))",
"e": 29302,
"s": 29203,
"text": null
},
{
"code": null,
"e": 29311,
"s": 29302,
"text": "Output :"
},
{
"code": null,
"e": 29339,
"s": 29311,
"text": "gcd = 7\n\ndistance = (5, 2)\n"
},
{
"code": null,
"e": 29492,
"s": 29339,
"text": " βExtending and Embedding the Python Interpreterβ is a Pythonβs documentation that can be consulted before attempting any kind of handwritten extension."
},
{
"code": null,
"e": 29571,
"s": 29492,
"text": "In extension modules, functions can be written as shown in code snippet below."
},
{
"code": null,
"e": 29581,
"s": 29571,
"text": "Code #4 :"
},
{
"code": "static PyObject *py_func(PyObject *self, PyObject *args){ ...}",
"e": 29647,
"s": 29581,
"text": null
},
{
"code": null,
"e": 30028,
"s": 29649,
"text": "PyObject β C data type that represents any Python object. At a very high level, an extension function is a C function that receives a tuple of Python objects (in PyObject *args) and returns a new Python object as a result. The self argument to the function is unused for simple extension functions, but comes into play should you want to define new classes or object types in C."
},
{
"code": null,
"e": 30317,
"s": 30028,
"text": "The PyArg_ParseTuple() function is used to convert values from Python to a C representation. As input, it takes a format string that indicates the required values, such as βiβ for integer and βdβ for double, as well as the addresses of C variables in which to place the converted results."
},
{
"code": null,
"e": 30647,
"s": 30317,
"text": "Py_BuildValue() function is used to create Python objects from C data types. It also accepts a format code to indicate the desired type. In the extension functions, it is used to return results back to Python. One feature of Py_BuildValue() is that it can build more complicated kinds of objects, such as tuples and dictionaries."
},
{
"code": null,
"e": 30660,
"s": 30647,
"text": "Python-ctype"
},
{
"code": null,
"e": 30667,
"s": 30660,
"text": "Python"
},
{
"code": null,
"e": 30765,
"s": 30667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30783,
"s": 30765,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30815,
"s": 30783,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30837,
"s": 30815,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30879,
"s": 30837,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30909,
"s": 30879,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30938,
"s": 30909,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30982,
"s": 30938,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 31019,
"s": 30982,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31061,
"s": 31019,
"text": "Check if element exists in list in Python"
}
] |
A Guide to Spring Boot ConfigurationProperties for Kotlin Data Class | by billydharmawan | Towards Data Science
|
I describe Spring Boot as the Apple equivalent for Software Engineering framework. π The reason is because it is well designed and it allows you to write less and clean code. I mean, itβs just elegant, like Apple. (I might be a bit biased here as I am team Apple).
Spring Boot comes with a lot of annotations that make our lives as programmers so much easier. π One of them, which I use quite frequently is the @ConfigurationProperties. I found it quite useful and so, I want to show you how to use it in your application.
More specifically, you will learn how to define your app configurations as a dataclass that will be managed by Spring. We will use the combination of the @ConfigurationProperties annotation and application.yml file to create the configuration dataclass.
Having a configuration class/es defined is convenient. We only need to define it once and after that, we can use it as many times as we want in different classes that need it.
To follow this guide along, you can clone this Github repo. Please note that the start of this tutorial is from this commit, so checkout that commit if you want to build the code yourself as you go through this tutorial. If not, you can just clone the repo and read along. π
The app that is contained in the repo is a Kotlin app built by using Spring Boot and Spring Webflux and coupled with DynamoDB. If youβre interested, you can check out this article for the full walkthrough of how the application was originally built.
Letβs take a look at our current DynamoClientProperties class. You can see that it takes region and endpoint as the 2 x arguments for its class constructor. Both of these values will be injected by Spring via the @Value annotation, which looks into the application.yml file located in src/main/kotlin/resources directory, by the path passed into its argument.
On the other hand, letβs check out the content of our application.yml file. Pretty simple and straight forward. It just defines the configuration for our DynamoDB related class/es.
Now, if we just leave the application as is, everything works fine. There is really no need to change anything. But, imagine if our configuration consists of a few values, not just 2 (in our case, itβs just region and endpoint), and that same configuration is used in multiple classes, not just in 1 class (e.g. in DynamoClientProperties.kt).
When that is the case, it means that we need to write the same @Values statements in different places. That is why we are going to use @ConfigurationProperties instead. It enables us to define a dataclass containing all the configuration values for a particular purpose (for example, DynamoDB related configuration), just once, in one place and we can use it in as many other places/ classes as we need.
Go ahead and create a new Kotlin file and name it DynamoConfigProperties.kt. The content of the file will be like this.
Straight away you can see that you write less code to get the values you need. You can then go to DynamoClientProperties class and inject DynamoConfigProperties instead of region and endpoint. It will become like this.
Itβs much simpler and cleaner, right? Another benefit is, if you ever need any of the values customerTableName, region or endpoint, you can simply just pass DynamoConfigProperties, which, by the way, is a Spring bean so it is only initialised once at the start of the Spring Boot application.
Now, if you run the applicationβs main function in DynamodemoApplication.kt from IntelliJ, everything will run as before the change was made. All is good, guys. π
You can go ahead and follow this tutorial to test that the interactions with DynamoDB still work as expected (it is the last part of the tutorial, sorry, but Medium does not support anchor link yet π).
When you look at how DynamoConfigProperties was written, you might be a bit hesitant or think that itβs a bit messy (or ugly) as we declared the fields as var instead of val, despite the fact that the values will never change (or should not change, I should say).
Also, we need to provide a default value of either an empty string "" (or any String, really) or null (for this, the type of the fields in DynamoConfigProperties needs to be changed to String?).
If you declare them as val or do not provide a default value and run the application, you will see the following error.
2020-01-16 07:21:57.883 WARN 97395 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerHandler' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerHandler.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerRepo' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerRepo.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dynamoClientProperties' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/DynamoClientProperties.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dynamoConfigProperties' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/DynamoConfigProperties.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}2020-01-16 07:21:57.960 INFO 97395 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2020-01-16 07:21:58.085 ERROR 97395 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :***************************APPLICATION FAILED TO START***************************Description:Parameter 0 of constructor in io.codebrews.dynamodemo.DynamoConfigProperties required a bean of type 'java.lang.String' that could not be found.Action:Consider defining a bean of type 'java.lang.String' in your configuration.Process finished with exit code 1
You can see that Spring complains about the constructor of our DynamoConfigProperties. π«
I guess we just have to deal with how βuglyβ our configuration dataclass was written, donβt we? π€·ββ
NOPE, we donβt. Here comes Spring Boot 2.2.x.RELEASE to the rescue. π
If your project uses Spring Boot framework version 2.2.0.RELEASE or above, you can change the way you write DynamoConfigProperties as follows.
Now, go ahead and run the main function of the application again. You should see the below exception getting thrown at ya. π¦
2020-01-16 13:29:03.367 WARN 87367 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerHandler' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerHandler.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerRepo' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerRepo.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dynamoClientProperties' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/DynamoClientProperties.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.codebrews.dynamodemo.DynamoConfigProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}2020-01-16 13:29:03.422 INFO 87367 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2020-01-16 13:29:03.498 ERROR 87367 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :***************************APPLICATION FAILED TO START***************************Description:Parameter 0 of constructor in io.codebrews.dynamodemo.DynamoClientProperties required a bean of type 'io.codebrews.dynamodemo.DynamoConfigProperties' that could not be found.Action:Consider defining a bean of type 'io.codebrews.dynamodemo.DynamoConfigProperties' in your configuration.Process finished with exit code 1
Unfortunately, Spring will complain to you that it cannot find the DynamoConfigProperties bean, which is required by our application to run. The reason for this is because Spring does not scan for classes annotated by @ConfigurationProperties.
Our initial DynamoConfigProperties works fine because we annotate it with @Component, which is scanned by Spring when it is building the Application Context.
I know what youβre thinking... You are going to add @Component annotation to the updated DynamoConfigProperties, ainβt you? But unfortunately, this wonβt work either and it will throw you this error when you start the application.
2020-01-16 13:45:06.021 WARN 92292 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamoConfigProperties': @EnableConfigurationProperties or @ConfigurationPropertiesScan must be used to add @ConstructorBinding type io.codebrews.dynamodemo.DynamoConfigProperties2020-01-16 13:45:06.031 INFO 92292 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2020-01-16 13:45:06.039 ERROR 92292 --- [ main] o.s.boot.SpringApplication : Application run failedorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamoConfigProperties': @EnableConfigurationProperties or @ConfigurationPropertiesScan must be used to add @ConstructorBinding type io.codebrews.dynamodemo.DynamoConfigProperties at org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.validate(ConfigurationPropertiesBeanDefinitionValidator.java:66) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.postProcessBeanFactory(ConfigurationPropertiesBeanDefinitionValidator.java:45) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:286) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:706) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at io.codebrews.dynamodemo.DynamodemoApplicationKt.main(DynamodemoApplication.kt:15) [classes/:na]Process finished with exit code 1
So, what do we do now? We improved the way our code is written, however, our application crashes! Should we go back to the old ways?
Absolutely not! π
ββ
Hereβs how to fix it. (It is very simple, actually).
By the virtue of another Spring Bootβs annotation β @ConfigurationPropertiesScan. The error message from the case where we tried to annotate the updated DynamoConfigProperties with @Component actually tells us to use either @ConfigurationPropertiesScan or @EnableConfigurationProperties.
Weβre going to go ahead with @ConfigurationPropertiesScan in this tutorial. So, letβs add that annotation to our DynamodemoApplication class like this.
Alternatively, in case you want to use @EnableConfigurationProperties instead, this is how you do it. It takes a little extra step to make it work, i.e. you need to specify explicitly which configuration class you want to enable. In our case, it is DynamoConfigProperties.
If you have another configuration class/es you want to enable, you need to specify all of them by separating them with a comma, e.g. @EnableConfigurationProperties(DynamoConfigProperties::class, KafkaConfigProperties::class).
After applying either of the above, go ahead and run the main function again. No more tricks from me this time. π
Voila! Everything works now.
Well done, guys! π π
The application Github β here
Tutorial on how the application was originally built β here
Official Spring Boot documentation on @ConfigurationProperties β here.
|
[
{
"code": null,
"e": 437,
"s": 172,
"text": "I describe Spring Boot as the Apple equivalent for Software Engineering framework. π The reason is because it is well designed and it allows you to write less and clean code. I mean, itβs just elegant, like Apple. (I might be a bit biased here as I am team Apple)."
},
{
"code": null,
"e": 695,
"s": 437,
"text": "Spring Boot comes with a lot of annotations that make our lives as programmers so much easier. π One of them, which I use quite frequently is the @ConfigurationProperties. I found it quite useful and so, I want to show you how to use it in your application."
},
{
"code": null,
"e": 949,
"s": 695,
"text": "More specifically, you will learn how to define your app configurations as a dataclass that will be managed by Spring. We will use the combination of the @ConfigurationProperties annotation and application.yml file to create the configuration dataclass."
},
{
"code": null,
"e": 1125,
"s": 949,
"text": "Having a configuration class/es defined is convenient. We only need to define it once and after that, we can use it as many times as we want in different classes that need it."
},
{
"code": null,
"e": 1400,
"s": 1125,
"text": "To follow this guide along, you can clone this Github repo. Please note that the start of this tutorial is from this commit, so checkout that commit if you want to build the code yourself as you go through this tutorial. If not, you can just clone the repo and read along. π"
},
{
"code": null,
"e": 1650,
"s": 1400,
"text": "The app that is contained in the repo is a Kotlin app built by using Spring Boot and Spring Webflux and coupled with DynamoDB. If youβre interested, you can check out this article for the full walkthrough of how the application was originally built."
},
{
"code": null,
"e": 2010,
"s": 1650,
"text": "Letβs take a look at our current DynamoClientProperties class. You can see that it takes region and endpoint as the 2 x arguments for its class constructor. Both of these values will be injected by Spring via the @Value annotation, which looks into the application.yml file located in src/main/kotlin/resources directory, by the path passed into its argument."
},
{
"code": null,
"e": 2191,
"s": 2010,
"text": "On the other hand, letβs check out the content of our application.yml file. Pretty simple and straight forward. It just defines the configuration for our DynamoDB related class/es."
},
{
"code": null,
"e": 2534,
"s": 2191,
"text": "Now, if we just leave the application as is, everything works fine. There is really no need to change anything. But, imagine if our configuration consists of a few values, not just 2 (in our case, itβs just region and endpoint), and that same configuration is used in multiple classes, not just in 1 class (e.g. in DynamoClientProperties.kt)."
},
{
"code": null,
"e": 2938,
"s": 2534,
"text": "When that is the case, it means that we need to write the same @Values statements in different places. That is why we are going to use @ConfigurationProperties instead. It enables us to define a dataclass containing all the configuration values for a particular purpose (for example, DynamoDB related configuration), just once, in one place and we can use it in as many other places/ classes as we need."
},
{
"code": null,
"e": 3058,
"s": 2938,
"text": "Go ahead and create a new Kotlin file and name it DynamoConfigProperties.kt. The content of the file will be like this."
},
{
"code": null,
"e": 3277,
"s": 3058,
"text": "Straight away you can see that you write less code to get the values you need. You can then go to DynamoClientProperties class and inject DynamoConfigProperties instead of region and endpoint. It will become like this."
},
{
"code": null,
"e": 3570,
"s": 3277,
"text": "Itβs much simpler and cleaner, right? Another benefit is, if you ever need any of the values customerTableName, region or endpoint, you can simply just pass DynamoConfigProperties, which, by the way, is a Spring bean so it is only initialised once at the start of the Spring Boot application."
},
{
"code": null,
"e": 3733,
"s": 3570,
"text": "Now, if you run the applicationβs main function in DynamodemoApplication.kt from IntelliJ, everything will run as before the change was made. All is good, guys. π"
},
{
"code": null,
"e": 3935,
"s": 3733,
"text": "You can go ahead and follow this tutorial to test that the interactions with DynamoDB still work as expected (it is the last part of the tutorial, sorry, but Medium does not support anchor link yet π)."
},
{
"code": null,
"e": 4199,
"s": 3935,
"text": "When you look at how DynamoConfigProperties was written, you might be a bit hesitant or think that itβs a bit messy (or ugly) as we declared the fields as var instead of val, despite the fact that the values will never change (or should not change, I should say)."
},
{
"code": null,
"e": 4394,
"s": 4199,
"text": "Also, we need to provide a default value of either an empty string \"\" (or any String, really) or null (for this, the type of the fields in DynamoConfigProperties needs to be changed to String?)."
},
{
"code": null,
"e": 4514,
"s": 4394,
"text": "If you declare them as val or do not provide a default value and run the application, you will see the following error."
},
{
"code": null,
"e": 6872,
"s": 4514,
"text": "2020-01-16 07:21:57.883 WARN 97395 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerHandler' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerHandler.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerRepo' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerRepo.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dynamoClientProperties' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/DynamoClientProperties.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dynamoConfigProperties' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/DynamoConfigProperties.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}2020-01-16 07:21:57.960 INFO 97395 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2020-01-16 07:21:58.085 ERROR 97395 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :***************************APPLICATION FAILED TO START***************************Description:Parameter 0 of constructor in io.codebrews.dynamodemo.DynamoConfigProperties required a bean of type 'java.lang.String' that could not be found.Action:Consider defining a bean of type 'java.lang.String' in your configuration.Process finished with exit code 1"
},
{
"code": null,
"e": 6961,
"s": 6872,
"text": "You can see that Spring complains about the constructor of our DynamoConfigProperties. π«"
},
{
"code": null,
"e": 7061,
"s": 6961,
"text": "I guess we just have to deal with how βuglyβ our configuration dataclass was written, donβt we? π€·ββ"
},
{
"code": null,
"e": 7131,
"s": 7061,
"text": "NOPE, we donβt. Here comes Spring Boot 2.2.x.RELEASE to the rescue. π"
},
{
"code": null,
"e": 7274,
"s": 7131,
"text": "If your project uses Spring Boot framework version 2.2.0.RELEASE or above, you can change the way you write DynamoConfigProperties as follows."
},
{
"code": null,
"e": 7399,
"s": 7274,
"text": "Now, go ahead and run the main function of the application again. You should see the below exception getting thrown at ya. π¦"
},
{
"code": null,
"e": 9514,
"s": 7399,
"text": "2020-01-16 13:29:03.367 WARN 87367 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerHandler' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerHandler.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerRepo' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/CustomerRepo.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dynamoClientProperties' defined in file [/Users/billyde/demo/dynamodemo/out/production/classes/io/codebrews/dynamodemo/DynamoClientProperties.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.codebrews.dynamodemo.DynamoConfigProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}2020-01-16 13:29:03.422 INFO 87367 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2020-01-16 13:29:03.498 ERROR 87367 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :***************************APPLICATION FAILED TO START***************************Description:Parameter 0 of constructor in io.codebrews.dynamodemo.DynamoClientProperties required a bean of type 'io.codebrews.dynamodemo.DynamoConfigProperties' that could not be found.Action:Consider defining a bean of type 'io.codebrews.dynamodemo.DynamoConfigProperties' in your configuration.Process finished with exit code 1"
},
{
"code": null,
"e": 9758,
"s": 9514,
"text": "Unfortunately, Spring will complain to you that it cannot find the DynamoConfigProperties bean, which is required by our application to run. The reason for this is because Spring does not scan for classes annotated by @ConfigurationProperties."
},
{
"code": null,
"e": 9916,
"s": 9758,
"text": "Our initial DynamoConfigProperties works fine because we annotate it with @Component, which is scanned by Spring when it is building the Application Context."
},
{
"code": null,
"e": 10147,
"s": 9916,
"text": "I know what youβre thinking... You are going to add @Component annotation to the updated DynamoConfigProperties, ainβt you? But unfortunately, this wonβt work either and it will throw you this error when you start the application."
},
{
"code": null,
"e": 13325,
"s": 10147,
"text": "2020-01-16 13:45:06.021 WARN 92292 --- [ main] onfigReactiveWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamoConfigProperties': @EnableConfigurationProperties or @ConfigurationPropertiesScan must be used to add @ConstructorBinding type io.codebrews.dynamodemo.DynamoConfigProperties2020-01-16 13:45:06.031 INFO 92292 --- [ main] ConditionEvaluationReportLoggingListener :Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.2020-01-16 13:45:06.039 ERROR 92292 --- [ main] o.s.boot.SpringApplication : Application run failedorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dynamoConfigProperties': @EnableConfigurationProperties or @ConfigurationPropertiesScan must be used to add @ConstructorBinding type io.codebrews.dynamodemo.DynamoConfigProperties at org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.validate(ConfigurationPropertiesBeanDefinitionValidator.java:66) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.postProcessBeanFactory(ConfigurationPropertiesBeanDefinitionValidator.java:45) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:286) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:706) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at io.codebrews.dynamodemo.DynamodemoApplicationKt.main(DynamodemoApplication.kt:15) [classes/:na]Process finished with exit code 1"
},
{
"code": null,
"e": 13458,
"s": 13325,
"text": "So, what do we do now? We improved the way our code is written, however, our application crashes! Should we go back to the old ways?"
},
{
"code": null,
"e": 13478,
"s": 13458,
"text": "Absolutely not! π
ββ"
},
{
"code": null,
"e": 13531,
"s": 13478,
"text": "Hereβs how to fix it. (It is very simple, actually)."
},
{
"code": null,
"e": 13819,
"s": 13531,
"text": "By the virtue of another Spring Bootβs annotation β @ConfigurationPropertiesScan. The error message from the case where we tried to annotate the updated DynamoConfigProperties with @Component actually tells us to use either @ConfigurationPropertiesScan or @EnableConfigurationProperties."
},
{
"code": null,
"e": 13971,
"s": 13819,
"text": "Weβre going to go ahead with @ConfigurationPropertiesScan in this tutorial. So, letβs add that annotation to our DynamodemoApplication class like this."
},
{
"code": null,
"e": 14244,
"s": 13971,
"text": "Alternatively, in case you want to use @EnableConfigurationProperties instead, this is how you do it. It takes a little extra step to make it work, i.e. you need to specify explicitly which configuration class you want to enable. In our case, it is DynamoConfigProperties."
},
{
"code": null,
"e": 14470,
"s": 14244,
"text": "If you have another configuration class/es you want to enable, you need to specify all of them by separating them with a comma, e.g. @EnableConfigurationProperties(DynamoConfigProperties::class, KafkaConfigProperties::class)."
},
{
"code": null,
"e": 14584,
"s": 14470,
"text": "After applying either of the above, go ahead and run the main function again. No more tricks from me this time. π"
},
{
"code": null,
"e": 14613,
"s": 14584,
"text": "Voila! Everything works now."
},
{
"code": null,
"e": 14634,
"s": 14613,
"text": "Well done, guys! π π"
},
{
"code": null,
"e": 14664,
"s": 14634,
"text": "The application Github β here"
},
{
"code": null,
"e": 14724,
"s": 14664,
"text": "Tutorial on how the application was originally built β here"
}
] |
Arrange given numbers to form the smallest number - GeeksforGeeks
|
30 Jun, 2021
Given an array arr[] of integer elements, the task is to arrange them in such a way that these numbers form the smallest possible number. For example, if the given array is {5, 6, 2, 9, 21, 1} then the arrangement will be 1212569.
Examples:
Input: arr[] = {5, 6, 2, 9, 21, 1} Output: 1212569
Input: arr[] = {1, 2, 1, 12, 33, 211, 50} Output: 111221123350
Approach: If all the given numbers are of at most one digit then the simple approach is sorting all numbers in ascending order. But if there is some number which have more than a single-digit then this approach will not work. Therefore, we have to sort the array by comparing any two elements in the following way: If the elements are A and B, then compare (A + B) with (B + A) where + represents concatenation.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <algorithm>#include <iostream>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i];} // A comparison function that return true// if 'AB' is smaller than 'BA' when// we concatenate two numbers 'A' and 'B'// For example, it will return true if// we pass 12 and 24 as arguments.// This function will be used by sort() functionbool compare(int num1, int num2){ // to_string function is predefined function // to convert a number in string // Convert first number to string format string A = to_string(num1); // Convert second number to string format string B = to_string(num2); // Check if 'AB' is smaller or 'BA' // and return bool value since // comparison operator '<=' returns // true or false return (A + B) <= (B + A);} // Function to print the arrangement// with the smallest valuevoid printSmallest(int N, int arr[]){ // If we pass the name of the comparison // function it will sort the array // according to the compare function sort(arr, arr + N, compare); // Print the sorted array printArr(arr, N);} // Driver codeint main(){ int arr[] = { 5, 6, 2, 9, 21, 1 }; int N = sizeof(arr) / sizeof(arr[0]); printSmallest(N, arr); return 0;}
// Java implementation of the approachclass GFG{ // Utility function to print // the contents of an array public static void printArr(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr[i]); } // A comparison function that return negative // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return negative value if // we pass 12 and 24 as arguments. // This function will be used during sort public static int compare(int num1, int num2) { // toString function is predefined function // to convert a number in string // Convert first number to string format String A = Integer.toString(num1); // Convert second number to string format String B = Integer.toString(num2); // Check if 'AB' is smaller or 'BA' // and return integer value return (A+B).compareTo(B+A); } // Function to print the arrangement // with the smallest value public static void printSmallest(int N, int[] arr) { // Sort using compare function which // is defined above for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (compare(arr[i], arr[j]) > 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Print the sorted array printArr(arr, N); } // Driver code public static void main(String[] args) { int[] arr = { 5, 6, 2, 9, 21, 1 }; int N = arr.length; printSmallest(N, arr); }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(0, n): print(arr[i], end = "") # A comparison function that return true# if 'AB' is smaller than 'BA' when# we concatenate two numbers 'A' and 'B'# For example, it will return true if# we pass 12 and 24 as arguments.# This function will be used by sort() functiondef compare(num1, num2): # Convert first number to string format A = str(num1) # Convert second number to string format B = str(num2) # Check if 'AB' is smaller or 'BA' # and return bool value since # comparison operator '<=' returns # true or false return int(A + B) <= int(B + A) def sort(arr): for i in range(len(arr)): for j in range(i + 1, len(arr)): if compare(arr[i], arr[j]) == False: arr[i], arr[j] = arr[j], arr[i] # Function to print the arrangement# with the smallest valuedef printSmallest(N, arr): # If we pass the name of the comparison # function it will sort the array # according to the compare function sort(arr) # Print the sorted array printArr(arr, N) # Driver codeif __name__ == "__main__": arr = [5, 6, 2, 9, 21, 1] N = len(arr) printSmallest(N, arr) # This code is contributed by Rituraj Jain
// C# implementation for above approachusing System; class GFG{ // Utility function to print // the contents of an array public static void printArr(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i]); } // A comparison function that return negative // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return negative value if // we pass 12 and 24 as arguments. // This function will be used during sort public static int compare(int num1, int num2) { // toString function is predefined function // to convert a number in string // Convert first number to string format String A = num1.ToString(); // Convert second number to string format String B = num2.ToString(); // Check if 'AB' is smaller or 'BA' // and return integer value return (A+B).CompareTo(B+A); } // Function to print the arrangement // with the smallest value public static void printSmallest(int N, int[] arr) { // Sort using compare function which // is defined above for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (compare(arr[i], arr[j]) > 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Print the sorted array printArr(arr, N); } // Driver code public static void Main(String[] args) { int[] arr = { 5, 6, 2, 9, 21, 1 }; int N = arr.Length; printSmallest(N, arr); }} // This code is contributed by Rajput-Ji
<?php// PHP implementation of the approach // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i];} // A comparison function that return true// if 'AB' is smaller than 'BA' when// we concatenate two numbers 'A' and 'B'// For example, it will return true if// we pass 12 and 24 as arguments.// This function will be used by sort() functionfunction compare($num1, $num2){ // to_string function is predefined function // to convert a number in string // Convert first number to string format $A = (string)$num1 ; // Convert second number to string format $B = (string)$num2 ; // Check if 'AB' is smaller or 'BA' // and return bool value since // comparison operator '<=' returns // true or false if((int)($A . $B) <= (int)($B . $A)) { return true; } else return false;} function sort_arr($arr){ for ($i = 0; $i < count($arr) ; $i++) { for ($j = $i + 1;$j < count($arr) ; $j++) { if (compare($arr[$i], $arr[$j]) == false) { $temp = $arr[$i] ; $arr[$i] = $arr[$j] ; $arr[$j] = $temp ; } } } return $arr ; } // Function to print the arrangement// with the smallest valuefunction printSmallest($N, $arr){ // If we pass the name of the comparison // function it will sort the array // according to the compare function $arr = sort_arr($arr); // Print the sorted array printArr($arr, $N);} // Driver code $arr = array(5, 6, 2, 9, 21, 1 ); $N = count($arr); printSmallest($N, $arr); // This code is contributed by Ryuga ?>
<script> // Javascript implementation of the approach // Utility function to print // the contents of an array function printArr(arr,n) { for (let i = 0; i < n; i++) document.write(arr[i]); } // A comparison function that return true // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return true if // we pass 12 and 24 as arguments. // This function will be used by sort() function function compare(num1,num2) { // to_string function is predefined function // to convert a number in string // Convert first number to string format let A = num1.toString(); // Convert second number to string format let B = num2.toString(); // Check if 'AB' is smaller or 'BA' // and return bool value since // comparison operator '<=' returns // true or false return (A + B).localeCompare(B + A); } // Function to print the arrangement // with the smallest value function printSmallest(N,arr) { // If we pass the name of the comparison // function it will sort the array // according to the compare function // Sort using compare function which // is defined above for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { if (compare(arr[i], arr[j]) > 0) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Print the sorted array printArr(arr,N); } // Driver code let arr = [ 5, 6, 2, 9, 21, 1 ]; let N = arr.length; printSmallest(N,arr);</script>
1212569
rituraj_jain
ankthon
sanjeev2552
Rajput-Ji
sai bhargava ramu
vaibhavrabadiya117
Numbers
Algorithms
Mathematical
Sorting
Mathematical
Sorting
Numbers
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Quadratic Probing in Hashing
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26492,
"s": 26464,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 26723,
"s": 26492,
"text": "Given an array arr[] of integer elements, the task is to arrange them in such a way that these numbers form the smallest possible number. For example, if the given array is {5, 6, 2, 9, 21, 1} then the arrangement will be 1212569."
},
{
"code": null,
"e": 26734,
"s": 26723,
"text": "Examples: "
},
{
"code": null,
"e": 26785,
"s": 26734,
"text": "Input: arr[] = {5, 6, 2, 9, 21, 1} Output: 1212569"
},
{
"code": null,
"e": 26850,
"s": 26785,
"text": "Input: arr[] = {1, 2, 1, 12, 33, 211, 50} Output: 111221123350 "
},
{
"code": null,
"e": 27313,
"s": 26850,
"text": "Approach: If all the given numbers are of at most one digit then the simple approach is sorting all numbers in ascending order. But if there is some number which have more than a single-digit then this approach will not work. Therefore, we have to sort the array by comparing any two elements in the following way: If the elements are A and B, then compare (A + B) with (B + A) where + represents concatenation.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27317,
"s": 27313,
"text": "C++"
},
{
"code": null,
"e": 27322,
"s": 27317,
"text": "Java"
},
{
"code": null,
"e": 27330,
"s": 27322,
"text": "Python3"
},
{
"code": null,
"e": 27333,
"s": 27330,
"text": "C#"
},
{
"code": null,
"e": 27337,
"s": 27333,
"text": "PHP"
},
{
"code": null,
"e": 27348,
"s": 27337,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <algorithm>#include <iostream>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i];} // A comparison function that return true// if 'AB' is smaller than 'BA' when// we concatenate two numbers 'A' and 'B'// For example, it will return true if// we pass 12 and 24 as arguments.// This function will be used by sort() functionbool compare(int num1, int num2){ // to_string function is predefined function // to convert a number in string // Convert first number to string format string A = to_string(num1); // Convert second number to string format string B = to_string(num2); // Check if 'AB' is smaller or 'BA' // and return bool value since // comparison operator '<=' returns // true or false return (A + B) <= (B + A);} // Function to print the arrangement// with the smallest valuevoid printSmallest(int N, int arr[]){ // If we pass the name of the comparison // function it will sort the array // according to the compare function sort(arr, arr + N, compare); // Print the sorted array printArr(arr, N);} // Driver codeint main(){ int arr[] = { 5, 6, 2, 9, 21, 1 }; int N = sizeof(arr) / sizeof(arr[0]); printSmallest(N, arr); return 0;}",
"e": 28713,
"s": 27348,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Utility function to print // the contents of an array public static void printArr(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr[i]); } // A comparison function that return negative // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return negative value if // we pass 12 and 24 as arguments. // This function will be used during sort public static int compare(int num1, int num2) { // toString function is predefined function // to convert a number in string // Convert first number to string format String A = Integer.toString(num1); // Convert second number to string format String B = Integer.toString(num2); // Check if 'AB' is smaller or 'BA' // and return integer value return (A+B).compareTo(B+A); } // Function to print the arrangement // with the smallest value public static void printSmallest(int N, int[] arr) { // Sort using compare function which // is defined above for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (compare(arr[i], arr[j]) > 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Print the sorted array printArr(arr, N); } // Driver code public static void main(String[] args) { int[] arr = { 5, 6, 2, 9, 21, 1 }; int N = arr.length; printSmallest(N, arr); }} // This code is contributed by// sanjeev2552",
"e": 30478,
"s": 28713,
"text": null
},
{
"code": "# Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(0, n): print(arr[i], end = \"\") # A comparison function that return true# if 'AB' is smaller than 'BA' when# we concatenate two numbers 'A' and 'B'# For example, it will return true if# we pass 12 and 24 as arguments.# This function will be used by sort() functiondef compare(num1, num2): # Convert first number to string format A = str(num1) # Convert second number to string format B = str(num2) # Check if 'AB' is smaller or 'BA' # and return bool value since # comparison operator '<=' returns # true or false return int(A + B) <= int(B + A) def sort(arr): for i in range(len(arr)): for j in range(i + 1, len(arr)): if compare(arr[i], arr[j]) == False: arr[i], arr[j] = arr[j], arr[i] # Function to print the arrangement# with the smallest valuedef printSmallest(N, arr): # If we pass the name of the comparison # function it will sort the array # according to the compare function sort(arr) # Print the sorted array printArr(arr, N) # Driver codeif __name__ == \"__main__\": arr = [5, 6, 2, 9, 21, 1] N = len(arr) printSmallest(N, arr) # This code is contributed by Rituraj Jain",
"e": 31819,
"s": 30478,
"text": null
},
{
"code": "// C# implementation for above approachusing System; class GFG{ // Utility function to print // the contents of an array public static void printArr(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i]); } // A comparison function that return negative // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return negative value if // we pass 12 and 24 as arguments. // This function will be used during sort public static int compare(int num1, int num2) { // toString function is predefined function // to convert a number in string // Convert first number to string format String A = num1.ToString(); // Convert second number to string format String B = num2.ToString(); // Check if 'AB' is smaller or 'BA' // and return integer value return (A+B).CompareTo(B+A); } // Function to print the arrangement // with the smallest value public static void printSmallest(int N, int[] arr) { // Sort using compare function which // is defined above for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (compare(arr[i], arr[j]) > 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Print the sorted array printArr(arr, N); } // Driver code public static void Main(String[] args) { int[] arr = { 5, 6, 2, 9, 21, 1 }; int N = arr.Length; printSmallest(N, arr); }} // This code is contributed by Rajput-Ji",
"e": 33578,
"s": 31819,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i];} // A comparison function that return true// if 'AB' is smaller than 'BA' when// we concatenate two numbers 'A' and 'B'// For example, it will return true if// we pass 12 and 24 as arguments.// This function will be used by sort() functionfunction compare($num1, $num2){ // to_string function is predefined function // to convert a number in string // Convert first number to string format $A = (string)$num1 ; // Convert second number to string format $B = (string)$num2 ; // Check if 'AB' is smaller or 'BA' // and return bool value since // comparison operator '<=' returns // true or false if((int)($A . $B) <= (int)($B . $A)) { return true; } else return false;} function sort_arr($arr){ for ($i = 0; $i < count($arr) ; $i++) { for ($j = $i + 1;$j < count($arr) ; $j++) { if (compare($arr[$i], $arr[$j]) == false) { $temp = $arr[$i] ; $arr[$i] = $arr[$j] ; $arr[$j] = $temp ; } } } return $arr ; } // Function to print the arrangement// with the smallest valuefunction printSmallest($N, $arr){ // If we pass the name of the comparison // function it will sort the array // according to the compare function $arr = sort_arr($arr); // Print the sorted array printArr($arr, $N);} // Driver code $arr = array(5, 6, 2, 9, 21, 1 ); $N = count($arr); printSmallest($N, $arr); // This code is contributed by Ryuga ?>",
"e": 35291,
"s": 33578,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Utility function to print // the contents of an array function printArr(arr,n) { for (let i = 0; i < n; i++) document.write(arr[i]); } // A comparison function that return true // if 'AB' is smaller than 'BA' when // we concatenate two numbers 'A' and 'B' // For example, it will return true if // we pass 12 and 24 as arguments. // This function will be used by sort() function function compare(num1,num2) { // to_string function is predefined function // to convert a number in string // Convert first number to string format let A = num1.toString(); // Convert second number to string format let B = num2.toString(); // Check if 'AB' is smaller or 'BA' // and return bool value since // comparison operator '<=' returns // true or false return (A + B).localeCompare(B + A); } // Function to print the arrangement // with the smallest value function printSmallest(N,arr) { // If we pass the name of the comparison // function it will sort the array // according to the compare function // Sort using compare function which // is defined above for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { if (compare(arr[i], arr[j]) > 0) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } // Print the sorted array printArr(arr,N); } // Driver code let arr = [ 5, 6, 2, 9, 21, 1 ]; let N = arr.length; printSmallest(N,arr);</script>",
"e": 37074,
"s": 35291,
"text": null
},
{
"code": null,
"e": 37082,
"s": 37074,
"text": "1212569"
},
{
"code": null,
"e": 37097,
"s": 37084,
"text": "rituraj_jain"
},
{
"code": null,
"e": 37105,
"s": 37097,
"text": "ankthon"
},
{
"code": null,
"e": 37117,
"s": 37105,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37127,
"s": 37117,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37145,
"s": 37127,
"text": "sai bhargava ramu"
},
{
"code": null,
"e": 37164,
"s": 37145,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 37172,
"s": 37164,
"text": "Numbers"
},
{
"code": null,
"e": 37183,
"s": 37172,
"text": "Algorithms"
},
{
"code": null,
"e": 37196,
"s": 37183,
"text": "Mathematical"
},
{
"code": null,
"e": 37204,
"s": 37196,
"text": "Sorting"
},
{
"code": null,
"e": 37217,
"s": 37204,
"text": "Mathematical"
},
{
"code": null,
"e": 37225,
"s": 37217,
"text": "Sorting"
},
{
"code": null,
"e": 37233,
"s": 37225,
"text": "Numbers"
},
{
"code": null,
"e": 37244,
"s": 37233,
"text": "Algorithms"
},
{
"code": null,
"e": 37342,
"s": 37244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37367,
"s": 37342,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 37394,
"s": 37367,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 37428,
"s": 37394,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 37457,
"s": 37428,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 37524,
"s": 37457,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 37554,
"s": 37524,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37569,
"s": 37554,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37629,
"s": 37569,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37672,
"s": 37629,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to handle chrome notification in Selenium?
|
We can handle Chrome notification in Selenium webdriver. These are generally known as the web push notifications and can be handled with the help of the ChromeOptions class. The below image shows a notification from the browser Chrome β
We have to create an object of this ChromeOptions class and apply the addArguments method on it. The parameter --disable-notifications is passed as a parameter to this method. Finally, this information is sent to the ChromeDriver.
ChromeOptions o = new ChromeOptions();
o.addArguments("--disable-notifications");
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.WebDriver;
public class NotificationChrome {
public static void main(String[] args) throws IOException {
//object of ChromeOptions
ChromeOptions o = new ChromeOptions();
//set browser options o.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
// pass browser option to webdriver
WebDriver driver = new ChromeDriver(o);
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.justdial.com/Bangalore/Bakeries");
}
}
|
[
{
"code": null,
"e": 1299,
"s": 1062,
"text": "We can handle Chrome notification in Selenium webdriver. These are generally known as the web push notifications and can be handled with the help of the ChromeOptions class. The below image shows a notification from the browser Chrome β"
},
{
"code": null,
"e": 1530,
"s": 1299,
"text": "We have to create an object of this ChromeOptions class and apply the addArguments method on it. The parameter --disable-notifications is passed as a parameter to this method. Finally, this information is sent to the ChromeDriver."
},
{
"code": null,
"e": 1612,
"s": 1530,
"text": "ChromeOptions o = new ChromeOptions();\no.addArguments(\"--disable-notifications\");"
},
{
"code": null,
"e": 2412,
"s": 1612,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.WebDriver;\npublic class NotificationChrome {\n public static void main(String[] args) throws IOException {\n //object of ChromeOptions\n ChromeOptions o = new ChromeOptions();\n\n //set browser options o.addArguments(\"--disable-notifications\");\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n // pass browser option to webdriver\n WebDriver driver = new ChromeDriver(o);\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.justdial.com/Bangalore/Bakeries\");\n }\n}"
}
] |
Tryit Editor v3.7
|
Tryit: Using media queries
|
[] |
Convert String to Byte Array in Java Using getBytes(encoding) Method - GeeksforGeeks
|
03 Mar, 2022
In Java, any sequence of characters within double quotes is treated as String literal. String class represents the character string literal. The string class is present in java.lang package. All string literals in java are immutable i.e their value cannot be changed once created. In Java, the string literals are stored as an array of Unicode characters. A byte array is an array of bytes. We can use a byte array to store the collection of binary data.
In order to convert a string literal into a byte array, we have to first convert the sequence of characters into a sequence of bytes and for this conversion, we can use an instance of Charset.
It is an abstract class present in java.nio package and it is used to define a mapping between sequence of sixteen-bit UTF-16 code units i.e sequence of character and sequence of bytes. Basically, it mainly used for encoding and decoding of charset and unicode. The process which we discuss above to convert a string literal into a byte array is defined as encoding in which we encode each character of the string literal into a byte.
Syntax:
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
This method encodes the string literal into byte using the named charset and returns the byte array, but this method may throw an UnsupportedEncodingException if the named charset is not supported. So in order to handle the exception we use try-catch block.
Approach:
In the below program getBytes() method converts the string literal into byte by using UTF-16 (16 is a number of bits)encoding constant.
Where UTF is Unicode Transformation Format and it is used in encoding the characters. There are many variations of UTF like UTF-8 which uses one byte at the minimum in encoding characters where UTF-16 uses 2bytes and UTF-32 uses 4bytes.
Here in the below program, we use UTF-16 which takes at least 2 bytes to encode a character i.e why the length of the resulting byte array is not same as the length of the given string. But if you use UTF-8 you get the length of the resultant array the same as the length of the input string because UTF-8 takes one byte to encode a character.
Java
// Java program to Convert String to Byte Array// Using getBytes(encoding) import java.io.*;import java.lang.*;import java.nio.*;import java.nio.charset.Charset;import java.util.*; // class to convert string literal into byte arrayclass GFG { public static void main(String[] args) { // using try-catch to handle the exception try { // taking input string String s = "GeeksForGeeks"; // name of supported charset // UTF-16 is an encoding constant String charsetName = "UTF-16"; // UTF-16 charset encoding and storing the // resultant bytearray. byte[] byteArray = s.getBytes("UTF-16"); // printing the byte array to convert it into // string System.out.println(Arrays.toString(byteArray)); // printing the length of input string and // resultant byte array System.out.println("Length of String" + " " + s.length() + " " + "Length of byte Array" + " " + byteArray.length); } catch (UnsupportedEncodingException e) { System.out.println("Unsupported charset :" + e); } }}
[-2, -1, 0, 71, 0, 101, 0, 101, 0, 107, 0, 115, 0, 70, 0, 111, 0, 114, 0, 71, 0, 101, 0, 101, 0, 107, 0, 115]
Length of String 13 Length of byte Array 28
kk773572498
kk9826225
Java-Arrays
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
HashMap containsKey() Method in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n03 Mar, 2022"
},
{
"code": null,
"e": 24013,
"s": 23557,
"text": "In Java, any sequence of characters within double quotes is treated as String literal. String class represents the character string literal. The string class is present in java.lang package. All string literals in java are immutable i.e their value cannot be changed once created. In Java, the string literals are stored as an array of Unicode characters. A byte array is an array of bytes. We can use a byte array to store the collection of binary data. "
},
{
"code": null,
"e": 24206,
"s": 24013,
"text": "In order to convert a string literal into a byte array, we have to first convert the sequence of characters into a sequence of bytes and for this conversion, we can use an instance of Charset."
},
{
"code": null,
"e": 24641,
"s": 24206,
"text": "It is an abstract class present in java.nio package and it is used to define a mapping between sequence of sixteen-bit UTF-16 code units i.e sequence of character and sequence of bytes. Basically, it mainly used for encoding and decoding of charset and unicode. The process which we discuss above to convert a string literal into a byte array is defined as encoding in which we encode each character of the string literal into a byte."
},
{
"code": null,
"e": 24649,
"s": 24641,
"text": "Syntax:"
},
{
"code": null,
"e": 24730,
"s": 24649,
"text": "public byte[] getBytes(String charsetName) throws UnsupportedEncodingException "
},
{
"code": null,
"e": 24989,
"s": 24730,
"text": "This method encodes the string literal into byte using the named charset and returns the byte array, but this method may throw an UnsupportedEncodingException if the named charset is not supported. So in order to handle the exception we use try-catch block."
},
{
"code": null,
"e": 24999,
"s": 24989,
"text": "Approach:"
},
{
"code": null,
"e": 25135,
"s": 24999,
"text": "In the below program getBytes() method converts the string literal into byte by using UTF-16 (16 is a number of bits)encoding constant."
},
{
"code": null,
"e": 25372,
"s": 25135,
"text": "Where UTF is Unicode Transformation Format and it is used in encoding the characters. There are many variations of UTF like UTF-8 which uses one byte at the minimum in encoding characters where UTF-16 uses 2bytes and UTF-32 uses 4bytes."
},
{
"code": null,
"e": 25716,
"s": 25372,
"text": "Here in the below program, we use UTF-16 which takes at least 2 bytes to encode a character i.e why the length of the resulting byte array is not same as the length of the given string. But if you use UTF-8 you get the length of the resultant array the same as the length of the input string because UTF-8 takes one byte to encode a character."
},
{
"code": null,
"e": 25721,
"s": 25716,
"text": "Java"
},
{
"code": "// Java program to Convert String to Byte Array// Using getBytes(encoding) import java.io.*;import java.lang.*;import java.nio.*;import java.nio.charset.Charset;import java.util.*; // class to convert string literal into byte arrayclass GFG { public static void main(String[] args) { // using try-catch to handle the exception try { // taking input string String s = \"GeeksForGeeks\"; // name of supported charset // UTF-16 is an encoding constant String charsetName = \"UTF-16\"; // UTF-16 charset encoding and storing the // resultant bytearray. byte[] byteArray = s.getBytes(\"UTF-16\"); // printing the byte array to convert it into // string System.out.println(Arrays.toString(byteArray)); // printing the length of input string and // resultant byte array System.out.println(\"Length of String\" + \" \" + s.length() + \" \" + \"Length of byte Array\" + \" \" + byteArray.length); } catch (UnsupportedEncodingException e) { System.out.println(\"Unsupported charset :\" + e); } }}",
"e": 26995,
"s": 25721,
"text": null
},
{
"code": null,
"e": 27152,
"s": 26998,
"text": "[-2, -1, 0, 71, 0, 101, 0, 101, 0, 107, 0, 115, 0, 70, 0, 111, 0, 114, 0, 71, 0, 101, 0, 101, 0, 107, 0, 115]\nLength of String 13 Length of byte Array 28"
},
{
"code": null,
"e": 27166,
"s": 27154,
"text": "kk773572498"
},
{
"code": null,
"e": 27176,
"s": 27166,
"text": "kk9826225"
},
{
"code": null,
"e": 27188,
"s": 27176,
"text": "Java-Arrays"
},
{
"code": null,
"e": 27195,
"s": 27188,
"text": "Picked"
},
{
"code": null,
"e": 27219,
"s": 27195,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27224,
"s": 27219,
"text": "Java"
},
{
"code": null,
"e": 27238,
"s": 27224,
"text": "Java Programs"
},
{
"code": null,
"e": 27257,
"s": 27238,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27262,
"s": 27257,
"text": "Java"
},
{
"code": null,
"e": 27360,
"s": 27262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27369,
"s": 27360,
"text": "Comments"
},
{
"code": null,
"e": 27382,
"s": 27369,
"text": "Old Comments"
},
{
"code": null,
"e": 27400,
"s": 27382,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 27421,
"s": 27400,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27467,
"s": 27421,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27510,
"s": 27467,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27547,
"s": 27510,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 27591,
"s": 27547,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27617,
"s": 27591,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27651,
"s": 27617,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27698,
"s": 27651,
"text": "Implementing a Linked List in Java using Class"
}
] |
Understanding the bag of words in NLP | by Mathanraj Sharma | Towards Data Science
|
Natural language processing is an important branch of Artificial intelligence where many interesting and important pieces of research are going on. As a machine learning enthusiast, it is important to understand the sub-processes of NLP.
Here I would like to share one of the buzz words used in NLP with (link to notebook attached at the bottom) code examples. βBAG OF WORDS!!!β.
Bag of words is a method that is used to find out the important topics in a text (paragraph). What are the topics? letβs say you are reading the below paragraph,
As a pet, cat is a very useful animal and helps in protecting or saving our rashan from rats. The offspring of a cat is called as kitten, it is a smaller and a cuter version of a cat. Cat has got four thin, short and sturdy limbs that helps it in walking, running and jumping for long distances.Itβs bright eyes help it in seeing long distances and also help during the dark. Cats are found all over the world. There is no place without a cat. Sometimes a cat can be mistaken for a tiger cub, because of its extreme similarities with it.A catβs body is completely covered with soft and beautiful fur. Cats make meaw meaw sound. God has provided cats with soft shoes or pads, which help a cat in walking without making a sound.
[Text Credits: https://www.atozessays.com/animals/essay-on-cat/]
As a human when you are reading this, you know this paragraph is about the cat. Cat is an important topic in the above paragraph. But,
how does a machine suppose to figure this out?
how can you tell your model cat is an important topic in this paragraph?
"The more frequent a word, the more important it might be!!!"
This where the bag of words comes into play!!!
First, create the tokens of the paragraph using tokenization, tokens can be anything that is a part of a text, i.e words, digits, punctuations or special charactersApply necessary text preprocessing steps to filter out the good tokens, such as lowercasing words, lemmatization/stemming (bring the words to their root form), removing stop words and punctuations and etc.Count up the occurrences of each token to find the most common words.
First, create the tokens of the paragraph using tokenization, tokens can be anything that is a part of a text, i.e words, digits, punctuations or special characters
Apply necessary text preprocessing steps to filter out the good tokens, such as lowercasing words, lemmatization/stemming (bring the words to their root form), removing stop words and punctuations and etc.
Count up the occurrences of each token to find the most common words.
# declare your text hereparagraph = "As a pet, cat is a very useful animal and helps in protecting or saving our rashan from rats........................."# tokenize the paragraph using word_tokenize,return tokenstokens = word_tokenize(paragraph)# change the tokens to lower caselower_tokens = [token.lower() for token in tokens]# Retain alphabetic words: alpha_only, eliminate punctions and special charactersalpha_only = [t for t in lower_tokens if t.isalpha()]#remove all stop wordsstop_words = set(stopwords.words('english'))filtered_tokens = [token for token in alpha_only if not token in stop_words]# lemmatize the words to bring them to their root formwordnet_lemmatizer = WordNetLemmatizer()lemmatized_tokens = [wordnet_lemmatizer.lemmatize(token) for token in filtered_tokens]# create bag of wordsbag_of_words = Counter(lemmatized_tokens)# print the top 5 most common wordsprint(bag_of_words.most_common(5))Output:[('cat', 11), ('help', 5), ('walking', 2), ('long', 2), ('without', 2)]
By looking at the output you can simply say, this is a text about cats since it is the most occurring word in the text. Now you can proceed to your next steps of NLP using this bag of words as features.
This is just one way of doing it, I have only added simple preprocessing steps for simplicity. But the preprocesses step will vary from case to case. Read similar works and fine-tune preprocessing steps for your case.
You can have a look at the notebook for this example here. I hope this article is helpful to you!!!
|
[
{
"code": null,
"e": 410,
"s": 172,
"text": "Natural language processing is an important branch of Artificial intelligence where many interesting and important pieces of research are going on. As a machine learning enthusiast, it is important to understand the sub-processes of NLP."
},
{
"code": null,
"e": 552,
"s": 410,
"text": "Here I would like to share one of the buzz words used in NLP with (link to notebook attached at the bottom) code examples. βBAG OF WORDS!!!β."
},
{
"code": null,
"e": 714,
"s": 552,
"text": "Bag of words is a method that is used to find out the important topics in a text (paragraph). What are the topics? letβs say you are reading the below paragraph,"
},
{
"code": null,
"e": 1441,
"s": 714,
"text": "As a pet, cat is a very useful animal and helps in protecting or saving our rashan from rats. The offspring of a cat is called as kitten, it is a smaller and a cuter version of a cat. Cat has got four thin, short and sturdy limbs that helps it in walking, running and jumping for long distances.Itβs bright eyes help it in seeing long distances and also help during the dark. Cats are found all over the world. There is no place without a cat. Sometimes a cat can be mistaken for a tiger cub, because of its extreme similarities with it.A catβs body is completely covered with soft and beautiful fur. Cats make meaw meaw sound. God has provided cats with soft shoes or pads, which help a cat in walking without making a sound."
},
{
"code": null,
"e": 1506,
"s": 1441,
"text": "[Text Credits: https://www.atozessays.com/animals/essay-on-cat/]"
},
{
"code": null,
"e": 1641,
"s": 1506,
"text": "As a human when you are reading this, you know this paragraph is about the cat. Cat is an important topic in the above paragraph. But,"
},
{
"code": null,
"e": 1688,
"s": 1641,
"text": "how does a machine suppose to figure this out?"
},
{
"code": null,
"e": 1761,
"s": 1688,
"text": "how can you tell your model cat is an important topic in this paragraph?"
},
{
"code": null,
"e": 1823,
"s": 1761,
"text": "\"The more frequent a word, the more important it might be!!!\""
},
{
"code": null,
"e": 1870,
"s": 1823,
"text": "This where the bag of words comes into play!!!"
},
{
"code": null,
"e": 2309,
"s": 1870,
"text": "First, create the tokens of the paragraph using tokenization, tokens can be anything that is a part of a text, i.e words, digits, punctuations or special charactersApply necessary text preprocessing steps to filter out the good tokens, such as lowercasing words, lemmatization/stemming (bring the words to their root form), removing stop words and punctuations and etc.Count up the occurrences of each token to find the most common words."
},
{
"code": null,
"e": 2474,
"s": 2309,
"text": "First, create the tokens of the paragraph using tokenization, tokens can be anything that is a part of a text, i.e words, digits, punctuations or special characters"
},
{
"code": null,
"e": 2680,
"s": 2474,
"text": "Apply necessary text preprocessing steps to filter out the good tokens, such as lowercasing words, lemmatization/stemming (bring the words to their root form), removing stop words and punctuations and etc."
},
{
"code": null,
"e": 2750,
"s": 2680,
"text": "Count up the occurrences of each token to find the most common words."
},
{
"code": null,
"e": 3745,
"s": 2750,
"text": "# declare your text hereparagraph = \"As a pet, cat is a very useful animal and helps in protecting or saving our rashan from rats.........................\"# tokenize the paragraph using word_tokenize,return tokenstokens = word_tokenize(paragraph)# change the tokens to lower caselower_tokens = [token.lower() for token in tokens]# Retain alphabetic words: alpha_only, eliminate punctions and special charactersalpha_only = [t for t in lower_tokens if t.isalpha()]#remove all stop wordsstop_words = set(stopwords.words('english'))filtered_tokens = [token for token in alpha_only if not token in stop_words]# lemmatize the words to bring them to their root formwordnet_lemmatizer = WordNetLemmatizer()lemmatized_tokens = [wordnet_lemmatizer.lemmatize(token) for token in filtered_tokens]# create bag of wordsbag_of_words = Counter(lemmatized_tokens)# print the top 5 most common wordsprint(bag_of_words.most_common(5))Output:[('cat', 11), ('help', 5), ('walking', 2), ('long', 2), ('without', 2)]"
},
{
"code": null,
"e": 3948,
"s": 3745,
"text": "By looking at the output you can simply say, this is a text about cats since it is the most occurring word in the text. Now you can proceed to your next steps of NLP using this bag of words as features."
},
{
"code": null,
"e": 4166,
"s": 3948,
"text": "This is just one way of doing it, I have only added simple preprocessing steps for simplicity. But the preprocesses step will vary from case to case. Read similar works and fine-tune preprocessing steps for your case."
}
] |
In MongoDB how do you use $set to update a nested value/embedded document?
|
The syntax is as follows for this β
db.yourCollectionName.update({ }, { $set: { "yourOuterFieldName.yourInnerFieldName": "yourValue" } });
To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows β
> db.updateNestedValueDemo.insertOne({"CustomerName":"Chris",
... "CustomerDetails":{"CustomerAge":25,"CustomerCompanyName":"Google","CustomerCityName":"US"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fccc4d3c9d04998abf015")
}
Display all documents from a collection with the help of find() method. The query is as follows β
> db.updateNestedValueDemo.find().pretty();
The following is the output β
{
"_id" : ObjectId("5c8fccc4d3c9d04998abf015"),
"CustomerName" : "Chris",
"CustomerDetails" : {
"CustomerAge" : 25,
"CustomerCompanyName" : "Google",
"CustomerCityName" : "US"
}
}
Here is the query to use $set to update a nested value/embedded document β
> db.updateNestedValueDemo.update({ }, { $set: { "CustomerDetails.CustomerCompanyName": "Dell" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents from a collection using find() method β
> db.updateNestedValueDemo.find().pretty();
The following is the output β
{
"_id" : ObjectId("5c8fccc4d3c9d04998abf015"),
"CustomerName" : "Chris",
"CustomerDetails" : {
"CustomerAge" : 25,
"CustomerCompanyName" : "Dell",
"CustomerCityName" : "US"
}
}
Look at the above sample output, the nested field βCustomerCompanyNameβ has been changed from βGoogleβ to βDellβ.
|
[
{
"code": null,
"e": 1098,
"s": 1062,
"text": "The syntax is as follows for this β"
},
{
"code": null,
"e": 1201,
"s": 1098,
"text": "db.yourCollectionName.update({ }, { $set: { \"yourOuterFieldName.yourInnerFieldName\": \"yourValue\" } });"
},
{
"code": null,
"e": 1338,
"s": 1201,
"text": "To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows β"
},
{
"code": null,
"e": 1587,
"s": 1338,
"text": "> db.updateNestedValueDemo.insertOne({\"CustomerName\":\"Chris\",\n ... \"CustomerDetails\":{\"CustomerAge\":25,\"CustomerCompanyName\":\"Google\",\"CustomerCityName\":\"US\"}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8fccc4d3c9d04998abf015\")\n}"
},
{
"code": null,
"e": 1685,
"s": 1587,
"text": "Display all documents from a collection with the help of find() method. The query is as follows β"
},
{
"code": null,
"e": 1729,
"s": 1685,
"text": "> db.updateNestedValueDemo.find().pretty();"
},
{
"code": null,
"e": 1759,
"s": 1729,
"text": "The following is the output β"
},
{
"code": null,
"e": 1969,
"s": 1759,
"text": "{\n \"_id\" : ObjectId(\"5c8fccc4d3c9d04998abf015\"),\n \"CustomerName\" : \"Chris\",\n \"CustomerDetails\" : {\n \"CustomerAge\" : 25,\n \"CustomerCompanyName\" : \"Google\",\n \"CustomerCityName\" : \"US\"\n }\n}"
},
{
"code": null,
"e": 2044,
"s": 1969,
"text": "Here is the query to use $set to update a nested value/embedded document β"
},
{
"code": null,
"e": 2211,
"s": 2044,
"text": "> db.updateNestedValueDemo.update({ }, { $set: { \"CustomerDetails.CustomerCompanyName\": \"Dell\" } });\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2278,
"s": 2211,
"text": "Let us check the documents from a collection using find() method β"
},
{
"code": null,
"e": 2322,
"s": 2278,
"text": "> db.updateNestedValueDemo.find().pretty();"
},
{
"code": null,
"e": 2352,
"s": 2322,
"text": "The following is the output β"
},
{
"code": null,
"e": 2560,
"s": 2352,
"text": "{\n \"_id\" : ObjectId(\"5c8fccc4d3c9d04998abf015\"),\n \"CustomerName\" : \"Chris\",\n \"CustomerDetails\" : {\n \"CustomerAge\" : 25,\n \"CustomerCompanyName\" : \"Dell\",\n \"CustomerCityName\" : \"US\"\n }\n}"
},
{
"code": null,
"e": 2674,
"s": 2560,
"text": "Look at the above sample output, the nested field βCustomerCompanyNameβ has been changed from βGoogleβ to βDellβ."
}
] |
Go - Operators Precedence
|
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Try the following example to understand the operator precedence available in Go programming language β
package main
import "fmt"
func main() {
var a int = 20
var b int = 10
var c int = 15
var d int = 5
var e int;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
fmt.Printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
fmt.Printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
fmt.Printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
fmt.Printf("Value of a + (b * c) / d is : %d\n" , e );
}
When you compile and execute the above program it produces the following result β
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2198,
"s": 1937,
"text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator."
},
{
"code": null,
"e": 2364,
"s": 2198,
"text": "For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7."
},
{
"code": null,
"e": 2559,
"s": 2364,
"text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first."
},
{
"code": null,
"e": 2662,
"s": 2559,
"text": "Try the following example to understand the operator precedence available in Go programming language β"
},
{
"code": null,
"e": 3223,
"s": 2662,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var a int = 20\n var b int = 10\n var c int = 15\n var d int = 5\n var e int;\n\n e = (a + b) * c / d; // ( 30 * 15 ) / 5\n fmt.Printf(\"Value of (a + b) * c / d is : %d\\n\", e );\n\n e = ((a + b) * c) / d; // (30 * 15 ) / 5\n fmt.Printf(\"Value of ((a + b) * c) / d is : %d\\n\" , e );\n\n e = (a + b) * (c / d); // (30) * (15/5)\n fmt.Printf(\"Value of (a + b) * (c / d) is : %d\\n\", e );\n\n e = a + (b * c) / d; // 20 + (150/5)\n fmt.Printf(\"Value of a + (b * c) / d is : %d\\n\" , e ); \n}"
},
{
"code": null,
"e": 3305,
"s": 3223,
"text": "When you compile and execute the above program it produces the following result β"
},
{
"code": null,
"e": 3445,
"s": 3305,
"text": "Value of (a + b) * c / d is : 90\nValue of ((a + b) * c) / d is : 90\nValue of (a + b) * (c / d) is : 90\nValue of a + (b * c) / d is : 50\n"
},
{
"code": null,
"e": 3480,
"s": 3445,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3493,
"s": 3480,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 3528,
"s": 3493,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3542,
"s": 3528,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3575,
"s": 3542,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3594,
"s": 3575,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 3627,
"s": 3594,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3646,
"s": 3627,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3678,
"s": 3646,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3695,
"s": 3678,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 3728,
"s": 3695,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3747,
"s": 3728,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3754,
"s": 3747,
"text": " Print"
},
{
"code": null,
"e": 3765,
"s": 3754,
"text": " Add Notes"
}
] |
How to capture and print Python exception message?
|
Python exception messages can be captured and printed in different ways as shown in two code examples below. In the first one, we use the message attribute of the exception object.
try:
a = 7/0
print float(a)
except BaseException as e:
print e.message
integer division or modulo by zero
In case of given code, we import the sys module and use the sys.exc_value attribute to capture and print the exception message.
import sys
def catchEverything():
try:
a = 'sequel'
b = 0.8
print a + b
except Exception as e:
print sys.exc_value
catchEverything()
cannot concatenate 'str' and 'float' objects
|
[
{
"code": null,
"e": 1243,
"s": 1062,
"text": "Python exception messages can be captured and printed in different ways as shown in two code examples below. In the first one, we use the message attribute of the exception object."
},
{
"code": null,
"e": 1314,
"s": 1243,
"text": "try:\na = 7/0\nprint float(a)\nexcept BaseException as e:\nprint e.message"
},
{
"code": null,
"e": 1349,
"s": 1314,
"text": "integer division or modulo by zero"
},
{
"code": null,
"e": 1477,
"s": 1349,
"text": "In case of given code, we import the sys module and use the sys.exc_value attribute to capture and print the exception message."
},
{
"code": null,
"e": 1610,
"s": 1477,
"text": "import sys\ndef catchEverything():\ntry:\na = 'sequel'\nb = 0.8\nprint a + b\nexcept Exception as e:\nprint sys.exc_value\ncatchEverything()"
},
{
"code": null,
"e": 1655,
"s": 1610,
"text": "cannot concatenate 'str' and 'float' objects"
}
] |
SQLite - LIMIT Clause
|
SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement.
Following is the basic syntax of SELECT statement with LIMIT clause.
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows]
Following is the syntax of LIMIT clause when it is used along with OFFSET clause.
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows] OFFSET [row num]
SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example.
Consider COMPANY table with the following records β
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is an example, which limits the row in the table according to the number of rows you want to fetch from table.
sqlite> SELECT * FROM COMPANY LIMIT 6;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position.
sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
This will produce the following result.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2725,
"s": 2638,
"text": "SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement."
},
{
"code": null,
"e": 2794,
"s": 2725,
"text": "Following is the basic syntax of SELECT statement with LIMIT clause."
},
{
"code": null,
"e": 2864,
"s": 2794,
"text": "SELECT column1, column2, columnN \nFROM table_name\nLIMIT [no of rows]\n"
},
{
"code": null,
"e": 2946,
"s": 2864,
"text": "Following is the syntax of LIMIT clause when it is used along with OFFSET clause."
},
{
"code": null,
"e": 3033,
"s": 2946,
"text": "SELECT column1, column2, columnN \nFROM table_name\nLIMIT [no of rows] OFFSET [row num]\n"
},
{
"code": null,
"e": 3147,
"s": 3033,
"text": "SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example."
},
{
"code": null,
"e": 3199,
"s": 3147,
"text": "Consider COMPANY table with the following records β"
},
{
"code": null,
"e": 3705,
"s": 3199,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 3826,
"s": 3705,
"text": "Following is an example, which limits the row in the table according to the number of rows you want to fetch from table."
},
{
"code": null,
"e": 3865,
"s": 3826,
"text": "sqlite> SELECT * FROM COMPANY LIMIT 6;"
},
{
"code": null,
"e": 3905,
"s": 3865,
"text": "This will produce the following result."
},
{
"code": null,
"e": 4356,
"s": 3905,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n"
},
{
"code": null,
"e": 4531,
"s": 4356,
"text": "However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position."
},
{
"code": null,
"e": 4579,
"s": 4531,
"text": "sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2;"
},
{
"code": null,
"e": 4619,
"s": 4579,
"text": "This will produce the following result."
},
{
"code": null,
"e": 4902,
"s": 4619,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n"
},
{
"code": null,
"e": 4937,
"s": 4902,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4958,
"s": 4937,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4991,
"s": 4958,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5008,
"s": 4991,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5039,
"s": 5008,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 5052,
"s": 5039,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 5059,
"s": 5052,
"text": " Print"
},
{
"code": null,
"e": 5070,
"s": 5059,
"text": " Add Notes"
}
] |
Spring WS - Writing Client
|
In this chapter, we will learn how to create a client for the web application server created in the Spring WS - Writing Server using Spring WS.
package com.tutorialspoint.client;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.tutorialspoint.GetCountryRequest;
import com.tutorialspoint.GetCountryResponse;
public class CountryServiceClient extends WebServiceGatewaySupport {
public GetCountryResponse getCountryDetails(String country){
String uri = "http://localhost:8080/countryService/";
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
.marshalSendAndReceive(uri, request);
return response;
}
}
package com.tutorialspoint;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.tutorialspoint.client.CountryServiceClient;
public class MainApp {
public static void main(String[] args) {
CountryServiceClient client = new CountryServiceClient();
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.tutorialspoint");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
GetCountryResponse response = client.getCountryDetails("United States");
System.out.println("Country : " + response.getCountry().getName());
System.out.println("Capital : " + response.getCountry().getCapital());
System.out.println("Population : " + response.getCountry().getPopulation());
System.out.println("Currency : " + response.getCountry().getCurrency());
}
}
Start the Tomcat server and ensure that we can access other webpages from the webapps folder using a standard browser.
Right click on the MainApp.java in your application under Eclipse and use run as Java Application command. If everything is ok with the application, it will print the following message.
Country : United States
Capital : Washington
Population : 46704314
Currency : USD
Here, we have created a Client β CountryServiceClient.java for the SOAP based web service. MainApp uses CountryServiceClient to make a hit to the web service, makes a post request and gets the data.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1954,
"s": 1810,
"text": "In this chapter, we will learn how to create a client for the web application server created in the Spring WS - Writing Server using Spring WS."
},
{
"code": null,
"e": 2600,
"s": 1954,
"text": "package com.tutorialspoint.client;\n\nimport org.springframework.ws.client.core.support.WebServiceGatewaySupport;\nimport com.tutorialspoint.GetCountryRequest;\nimport com.tutorialspoint.GetCountryResponse;\n\npublic class CountryServiceClient extends WebServiceGatewaySupport {\n public GetCountryResponse getCountryDetails(String country){\n String uri = \"http://localhost:8080/countryService/\";\n GetCountryRequest request = new GetCountryRequest();\n request.setName(country);\n\n GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()\n .marshalSendAndReceive(uri, request);\n return response;\n }\n}"
},
{
"code": null,
"e": 3464,
"s": 2600,
"text": "package com.tutorialspoint;\n\nimport org.springframework.oxm.jaxb.Jaxb2Marshaller;\nimport com.tutorialspoint.client.CountryServiceClient;\n\npublic class MainApp {\n public static void main(String[] args) {\n CountryServiceClient client = new CountryServiceClient();\n Jaxb2Marshaller marshaller = new Jaxb2Marshaller();\n marshaller.setContextPath(\"com.tutorialspoint\");\n client.setMarshaller(marshaller);\n client.setUnmarshaller(marshaller);\n GetCountryResponse response = client.getCountryDetails(\"United States\");\n\n System.out.println(\"Country : \" + response.getCountry().getName());\n System.out.println(\"Capital : \" + response.getCountry().getCapital());\n System.out.println(\"Population : \" + response.getCountry().getPopulation());\n System.out.println(\"Currency : \" + response.getCountry().getCurrency());\n }\n}"
},
{
"code": null,
"e": 3583,
"s": 3464,
"text": "Start the Tomcat server and ensure that we can access other webpages from the webapps folder using a standard browser."
},
{
"code": null,
"e": 3769,
"s": 3583,
"text": "Right click on the MainApp.java in your application under Eclipse and use run as Java Application command. If everything is ok with the application, it will print the following message."
},
{
"code": null,
"e": 3852,
"s": 3769,
"text": "Country : United States\nCapital : Washington\nPopulation : 46704314\nCurrency : USD\n"
},
{
"code": null,
"e": 4051,
"s": 3852,
"text": "Here, we have created a Client β CountryServiceClient.java for the SOAP based web service. MainApp uses CountryServiceClient to make a hit to the web service, makes a post request and gets the data."
},
{
"code": null,
"e": 4058,
"s": 4051,
"text": " Print"
},
{
"code": null,
"e": 4069,
"s": 4058,
"text": " Add Notes"
}
] |
How to check if field is null or empty in MySQL?
|
To check whether a field is null or empty in MySQL, use the IF() function in MySQL. The syntax is as follows β
SELECT IF(yourColumnName IS NULL or yourColumnName = '', 'NULLId', yourColumnName) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The following is the query to create a table β
mysql> create table NullAndEmptyDemo
-1> (
-> Id varchar(200)
-> );
Query OK, 0 rows affected (0.66 sec)
Let us now insert records into the table with the help of insert command. The query to insert records in the table is as follows. We have added null and empty values as well β
mysql> insert into NullAndEmptyDemo values(NULL);
Query OK, 1 row affected (0.22 sec)
mysql> insert into NullAndEmptyDemo values('Smith123');
Query OK, 1 row affected (0.17 sec)
mysql> insert into NullAndEmptyDemo values(' ');
Query OK, 1 row affected (0.35 sec)
mysql> insert into NullAndEmptyDemo values('98765');
Query OK, 1 row affected (0.15 sec)
mysql> insert into NullAndEmptyDemo values(NULL);
Query OK, 1 row affected (0.10 sec)
mysql> insert into NullAndEmptyDemo values('Carol567');
Query OK, 1 row affected (0.14 sec)
mysql> insert into NullAndEmptyDemo values('');
Query OK, 1 row affected (0.13 sec)
Displaying all records with the help of select statement. The query is as follows β
mysql> select *from NullAndEmptyDemo;
The following is the output β
+----------+
| Id |
+----------+
| NULL |
| Smith123 |
| |
| 98765 |
| NULL |
| Carol567 |
| |
+----------+
7 rows in set (0.00 sec)
Now you can apply the above syntax we discussed in the beginning to check whether the field is null or empty. The query is as follows β
mysql> SELECT IF(Id IS NULL or Id = '', 'NULLId', Id) as UpdatedColumnValue from NullAndEmptyDemo;
The following is the output that replace the values, if NULL or empty (ββ) is found at first β
+--------------------+
| UpdatedColumnValue |
+--------------------+
| NULLId |
| Smith123 |
| NULLId |
| 98765 |
| NULLId |
| Carol567 |
| NULLId |
+--------------------+
7 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "To check whether a field is null or empty in MySQL, use the IF() function in MySQL. The syntax is as follows β"
},
{
"code": null,
"e": 1295,
"s": 1173,
"text": "SELECT IF(yourColumnName IS NULL or yourColumnName = '', 'NULLId', yourColumnName) as anyVariableName from yourTableName;"
},
{
"code": null,
"e": 1397,
"s": 1295,
"text": "To understand the above syntax, let us create a table. The following is the query to create a table β"
},
{
"code": null,
"e": 1502,
"s": 1397,
"text": "mysql> create table NullAndEmptyDemo\n-1> (\n-> Id varchar(200)\n-> );\nQuery OK, 0 rows affected (0.66 sec)"
},
{
"code": null,
"e": 1678,
"s": 1502,
"text": "Let us now insert records into the table with the help of insert command. The query to insert records in the table is as follows. We have added null and empty values as well β"
},
{
"code": null,
"e": 2292,
"s": 1678,
"text": "mysql> insert into NullAndEmptyDemo values(NULL);\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into NullAndEmptyDemo values('Smith123');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into NullAndEmptyDemo values(' ');\nQuery OK, 1 row affected (0.35 sec)\nmysql> insert into NullAndEmptyDemo values('98765');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into NullAndEmptyDemo values(NULL);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into NullAndEmptyDemo values('Carol567');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into NullAndEmptyDemo values('');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 2376,
"s": 2292,
"text": "Displaying all records with the help of select statement. The query is as follows β"
},
{
"code": null,
"e": 2414,
"s": 2376,
"text": "mysql> select *from NullAndEmptyDemo;"
},
{
"code": null,
"e": 2444,
"s": 2414,
"text": "The following is the output β"
},
{
"code": null,
"e": 2612,
"s": 2444,
"text": "+----------+\n| Id |\n+----------+\n| NULL |\n| Smith123 |\n| |\n| 98765 |\n| NULL |\n| Carol567 |\n| |\n+----------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2748,
"s": 2612,
"text": "Now you can apply the above syntax we discussed in the beginning to check whether the field is null or empty. The query is as follows β"
},
{
"code": null,
"e": 2847,
"s": 2748,
"text": "mysql> SELECT IF(Id IS NULL or Id = '', 'NULLId', Id) as UpdatedColumnValue from NullAndEmptyDemo;"
},
{
"code": null,
"e": 2942,
"s": 2847,
"text": "The following is the output that replace the values, if NULL or empty (ββ) is found at first β"
},
{
"code": null,
"e": 3220,
"s": 2942,
"text": "+--------------------+\n| UpdatedColumnValue |\n+--------------------+\n| NULLId |\n| Smith123 |\n| NULLId |\n| 98765 |\n| NULLId |\n| Carol567 |\n| NULLId |\n+--------------------+\n7 rows in set (0.00 sec)"
}
] |
How to create a signup form with HTML and CSS?
|
Following is the code to create a signup form using HTML and CSS β
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
* {box-sizing: border-box}
input[type=text], input[type=password] {
width: 100%;
font-size: 28px;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
label{
font-size: 15px;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
button {
font-size: 18px;
font-weight: bold;
background-color: rgb(10, 119, 13);
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
.cancel {
padding: 14px 20px;
background-color: #ff3d2f;
}
.formContainer {
padding: 16px;
}
.formContainer p{
font-size: 28px;
}
</style>
<body>
<form>
<div class="formContainer">
<h1>Sign Up Form</h1>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label for="repeatPassword"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="repeatPassword"
required>
<label>
<input type="checkbox" checked="checked" name="remember" style="marginbottom: 15px"> Remember me
</label>
<p>By creating an account you agree to our <a href="#"
style="color:dodgerblue">Terms & Privacy</a><p>
<div>
<button type="button" class="cancel">Cancel</button>
<button type="submit" class="signup">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
This will produce the following output β
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Following is the code to create a signup form using HTML and CSS β"
},
{
"code": null,
"e": 1140,
"s": 1129,
"text": " Live Demo"
},
{
"code": null,
"e": 2872,
"s": 1140,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody{\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n}\n* {box-sizing: border-box}\ninput[type=text], input[type=password] {\n width: 100%;\n font-size: 28px;\n padding: 15px;\n margin: 5px 0 22px 0;\n display: inline-block;\n border: none;\n background: #f1f1f1;\n}\nlabel{\n font-size: 15px;\n}\ninput[type=text]:focus, input[type=password]:focus {\n background-color: #ddd;\n outline: none;\n}\nhr {\n border: 1px solid #f1f1f1;\n margin-bottom: 25px;\n}\nbutton {\n font-size: 18px;\n font-weight: bold;\n background-color: rgb(10, 119, 13);\n color: white;\n padding: 14px 20px;\n margin: 8px 0;\n border: none;\n cursor: pointer;\n width: 100%;\n opacity: 0.9;\n}\nbutton:hover {\n opacity:1;\n}\n.cancel {\n padding: 14px 20px;\n background-color: #ff3d2f;\n}\n.formContainer {\n padding: 16px;\n}\n.formContainer p{\n font-size: 28px;\n}\n</style>\n<body>\n<form>\n<div class=\"formContainer\">\n<h1>Sign Up Form</h1>\n<hr>\n<label for=\"email\"><b>Email</b></label>\n<input type=\"text\" placeholder=\"Enter Email\" name=\"email\" required>\n<label for=\"password\"><b>Password</b></label>\n<input type=\"password\" placeholder=\"Enter Password\" name=\"password\" required>\n<label for=\"repeatPassword\"><b>Repeat Password</b></label>\n<input type=\"password\" placeholder=\"Repeat Password\" name=\"repeatPassword\"\nrequired>\n<label>\n<input type=\"checkbox\" checked=\"checked\" name=\"remember\" style=\"marginbottom: 15px\"> Remember me\n</label>\n<p>By creating an account you agree to our <a href=\"#\"\nstyle=\"color:dodgerblue\">Terms & Privacy</a><p>\n<div>\n<button type=\"button\" class=\"cancel\">Cancel</button>\n<button type=\"submit\" class=\"signup\">Sign Up</button>\n</div>\n</div>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 2913,
"s": 2872,
"text": "This will produce the following output β"
}
] |
How to cast and update a numeric value from string column only where applicable in MySQL?
|
You can use the CEIL() function from MySQL. Let us first create a table. Here, we have taken the first column as VARCHAR β
mysql> create table DemoTable
-> (
-> Value varchar(20),
-> UpdateValue int
-> );
Query OK, 0 rows affected (1.08 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable(Value) values('100');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Value) values('false');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Value) values('true');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(Value) values('1');
Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+-------+-------------+
| Value | UpdateValue |
+-------+-------------+
| 100 | NULL |
| false | NULL |
| true | NULL |
| 1 | NULL |
+-------+-------------+
4 rows in set (0.00 sec)
Following is the query to cast and update a numeric value from string column only where applicable β
mysql> update DemoTable
-> set UpdateValue=ceil(cast(Value AS char(7)));
Query OK, 4 rows affected (0.18 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again β
mysql> select *from DemoTable;
This will produce the following output β
+-------+-------------+
| Value | UpdateValue |
+-------+-------------+
| 100 | 100 |
| false | 0 |
| true | 0 |
| 1 | 1 |
+-------+-------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "You can use the CEIL() function from MySQL. Let us first create a table. Here, we have taken the first column as VARCHAR β"
},
{
"code": null,
"e": 1316,
"s": 1185,
"text": "mysql> create table DemoTable\n -> (\n -> Value varchar(20),\n -> UpdateValue int\n -> );\nQuery OK, 0 rows affected (1.08 sec)"
},
{
"code": null,
"e": 1372,
"s": 1316,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1721,
"s": 1372,
"text": "mysql> insert into DemoTable(Value) values('100');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable(Value) values('false');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(Value) values('true');\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable(Value) values('1');\nQuery OK, 1 row affected (0.07 sec)"
},
{
"code": null,
"e": 1781,
"s": 1721,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1812,
"s": 1781,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1853,
"s": 1812,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2070,
"s": 1853,
"text": "+-------+-------------+\n| Value | UpdateValue |\n+-------+-------------+\n| 100 | NULL |\n| false | NULL |\n| true | NULL |\n| 1 | NULL |\n+-------+-------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2171,
"s": 2070,
"text": "Following is the query to cast and update a numeric value from string column only where applicable β"
},
{
"code": null,
"e": 2323,
"s": 2171,
"text": "mysql> update DemoTable\n -> set UpdateValue=ceil(cast(Value AS char(7)));\nQuery OK, 4 rows affected (0.18 sec)\nRows matched: 4 Changed: 4 Warnings: 0"
},
{
"code": null,
"e": 2367,
"s": 2323,
"text": "Let us check the table records once again β"
},
{
"code": null,
"e": 2398,
"s": 2367,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2439,
"s": 2398,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2656,
"s": 2439,
"text": "+-------+-------------+\n| Value | UpdateValue |\n+-------+-------------+\n| 100 | 100 |\n| false | 0 |\n| true | 0 |\n| 1 | 1 |\n+-------+-------------+\n4 rows in set (0.00 sec)"
}
] |
bitset test() in C++ STL - GeeksforGeeks
|
19 Jun, 2018
bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not.
Syntax:
bitset_name.test(index)
Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not.
Return Value: The function returns a boolean value. It returns true if the bit at the given index is set else it returns false.
Below programs illustrate the above function:
Program 1:
// CPP program to illustrate the// bitset::test() function// when bitset is a string#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(string("1100")); bitset<6> b2(string("010010")); // Function to check if 2nd index bit // is set or not in b1 if (b1.test(2)) cout << "Bit at index 2 of 1100 is set\n"; else cout << "Bit at index 2 is not set\n"; // Function to check if 3nd index bit // is set or not in b2 if (b2.test(3)) cout << "Bit at index 3 of 010010 is set\n"; else cout << "Bit at index 3 of 010010 is not set\n"; return 0;}
Bit at index 2 of 1100 is set
Bit at index 3 of 010010 is not set
Program 2:
// CPP program to illustrate the// bitset::test() function// when the bitset is a number#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(5); bitset<6> b2(16); // Function to check if 2nd index bit // is set or not in b1 if (b1.test(2)) cout << "Bit at index 2 of 5 is set\n"; else cout << "Bit at index 2 of 5 is not set\n"; // Function to check if 3nd index bit // is set or not in b2 if (b2.test(3)) cout << "Bit at index 3 of 16 is set\n"; else cout << "Bit at index 3 of 16 is not set\n"; return 0;}
Bit at index 2 of 5 is set
Bit at index 3 of 16 is not set
CPP-bitset
CPP-Functions
STL
C++ Programs
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Const keyword in C++
Handling the Divide by Zero Exception in C++
Why it is important to write "using namespace std" in C++ program?
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Setting up Sublime Text for C++ Competitive Programming Environment
Different ways to print elements of vector
|
[
{
"code": null,
"e": 24161,
"s": 24133,
"text": "\n19 Jun, 2018"
},
{
"code": null,
"e": 24270,
"s": 24161,
"text": "bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not."
},
{
"code": null,
"e": 24278,
"s": 24270,
"text": "Syntax:"
},
{
"code": null,
"e": 24303,
"s": 24278,
"text": "bitset_name.test(index) "
},
{
"code": null,
"e": 24434,
"s": 24303,
"text": "Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not."
},
{
"code": null,
"e": 24562,
"s": 24434,
"text": "Return Value: The function returns a boolean value. It returns true if the bit at the given index is set else it returns false."
},
{
"code": null,
"e": 24608,
"s": 24562,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 24619,
"s": 24608,
"text": "Program 1:"
},
{
"code": "// CPP program to illustrate the// bitset::test() function// when bitset is a string#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(string(\"1100\")); bitset<6> b2(string(\"010010\")); // Function to check if 2nd index bit // is set or not in b1 if (b1.test(2)) cout << \"Bit at index 2 of 1100 is set\\n\"; else cout << \"Bit at index 2 is not set\\n\"; // Function to check if 3nd index bit // is set or not in b2 if (b2.test(3)) cout << \"Bit at index 3 of 010010 is set\\n\"; else cout << \"Bit at index 3 of 010010 is not set\\n\"; return 0;}",
"e": 25272,
"s": 24619,
"text": null
},
{
"code": null,
"e": 25339,
"s": 25272,
"text": "Bit at index 2 of 1100 is set\nBit at index 3 of 010010 is not set\n"
},
{
"code": null,
"e": 25350,
"s": 25339,
"text": "Program 2:"
},
{
"code": "// CPP program to illustrate the// bitset::test() function// when the bitset is a number#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(5); bitset<6> b2(16); // Function to check if 2nd index bit // is set or not in b1 if (b1.test(2)) cout << \"Bit at index 2 of 5 is set\\n\"; else cout << \"Bit at index 2 of 5 is not set\\n\"; // Function to check if 3nd index bit // is set or not in b2 if (b2.test(3)) cout << \"Bit at index 3 of 16 is set\\n\"; else cout << \"Bit at index 3 of 16 is not set\\n\"; return 0;}",
"e": 25974,
"s": 25350,
"text": null
},
{
"code": null,
"e": 26034,
"s": 25974,
"text": "Bit at index 2 of 5 is set\nBit at index 3 of 16 is not set\n"
},
{
"code": null,
"e": 26045,
"s": 26034,
"text": "CPP-bitset"
},
{
"code": null,
"e": 26059,
"s": 26045,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26063,
"s": 26059,
"text": "STL"
},
{
"code": null,
"e": 26076,
"s": 26063,
"text": "C++ Programs"
},
{
"code": null,
"e": 26080,
"s": 26076,
"text": "STL"
},
{
"code": null,
"e": 26178,
"s": 26080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26187,
"s": 26178,
"text": "Comments"
},
{
"code": null,
"e": 26200,
"s": 26187,
"text": "Old Comments"
},
{
"code": null,
"e": 26241,
"s": 26200,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 26300,
"s": 26241,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 26312,
"s": 26300,
"text": "cout in C++"
},
{
"code": null,
"e": 26333,
"s": 26312,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 26378,
"s": 26333,
"text": "Handling the Divide by Zero Exception in C++"
},
{
"code": null,
"e": 26445,
"s": 26378,
"text": "Why it is important to write \"using namespace std\" in C++ program?"
},
{
"code": null,
"e": 26466,
"s": 26445,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 26508,
"s": 26466,
"text": "isdigit() function in C/C++ with Examples"
},
{
"code": null,
"e": 26576,
"s": 26508,
"text": "Setting up Sublime Text for C++ Competitive Programming Environment"
}
] |
Automated Machine Learning on the Cloud in Python | by Will Koehrsen | Towards Data Science
|
Two trends have recently become apparent in data science:
Data analysis and model training is done using cloud resourcesMachine learning pipelines are algorithmically developed and optimized
Data analysis and model training is done using cloud resources
Machine learning pipelines are algorithmically developed and optimized
This article will cover a brief introduction to these topics and show how to implement them, using Google Colaboratory to do automated machine learning on the cloud in Python.
Originally, all computing was done on a mainframe. You logged in via a terminal, and connected to a central machine where users simultaneously shared a single large computer. Then, along came microprocessors and the personal computer revolution and everyone got their own machine. Laptops and desktops work fine for routine tasks, but with the recent increase in size of datasets and computing power needed to run machine learning models, taking advantage of cloud resources is a necessity for data science.
Cloud computing in general refers to the βdelivery of computing services over the Internetβ. This covers a wide range of services, from databases to servers to software, but in this article we will run a simple data science workload on the cloud in the form of a Jupyter Notebook. We will use the relatively new Google Colaboratory service: online Jupyter Notebooks in Python which run on Googleβs servers, can be accessed from anywhere with an internet connection, are free to use, and are shareable like any Google Doc.
Google Colab has made the process of using cloud computing a breeze. In the past, I spent dozens of hours configuring an Amazon EC2 instance so I could run a Jupyter Notebook on the cloud and had to pay by the hour! Fortunately, last year, Google announced you can now run Jupyter Notebooks on their Colab servers for up to 12 hours at a time completely free. (If thatβs not enough, Google recently began letting users add a NVIDIA Tesla K80 GPU to the notebooks). The best part is these notebooks come pre-installed with most data science packages, and more can be easily added, so you donβt have to worry about the technical details of getting set up on your own machine.
To use Colab, all you need is an internet connection and a Google account. If you just want an introduction, head to colab.research.google.com and create a new notebook, or explore the tutorial Google has developed (called Hello, Colaboratory). To follow along with this article, get the notebook here. Sign into your Google account, open the notebook in Colaboratory, click File > save a copy in Drive, and you will then have your own version to edit and run.
Data science is becoming increasingly accessible with the wealth of resources online, and the Colab project has significantly lowered the barrier to cloud computing. For those who have done prior work in Jupyter Notebooks, itβs a completely natural transition, and for those who havenβt, itβs a great opportunity to get started with this commonly used data science tool!
Automated machine learning (abbreviated auto-ml) aims to algorithmically design and optimize a machine learning pipeline for a particular problem. In this context, the machine learning pipeline consists of:
Feature Preprocessing: imputation, scaling, and constructing new featuresFeature selection: dimensionality reductionModel Selection: evaluating many machine learning modelsHyperparameter tuning: finding the optimal model settings
Feature Preprocessing: imputation, scaling, and constructing new features
Feature selection: dimensionality reduction
Model Selection: evaluating many machine learning models
Hyperparameter tuning: finding the optimal model settings
There are an almost infinite number of ways these steps can be combined together, and the optimal solution will change for every problem! Designing a machine learning pipeline can be a time-consuming and frustrating process, and at the end, you will never know if the solution you developed is even close to optimal. Auto-ml can help by evaluating thousands of possible pipelines to try and find the best (or near-optimal) solution for a particular problem.
Itβs important to remember that machine learning is only one part of the data science process, and automated machine learning is not meant to replace the data scientist. Instead, auto-ml is meant to free the data scientist so she can work on more valuable aspects of the process, such as gathering data or interpreting a model.
There are a number of auto-ml tools β H20, auto-sklearn, Google Cloud AutoML β and we will focus on TPOT: Tree-based Pipeline Optimization Tool developed by Randy Olson. TPOT (your βdata-science assistantβ) uses genetic programming to find the best machine learning pipeline.
To use TPOT, itβs not really necessary to know the details of genetic programming, so you can skip this section. For those who are curious, at a high level, genetic programming for machine learning works as follows:
Start with an initial population of randomly generated machine learning pipelines, say 100, each of which is composed of functions for feature preprocessing, model selection, and hyperparameter tuning.Train each of these pipelines (called an individual) and evaluate on a performance metric using cross validation. The cross validation performance represents the βfitnessβ of the individual. Each training run of a population is known as a generation.After one round of training β the first generation β create a second generation of 100 individuals by reproduction, mutation, and crossover. Reproduction means keeping the same steps in the pipeline, chosen with a probability proportional to the fitness score. Mutation refers to random changes within an individual from one generation to the next. Crossover is random changes between individuals from one generation to the next. Together, these three strategies will result in 100 new pipelines, each slightly different, but with the steps that worked the best according to the fitness function more likely to be retained.Repeat this process for a suitable number of generations, each time creating new individuals through reproduction, mutation, and crossover.At the end of optimization, select the best-performing individual pipeline.
Start with an initial population of randomly generated machine learning pipelines, say 100, each of which is composed of functions for feature preprocessing, model selection, and hyperparameter tuning.
Train each of these pipelines (called an individual) and evaluate on a performance metric using cross validation. The cross validation performance represents the βfitnessβ of the individual. Each training run of a population is known as a generation.
After one round of training β the first generation β create a second generation of 100 individuals by reproduction, mutation, and crossover. Reproduction means keeping the same steps in the pipeline, chosen with a probability proportional to the fitness score. Mutation refers to random changes within an individual from one generation to the next. Crossover is random changes between individuals from one generation to the next. Together, these three strategies will result in 100 new pipelines, each slightly different, but with the steps that worked the best according to the fitness function more likely to be retained.
Repeat this process for a suitable number of generations, each time creating new individuals through reproduction, mutation, and crossover.
At the end of optimization, select the best-performing individual pipeline.
(For more details on genetic programming, check out this short article.)
The primary benefit of genetic programming for building machine learning models is exploration. Even a human with no time restraints will not be able to try out all combinations of preprocessing, models, and hyperparameters because of limited knowledge and imagination. Genetic programming does not display an initial bias towards any particular sequence of machine learning steps, and with each generation, new pipelines are evaluated. Furthermore, the fitness function means that the most promising areas of the search space are explored more thoroughly than poorer-performing areas.
With the background in place, we can now walk through using TPOT in a Google Colab notebook to automatically design a machine learning pipeline. (Follow along with the notebook here).
Our task is a supervised regression problem: given New York City energy data, we want to predict the Energy Star Score of a building. In a previous series of articles (part one, part two, part three, code on GitHub), we built a complete machine learning solution for this problem. Using manual feature engineering, dimensionality reduction, model selection, and hyperparameter tuning, we designed a Gradient Boosting Regressor model that achieved a mean absolute error of 9.06 points (on a scale from 1β100) on the test set.
The data contains several dozen continuous numeric variables (such as energy use and area of the building) and two one-hot encoded categorical variables (borough and building type) for a total of 82 features.
The score is the target for regression. All of the missing values have been encoded as np.nan and no feature preprocessing has been done to the data.
To get started, we first need to make sure TPOT is installed in the Google Colab environment. Most data science packages are already installed, but we can add any new ones using system commands (preceded with a ! in Jupyter):
!pip install TPOT
After reading in the data, we would normally fill in the missing values (imputation) and normalize the features to a range (scaling). However, in addition to feature engineering, model selection, and hyperparameter tuning, TPOT will automatically impute the missing values and do feature scaling! So, our next step is to create the TPOT optimizer:
The default parameters for TPOT optimizers will evaluate 100 populations of pipelines, each with 100 generations for a total of 10,000 pipelines. Using 10-fold cross validation, this represents 100,000 training runs! Even though we are using Googleβs resources, we do not have unlimited time for training. To avoid running out of time on the Colab server (we get a max of 12 hours of continuous run time), we will set a maximum of 8 hours (480 minutes) for evaluation. TPOT is designed to be run for days, but we can still get good results from a few hours of optimization.
We set the following parameters in the call to the optimizer:
scoring = neg_mean_absolute error: Our regression performance metric
max_time_minutes = 480: Limit evaluation to 8 hours
n_jobs = -1: Use all available cores on the machine
verbosity = 2: Show a limited amount of information while training
cv = 5: Use 5-fold cross validation (default is 10)
There are other parameters that control details of the genetic programming method, but leaving them at the default works well for most cases. (If you want to play around with the parameters, check out the documentation.)
The syntax for TPOT optimizers is designed to be identical to that for Scikit-Learn models so we can train the optimizer using the .fit method.
# Fit the tpot optimizer on the training datatpot.fit(training_features, training_targets)
During training, we get some information displayed:
Due to the time limit, our model was only able to get through 15 generations. With 100 populations, this still represents 1500 different individual pipelines that were evaluated, quite a few more than we could have tried by hand!
Once the model has trained, we can see the optimal pipeline using tpot.fitted_pipeline_. We can also save the model to a Python script:
# Export the pipeline as a python script filetpot.export('tpot_exported_pipeline.py')
Since we are in a Google Colab notebook, to get the pipeline onto a local machine from the server, we have to use the Google Colab library:
# Import file managementfrom google.colab import file# Download the pipeline for local usefiles.download('tpot_exported_pipeline.py')
We can then open the file (available here) and look at the completed pipeline:
We see that the optimizer imputed the missing values for us and built a complete model pipeline! The final estimator is a stacked model meaning that it uses two machine learning algorithms ( LassoLarsCV and GradientBoostingRegressor ), the second of which is trained on the predictions of the first (If you run the notebook again, you may get a different model because the optimization process is stochastic). This is a complex method that I probably would not have been able to develop on my own!
Now, the moment of truth: performance on the testing set. To find the mean absolute error, we can use the .score method:
# Evaluate the final modelprint(tpot.score(testing_features, testing_targets))8.642
In the series of articles where we developed a solution manually, after many hours of development, we built a Gradient Boosting Regressor model that achieved a mean absolute error of 9.06. Automated machine learning has significantly improved on the performance with a drastic reduction in the amount of development time.
From here, we can use the optimized pipeline and try to further refine the solution, or we can move on to other important phases of the data science pipeline. If we use this as our final model, we could try and interpret the model (such as by using LIME: Local Interpretable Model-Agnostic Explainations) or write a well-documented report.
In this post, we got a brief introduction to both the capabilities of the cloud and automated machine learning. With only a Google account and an internet connection, we can use Google Colab to develop, run, and share machine learning or data science work loads. Using TPOT, we can automatically develop an optimized machine learning pipeline with feature preprocessing, model selection, and hyperparameter tuning. Moreover, we saw that auto-ml will not replace the data scientist, but it will allow her to spend more time on higher value parts of the workflow.
While being an early adopter does not always pay off, in this case, TPOT is mature enough to be easy to use and relatively issue-free, yet also new enough that learning it will put you ahead of the curve. With that in mind, find a machine learning problem (perhaps through Kaggle) and try to solve it! Running automatic machine learning in a notebook on Google Colab feels like the future and with such a low barrier to entry, thereβs never been a better time to get started!
As always, I welcome feedback and discussion and can be reached on Twitter @koehrsen_will.
|
[
{
"code": null,
"e": 230,
"s": 172,
"text": "Two trends have recently become apparent in data science:"
},
{
"code": null,
"e": 363,
"s": 230,
"text": "Data analysis and model training is done using cloud resourcesMachine learning pipelines are algorithmically developed and optimized"
},
{
"code": null,
"e": 426,
"s": 363,
"text": "Data analysis and model training is done using cloud resources"
},
{
"code": null,
"e": 497,
"s": 426,
"text": "Machine learning pipelines are algorithmically developed and optimized"
},
{
"code": null,
"e": 673,
"s": 497,
"text": "This article will cover a brief introduction to these topics and show how to implement them, using Google Colaboratory to do automated machine learning on the cloud in Python."
},
{
"code": null,
"e": 1181,
"s": 673,
"text": "Originally, all computing was done on a mainframe. You logged in via a terminal, and connected to a central machine where users simultaneously shared a single large computer. Then, along came microprocessors and the personal computer revolution and everyone got their own machine. Laptops and desktops work fine for routine tasks, but with the recent increase in size of datasets and computing power needed to run machine learning models, taking advantage of cloud resources is a necessity for data science."
},
{
"code": null,
"e": 1703,
"s": 1181,
"text": "Cloud computing in general refers to the βdelivery of computing services over the Internetβ. This covers a wide range of services, from databases to servers to software, but in this article we will run a simple data science workload on the cloud in the form of a Jupyter Notebook. We will use the relatively new Google Colaboratory service: online Jupyter Notebooks in Python which run on Googleβs servers, can be accessed from anywhere with an internet connection, are free to use, and are shareable like any Google Doc."
},
{
"code": null,
"e": 2377,
"s": 1703,
"text": "Google Colab has made the process of using cloud computing a breeze. In the past, I spent dozens of hours configuring an Amazon EC2 instance so I could run a Jupyter Notebook on the cloud and had to pay by the hour! Fortunately, last year, Google announced you can now run Jupyter Notebooks on their Colab servers for up to 12 hours at a time completely free. (If thatβs not enough, Google recently began letting users add a NVIDIA Tesla K80 GPU to the notebooks). The best part is these notebooks come pre-installed with most data science packages, and more can be easily added, so you donβt have to worry about the technical details of getting set up on your own machine."
},
{
"code": null,
"e": 2838,
"s": 2377,
"text": "To use Colab, all you need is an internet connection and a Google account. If you just want an introduction, head to colab.research.google.com and create a new notebook, or explore the tutorial Google has developed (called Hello, Colaboratory). To follow along with this article, get the notebook here. Sign into your Google account, open the notebook in Colaboratory, click File > save a copy in Drive, and you will then have your own version to edit and run."
},
{
"code": null,
"e": 3209,
"s": 2838,
"text": "Data science is becoming increasingly accessible with the wealth of resources online, and the Colab project has significantly lowered the barrier to cloud computing. For those who have done prior work in Jupyter Notebooks, itβs a completely natural transition, and for those who havenβt, itβs a great opportunity to get started with this commonly used data science tool!"
},
{
"code": null,
"e": 3416,
"s": 3209,
"text": "Automated machine learning (abbreviated auto-ml) aims to algorithmically design and optimize a machine learning pipeline for a particular problem. In this context, the machine learning pipeline consists of:"
},
{
"code": null,
"e": 3646,
"s": 3416,
"text": "Feature Preprocessing: imputation, scaling, and constructing new featuresFeature selection: dimensionality reductionModel Selection: evaluating many machine learning modelsHyperparameter tuning: finding the optimal model settings"
},
{
"code": null,
"e": 3720,
"s": 3646,
"text": "Feature Preprocessing: imputation, scaling, and constructing new features"
},
{
"code": null,
"e": 3764,
"s": 3720,
"text": "Feature selection: dimensionality reduction"
},
{
"code": null,
"e": 3821,
"s": 3764,
"text": "Model Selection: evaluating many machine learning models"
},
{
"code": null,
"e": 3879,
"s": 3821,
"text": "Hyperparameter tuning: finding the optimal model settings"
},
{
"code": null,
"e": 4337,
"s": 3879,
"text": "There are an almost infinite number of ways these steps can be combined together, and the optimal solution will change for every problem! Designing a machine learning pipeline can be a time-consuming and frustrating process, and at the end, you will never know if the solution you developed is even close to optimal. Auto-ml can help by evaluating thousands of possible pipelines to try and find the best (or near-optimal) solution for a particular problem."
},
{
"code": null,
"e": 4665,
"s": 4337,
"text": "Itβs important to remember that machine learning is only one part of the data science process, and automated machine learning is not meant to replace the data scientist. Instead, auto-ml is meant to free the data scientist so she can work on more valuable aspects of the process, such as gathering data or interpreting a model."
},
{
"code": null,
"e": 4941,
"s": 4665,
"text": "There are a number of auto-ml tools β H20, auto-sklearn, Google Cloud AutoML β and we will focus on TPOT: Tree-based Pipeline Optimization Tool developed by Randy Olson. TPOT (your βdata-science assistantβ) uses genetic programming to find the best machine learning pipeline."
},
{
"code": null,
"e": 5157,
"s": 4941,
"text": "To use TPOT, itβs not really necessary to know the details of genetic programming, so you can skip this section. For those who are curious, at a high level, genetic programming for machine learning works as follows:"
},
{
"code": null,
"e": 6446,
"s": 5157,
"text": "Start with an initial population of randomly generated machine learning pipelines, say 100, each of which is composed of functions for feature preprocessing, model selection, and hyperparameter tuning.Train each of these pipelines (called an individual) and evaluate on a performance metric using cross validation. The cross validation performance represents the βfitnessβ of the individual. Each training run of a population is known as a generation.After one round of training β the first generation β create a second generation of 100 individuals by reproduction, mutation, and crossover. Reproduction means keeping the same steps in the pipeline, chosen with a probability proportional to the fitness score. Mutation refers to random changes within an individual from one generation to the next. Crossover is random changes between individuals from one generation to the next. Together, these three strategies will result in 100 new pipelines, each slightly different, but with the steps that worked the best according to the fitness function more likely to be retained.Repeat this process for a suitable number of generations, each time creating new individuals through reproduction, mutation, and crossover.At the end of optimization, select the best-performing individual pipeline."
},
{
"code": null,
"e": 6648,
"s": 6446,
"text": "Start with an initial population of randomly generated machine learning pipelines, say 100, each of which is composed of functions for feature preprocessing, model selection, and hyperparameter tuning."
},
{
"code": null,
"e": 6899,
"s": 6648,
"text": "Train each of these pipelines (called an individual) and evaluate on a performance metric using cross validation. The cross validation performance represents the βfitnessβ of the individual. Each training run of a population is known as a generation."
},
{
"code": null,
"e": 7523,
"s": 6899,
"text": "After one round of training β the first generation β create a second generation of 100 individuals by reproduction, mutation, and crossover. Reproduction means keeping the same steps in the pipeline, chosen with a probability proportional to the fitness score. Mutation refers to random changes within an individual from one generation to the next. Crossover is random changes between individuals from one generation to the next. Together, these three strategies will result in 100 new pipelines, each slightly different, but with the steps that worked the best according to the fitness function more likely to be retained."
},
{
"code": null,
"e": 7663,
"s": 7523,
"text": "Repeat this process for a suitable number of generations, each time creating new individuals through reproduction, mutation, and crossover."
},
{
"code": null,
"e": 7739,
"s": 7663,
"text": "At the end of optimization, select the best-performing individual pipeline."
},
{
"code": null,
"e": 7812,
"s": 7739,
"text": "(For more details on genetic programming, check out this short article.)"
},
{
"code": null,
"e": 8398,
"s": 7812,
"text": "The primary benefit of genetic programming for building machine learning models is exploration. Even a human with no time restraints will not be able to try out all combinations of preprocessing, models, and hyperparameters because of limited knowledge and imagination. Genetic programming does not display an initial bias towards any particular sequence of machine learning steps, and with each generation, new pipelines are evaluated. Furthermore, the fitness function means that the most promising areas of the search space are explored more thoroughly than poorer-performing areas."
},
{
"code": null,
"e": 8582,
"s": 8398,
"text": "With the background in place, we can now walk through using TPOT in a Google Colab notebook to automatically design a machine learning pipeline. (Follow along with the notebook here)."
},
{
"code": null,
"e": 9107,
"s": 8582,
"text": "Our task is a supervised regression problem: given New York City energy data, we want to predict the Energy Star Score of a building. In a previous series of articles (part one, part two, part three, code on GitHub), we built a complete machine learning solution for this problem. Using manual feature engineering, dimensionality reduction, model selection, and hyperparameter tuning, we designed a Gradient Boosting Regressor model that achieved a mean absolute error of 9.06 points (on a scale from 1β100) on the test set."
},
{
"code": null,
"e": 9316,
"s": 9107,
"text": "The data contains several dozen continuous numeric variables (such as energy use and area of the building) and two one-hot encoded categorical variables (borough and building type) for a total of 82 features."
},
{
"code": null,
"e": 9466,
"s": 9316,
"text": "The score is the target for regression. All of the missing values have been encoded as np.nan and no feature preprocessing has been done to the data."
},
{
"code": null,
"e": 9692,
"s": 9466,
"text": "To get started, we first need to make sure TPOT is installed in the Google Colab environment. Most data science packages are already installed, but we can add any new ones using system commands (preceded with a ! in Jupyter):"
},
{
"code": null,
"e": 9710,
"s": 9692,
"text": "!pip install TPOT"
},
{
"code": null,
"e": 10058,
"s": 9710,
"text": "After reading in the data, we would normally fill in the missing values (imputation) and normalize the features to a range (scaling). However, in addition to feature engineering, model selection, and hyperparameter tuning, TPOT will automatically impute the missing values and do feature scaling! So, our next step is to create the TPOT optimizer:"
},
{
"code": null,
"e": 10632,
"s": 10058,
"text": "The default parameters for TPOT optimizers will evaluate 100 populations of pipelines, each with 100 generations for a total of 10,000 pipelines. Using 10-fold cross validation, this represents 100,000 training runs! Even though we are using Googleβs resources, we do not have unlimited time for training. To avoid running out of time on the Colab server (we get a max of 12 hours of continuous run time), we will set a maximum of 8 hours (480 minutes) for evaluation. TPOT is designed to be run for days, but we can still get good results from a few hours of optimization."
},
{
"code": null,
"e": 10694,
"s": 10632,
"text": "We set the following parameters in the call to the optimizer:"
},
{
"code": null,
"e": 10763,
"s": 10694,
"text": "scoring = neg_mean_absolute error: Our regression performance metric"
},
{
"code": null,
"e": 10815,
"s": 10763,
"text": "max_time_minutes = 480: Limit evaluation to 8 hours"
},
{
"code": null,
"e": 10867,
"s": 10815,
"text": "n_jobs = -1: Use all available cores on the machine"
},
{
"code": null,
"e": 10934,
"s": 10867,
"text": "verbosity = 2: Show a limited amount of information while training"
},
{
"code": null,
"e": 10986,
"s": 10934,
"text": "cv = 5: Use 5-fold cross validation (default is 10)"
},
{
"code": null,
"e": 11207,
"s": 10986,
"text": "There are other parameters that control details of the genetic programming method, but leaving them at the default works well for most cases. (If you want to play around with the parameters, check out the documentation.)"
},
{
"code": null,
"e": 11351,
"s": 11207,
"text": "The syntax for TPOT optimizers is designed to be identical to that for Scikit-Learn models so we can train the optimizer using the .fit method."
},
{
"code": null,
"e": 11442,
"s": 11351,
"text": "# Fit the tpot optimizer on the training datatpot.fit(training_features, training_targets)"
},
{
"code": null,
"e": 11494,
"s": 11442,
"text": "During training, we get some information displayed:"
},
{
"code": null,
"e": 11724,
"s": 11494,
"text": "Due to the time limit, our model was only able to get through 15 generations. With 100 populations, this still represents 1500 different individual pipelines that were evaluated, quite a few more than we could have tried by hand!"
},
{
"code": null,
"e": 11860,
"s": 11724,
"text": "Once the model has trained, we can see the optimal pipeline using tpot.fitted_pipeline_. We can also save the model to a Python script:"
},
{
"code": null,
"e": 11946,
"s": 11860,
"text": "# Export the pipeline as a python script filetpot.export('tpot_exported_pipeline.py')"
},
{
"code": null,
"e": 12086,
"s": 11946,
"text": "Since we are in a Google Colab notebook, to get the pipeline onto a local machine from the server, we have to use the Google Colab library:"
},
{
"code": null,
"e": 12220,
"s": 12086,
"text": "# Import file managementfrom google.colab import file# Download the pipeline for local usefiles.download('tpot_exported_pipeline.py')"
},
{
"code": null,
"e": 12299,
"s": 12220,
"text": "We can then open the file (available here) and look at the completed pipeline:"
},
{
"code": null,
"e": 12797,
"s": 12299,
"text": "We see that the optimizer imputed the missing values for us and built a complete model pipeline! The final estimator is a stacked model meaning that it uses two machine learning algorithms ( LassoLarsCV and GradientBoostingRegressor ), the second of which is trained on the predictions of the first (If you run the notebook again, you may get a different model because the optimization process is stochastic). This is a complex method that I probably would not have been able to develop on my own!"
},
{
"code": null,
"e": 12918,
"s": 12797,
"text": "Now, the moment of truth: performance on the testing set. To find the mean absolute error, we can use the .score method:"
},
{
"code": null,
"e": 13002,
"s": 12918,
"text": "# Evaluate the final modelprint(tpot.score(testing_features, testing_targets))8.642"
},
{
"code": null,
"e": 13324,
"s": 13002,
"text": "In the series of articles where we developed a solution manually, after many hours of development, we built a Gradient Boosting Regressor model that achieved a mean absolute error of 9.06. Automated machine learning has significantly improved on the performance with a drastic reduction in the amount of development time."
},
{
"code": null,
"e": 13664,
"s": 13324,
"text": "From here, we can use the optimized pipeline and try to further refine the solution, or we can move on to other important phases of the data science pipeline. If we use this as our final model, we could try and interpret the model (such as by using LIME: Local Interpretable Model-Agnostic Explainations) or write a well-documented report."
},
{
"code": null,
"e": 14226,
"s": 13664,
"text": "In this post, we got a brief introduction to both the capabilities of the cloud and automated machine learning. With only a Google account and an internet connection, we can use Google Colab to develop, run, and share machine learning or data science work loads. Using TPOT, we can automatically develop an optimized machine learning pipeline with feature preprocessing, model selection, and hyperparameter tuning. Moreover, we saw that auto-ml will not replace the data scientist, but it will allow her to spend more time on higher value parts of the workflow."
},
{
"code": null,
"e": 14702,
"s": 14226,
"text": "While being an early adopter does not always pay off, in this case, TPOT is mature enough to be easy to use and relatively issue-free, yet also new enough that learning it will put you ahead of the curve. With that in mind, find a machine learning problem (perhaps through Kaggle) and try to solve it! Running automatic machine learning in a notebook on Google Colab feels like the future and with such a low barrier to entry, thereβs never been a better time to get started!"
}
] |
Bootstrap alert-dismissable class
|
The .alert-dismissable class in Bootstrap is used to close the alert.
You can try to run the following code to implement the alert-dismissable class in Bootstrap
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 = "alert alert-warning alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
Γ
</button>
Warning ! Donβt submit this.
</div>
<div class = "alert alert-danger alert-dismissable">
<button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
Γ
</button>
Error ! Change few things.
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "The .alert-dismissable class in Bootstrap is used to close the alert."
},
{
"code": null,
"e": 1224,
"s": 1132,
"text": "You can try to run the following code to implement the alert-dismissable class in Bootstrap"
},
{
"code": null,
"e": 1234,
"s": 1224,
"text": "Live Demo"
},
{
"code": null,
"e": 2011,
"s": 1234,
"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 = \"alert alert-warning alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n Γ\n </button>\n Warning ! Donβt submit this.\n </div>\n <div class = \"alert alert-danger alert-dismissable\">\n <button type = \"button\" class = \"close\" data-dismiss = \"alert\" aria-hidden = \"true\">\n Γ\n </button>\n Error ! Change few things.\n </div>\n </body>\n</html>"
}
] |
C++ Program for BogoSort or Permutation Sort - GeeksforGeeks
|
08 Jun, 2021
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, one would throw the deck into the air, pick the cards up at random, and repeat the process until the deck is sorted.
PseudoCode:
while not Sorted(list) do
shuffle (list)
done
CPP
// C++ implementation of Bogo Sort#include <bits/stdc++.h>using namespace std; // To check if array is sorted or notbool isSorted(int a[], int n){ while (--n > 1) if (a[n] < a[n - 1]) return false; return true;} // To generate permutation of the arrayvoid shuffle(int a[], int n){ for (int i = 0; i < n; i++) swap(a[i], a[rand() % n]);} // Sorts array a[0..n-1] using Bogo sortvoid bogosort(int a[], int n){ // if array is not sorted then shuffle // the array again while (!isSorted(a, n)) shuffle(a, n);} // prints the arrayvoid printArray(int a[], int n){ for (int i = 0; i < n; i++) printf("%d ", a[i]); printf("\n");} // Driver codeint main(){ int a[] = { 3, 2, 5, 1, 0, 4 }; int n = sizeof a / sizeof a[0]; bogosort(a, n); printf("Sorted array :\n"); printArray(a, n); return 0;}
Sorted array :
0 1 2 3 4 5
Please refer complete article on BogoSort or Permutation Sort for more details!
anikaseth98
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Const keyword in C++
Handling the Divide by Zero Exception in C++
|
[
{
"code": null,
"e": 24215,
"s": 24187,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 24741,
"s": 24215,
"text": "BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, one would throw the deck into the air, pick the cards up at random, and repeat the process until the deck is sorted. "
},
{
"code": null,
"e": 24755,
"s": 24741,
"text": "PseudoCode: "
},
{
"code": null,
"e": 24805,
"s": 24755,
"text": "while not Sorted(list) do\n shuffle (list)\ndone"
},
{
"code": null,
"e": 24811,
"s": 24807,
"text": "CPP"
},
{
"code": "// C++ implementation of Bogo Sort#include <bits/stdc++.h>using namespace std; // To check if array is sorted or notbool isSorted(int a[], int n){ while (--n > 1) if (a[n] < a[n - 1]) return false; return true;} // To generate permutation of the arrayvoid shuffle(int a[], int n){ for (int i = 0; i < n; i++) swap(a[i], a[rand() % n]);} // Sorts array a[0..n-1] using Bogo sortvoid bogosort(int a[], int n){ // if array is not sorted then shuffle // the array again while (!isSorted(a, n)) shuffle(a, n);} // prints the arrayvoid printArray(int a[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", a[i]); printf(\"\\n\");} // Driver codeint main(){ int a[] = { 3, 2, 5, 1, 0, 4 }; int n = sizeof a / sizeof a[0]; bogosort(a, n); printf(\"Sorted array :\\n\"); printArray(a, n); return 0;}",
"e": 25677,
"s": 24811,
"text": null
},
{
"code": null,
"e": 25704,
"s": 25677,
"text": "Sorted array :\n0 1 2 3 4 5"
},
{
"code": null,
"e": 25787,
"s": 25706,
"text": "Please refer complete article on BogoSort or Permutation Sort for more details! "
},
{
"code": null,
"e": 25799,
"s": 25787,
"text": "anikaseth98"
},
{
"code": null,
"e": 25812,
"s": 25799,
"text": "C++ Programs"
},
{
"code": null,
"e": 25820,
"s": 25812,
"text": "Sorting"
},
{
"code": null,
"e": 25828,
"s": 25820,
"text": "Sorting"
},
{
"code": null,
"e": 25926,
"s": 25828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25935,
"s": 25926,
"text": "Comments"
},
{
"code": null,
"e": 25948,
"s": 25935,
"text": "Old Comments"
},
{
"code": null,
"e": 25989,
"s": 25948,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 26048,
"s": 25989,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 26060,
"s": 26048,
"text": "cout in C++"
},
{
"code": null,
"e": 26081,
"s": 26060,
"text": "Const keyword in C++"
}
] |
Python time ctime() Method
|
Python time method ctime() converts a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. This function is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().
Following is the syntax for ctime() method β
time.ctime([ sec ])
sec β These are the number of seconds to be converted into string representation.
sec β These are the number of seconds to be converted into string representation.
This method does not return any value.
The following example shows the usage of ctime() method.
#!/usr/bin/python
import time
print "time.ctime() : %s" % time.ctime()
When we run above program, it produces following result β
time.ctime() : Tue Feb 17 10:00:18 2009
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2542,
"s": 2244,
"text": "Python time method ctime() converts a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. This function is equivalent to asctime(localtime(secs)). Locale information is not used by ctime()."
},
{
"code": null,
"e": 2587,
"s": 2542,
"text": "Following is the syntax for ctime() method β"
},
{
"code": null,
"e": 2608,
"s": 2587,
"text": "time.ctime([ sec ])\n"
},
{
"code": null,
"e": 2690,
"s": 2608,
"text": "sec β These are the number of seconds to be converted into string representation."
},
{
"code": null,
"e": 2772,
"s": 2690,
"text": "sec β These are the number of seconds to be converted into string representation."
},
{
"code": null,
"e": 2811,
"s": 2772,
"text": "This method does not return any value."
},
{
"code": null,
"e": 2868,
"s": 2811,
"text": "The following example shows the usage of ctime() method."
},
{
"code": null,
"e": 2940,
"s": 2868,
"text": "#!/usr/bin/python\nimport time\n\nprint \"time.ctime() : %s\" % time.ctime()"
},
{
"code": null,
"e": 2998,
"s": 2940,
"text": "When we run above program, it produces following result β"
},
{
"code": null,
"e": 3039,
"s": 2998,
"text": "time.ctime() : Tue Feb 17 10:00:18 2009\n"
},
{
"code": null,
"e": 3076,
"s": 3039,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3092,
"s": 3076,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3125,
"s": 3092,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3144,
"s": 3125,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3179,
"s": 3144,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3201,
"s": 3179,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3235,
"s": 3201,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3263,
"s": 3235,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3298,
"s": 3263,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3312,
"s": 3298,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3345,
"s": 3312,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3362,
"s": 3345,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3369,
"s": 3362,
"text": " Print"
},
{
"code": null,
"e": 3380,
"s": 3369,
"text": " Add Notes"
}
] |
Understanding Assertions Cypress
|
Cypress has a list of common assertions that can be applied to any element on the
browser. Assertions are the checkpoints that confirm if a test step of the automated
test case passed or failed. Thus it checks the expected state of the application under
test.
Cypress bundles the Chai, JQuery and Sinon libraries for assertions. Some of the
assertions are associated with the element along with the parent command and
cannot be used as a standalone command. For example, should().
However there are some assertions which act upon directly on the elements and
not dependent upon other commands. For example, expect(). Though Cypress
gives various assertions, there may be situations where Cypress automatically uses
the built in assertions without needing to explicitly use them.
These are known as Default Assertions. Some of them are listed below β
cy.visit () β awaits the page to display the text or html with 200 status code.
cy.visit () β awaits the page to display the text or html with 200 status code.
cy.request () β awaits the remote server to be present and give a response.
cy.request () β awaits the remote server to be present and give a response.
cy.contains () β awaits the element with content to be present in the DOM.
cy.contains () β awaits the element with content to be present in the DOM.
cy.get () β awaits the element to be present in DOM.
cy.get () β awaits the element to be present in DOM.
.find () β awaits the element to be present in DOM.
.find () β awaits the element to be present in DOM.
.type () β awaits the element to be in a type able state.
.type () β awaits the element to be in a type able state.
.click () β awaits the element to be in a clickable state.
.click () β awaits the element to be in a clickable state.
.its () β awaits the element to find a property on the present subject.
.its () β awaits the element to find a property on the present subject.
Some of the very common assertions are listed below β
Length β Verifies the count of the number of elements returned by the previously chained command.
Length β Verifies the count of the number of elements returned by the previously chained command.
cy.get('.product').should('have.length',1);
Value β Verifies if the element has a particular value.
Value β Verifies if the element has a particular value.
cy.get('.input-txt').should('have.value', 'Tutorialspoint');
Class β Verifies if the element contains or not contains the specified class or
not.
Class β Verifies if the element contains or not contains the specified class or
not.
cy.get('#tutor').find('a').should('have.class', 'enabled');
Text Content β Verifies if the element has a particular text.
Text Content β Verifies if the element has a particular text.
cy.get('.input-txt').parent('div').should('contain', 'Tutorialspoint');
Visibility β Verifies if the element is visible or not.
Visibility β Verifies if the element is visible or not.
cy.get('submit').should('be.visible');
Existence β Verifies if the element is present in the DOM.
Existence β Verifies if the element is present in the DOM.
cy.get('#gsc-id').should('not.exist');
CSS β Verifies the css properties of the element.
CSS β Verifies the css properties of the element.
cy.get('.text-area').should('have.css', 'text-highlight');
Code Implementation with assertion.
// test suite
describe('Tutorialspoint Test', function () {
// test case
it('Test Case1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/videotutorials/index.php");
// enter test in the edit box
cy.get("#search-strings").type("Java");
// wait for some time
cy.wait(3000);
// assertion to validate the number of search results
cy.get('.clsHeadQuestion'). should('have.length',19);
});
});
|
[
{
"code": null,
"e": 1322,
"s": 1062,
"text": "Cypress has a list of common assertions that can be applied to any element on the\nbrowser. Assertions are the checkpoints that confirm if a test step of the automated\ntest case passed or failed. Thus it checks the expected state of the application under\ntest."
},
{
"code": null,
"e": 1543,
"s": 1322,
"text": "Cypress bundles the Chai, JQuery and Sinon libraries for assertions. Some of the\nassertions are associated with the element along with the parent command and\ncannot be used as a standalone command. For example, should()."
},
{
"code": null,
"e": 1841,
"s": 1543,
"text": "However there are some assertions which act upon directly on the elements and\nnot dependent upon other commands. For example, expect(). Though Cypress\ngives various assertions, there may be situations where Cypress automatically uses\nthe built in assertions without needing to explicitly use them."
},
{
"code": null,
"e": 1912,
"s": 1841,
"text": "These are known as Default Assertions. Some of them are listed below β"
},
{
"code": null,
"e": 1992,
"s": 1912,
"text": "cy.visit () β awaits the page to display the text or html with 200 status code."
},
{
"code": null,
"e": 2072,
"s": 1992,
"text": "cy.visit () β awaits the page to display the text or html with 200 status code."
},
{
"code": null,
"e": 2148,
"s": 2072,
"text": "cy.request () β awaits the remote server to be present and give a response."
},
{
"code": null,
"e": 2224,
"s": 2148,
"text": "cy.request () β awaits the remote server to be present and give a response."
},
{
"code": null,
"e": 2299,
"s": 2224,
"text": "cy.contains () β awaits the element with content to be present in the DOM."
},
{
"code": null,
"e": 2374,
"s": 2299,
"text": "cy.contains () β awaits the element with content to be present in the DOM."
},
{
"code": null,
"e": 2427,
"s": 2374,
"text": "cy.get () β awaits the element to be present in DOM."
},
{
"code": null,
"e": 2480,
"s": 2427,
"text": "cy.get () β awaits the element to be present in DOM."
},
{
"code": null,
"e": 2532,
"s": 2480,
"text": ".find () β awaits the element to be present in DOM."
},
{
"code": null,
"e": 2584,
"s": 2532,
"text": ".find () β awaits the element to be present in DOM."
},
{
"code": null,
"e": 2642,
"s": 2584,
"text": ".type () β awaits the element to be in a type able state."
},
{
"code": null,
"e": 2700,
"s": 2642,
"text": ".type () β awaits the element to be in a type able state."
},
{
"code": null,
"e": 2759,
"s": 2700,
"text": ".click () β awaits the element to be in a clickable state."
},
{
"code": null,
"e": 2818,
"s": 2759,
"text": ".click () β awaits the element to be in a clickable state."
},
{
"code": null,
"e": 2890,
"s": 2818,
"text": ".its () β awaits the element to find a property on the present subject."
},
{
"code": null,
"e": 2962,
"s": 2890,
"text": ".its () β awaits the element to find a property on the present subject."
},
{
"code": null,
"e": 3016,
"s": 2962,
"text": "Some of the very common assertions are listed below β"
},
{
"code": null,
"e": 3114,
"s": 3016,
"text": "Length β Verifies the count of the number of elements returned by the previously chained command."
},
{
"code": null,
"e": 3212,
"s": 3114,
"text": "Length β Verifies the count of the number of elements returned by the previously chained command."
},
{
"code": null,
"e": 3256,
"s": 3212,
"text": "cy.get('.product').should('have.length',1);"
},
{
"code": null,
"e": 3312,
"s": 3256,
"text": "Value β Verifies if the element has a particular value."
},
{
"code": null,
"e": 3368,
"s": 3312,
"text": "Value β Verifies if the element has a particular value."
},
{
"code": null,
"e": 3429,
"s": 3368,
"text": "cy.get('.input-txt').should('have.value', 'Tutorialspoint');"
},
{
"code": null,
"e": 3514,
"s": 3429,
"text": "Class β Verifies if the element contains or not contains the specified class or\nnot."
},
{
"code": null,
"e": 3599,
"s": 3514,
"text": "Class β Verifies if the element contains or not contains the specified class or\nnot."
},
{
"code": null,
"e": 3659,
"s": 3599,
"text": "cy.get('#tutor').find('a').should('have.class', 'enabled');"
},
{
"code": null,
"e": 3721,
"s": 3659,
"text": "Text Content β Verifies if the element has a particular text."
},
{
"code": null,
"e": 3783,
"s": 3721,
"text": "Text Content β Verifies if the element has a particular text."
},
{
"code": null,
"e": 3855,
"s": 3783,
"text": "cy.get('.input-txt').parent('div').should('contain', 'Tutorialspoint');"
},
{
"code": null,
"e": 3911,
"s": 3855,
"text": "Visibility β Verifies if the element is visible or not."
},
{
"code": null,
"e": 3967,
"s": 3911,
"text": "Visibility β Verifies if the element is visible or not."
},
{
"code": null,
"e": 4006,
"s": 3967,
"text": "cy.get('submit').should('be.visible');"
},
{
"code": null,
"e": 4065,
"s": 4006,
"text": "Existence β Verifies if the element is present in the DOM."
},
{
"code": null,
"e": 4124,
"s": 4065,
"text": "Existence β Verifies if the element is present in the DOM."
},
{
"code": null,
"e": 4163,
"s": 4124,
"text": "cy.get('#gsc-id').should('not.exist');"
},
{
"code": null,
"e": 4213,
"s": 4163,
"text": "CSS β Verifies the css properties of the element."
},
{
"code": null,
"e": 4263,
"s": 4213,
"text": "CSS β Verifies the css properties of the element."
},
{
"code": null,
"e": 4322,
"s": 4263,
"text": "cy.get('.text-area').should('have.css', 'text-highlight');"
},
{
"code": null,
"e": 4358,
"s": 4322,
"text": "Code Implementation with assertion."
},
{
"code": null,
"e": 4839,
"s": 4358,
"text": "// test suite\ndescribe('Tutorialspoint Test', function () {\n // test case\n it('Test Case1', function (){\n // test step to launch a URL\n cy.visit(\"https://www.tutorialspoint.com/videotutorials/index.php\");\n // enter test in the edit box\n cy.get(\"#search-strings\").type(\"Java\");\n // wait for some time\n cy.wait(3000);\n // assertion to validate the number of search results\n cy.get('.clsHeadQuestion'). should('have.length',19);\n });\n});"
}
] |
Rexx - interpret
|
Interprets or executes the defined instruction.
Interpret command
command β The command sent to the interpret instruction.
command β The command sent to the interpret instruction.
Returns the output of the command sent to the interpret instruction.
/* Main program */
options arexx_bifs interpret
say 'Hello'
When we run the above program we will get the following result.
Hello
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2387,
"s": 2339,
"text": "Interprets or executes the defined instruction."
},
{
"code": null,
"e": 2407,
"s": 2387,
"text": "Interpret command \n"
},
{
"code": null,
"e": 2464,
"s": 2407,
"text": "command β The command sent to the interpret instruction."
},
{
"code": null,
"e": 2521,
"s": 2464,
"text": "command β The command sent to the interpret instruction."
},
{
"code": null,
"e": 2590,
"s": 2521,
"text": "Returns the output of the command sent to the interpret instruction."
},
{
"code": null,
"e": 2652,
"s": 2590,
"text": "/* Main program */ \noptions arexx_bifs interpret \nsay 'Hello'"
},
{
"code": null,
"e": 2716,
"s": 2652,
"text": "When we run the above program we will get the following result."
},
{
"code": null,
"e": 2723,
"s": 2716,
"text": "Hello\n"
},
{
"code": null,
"e": 2730,
"s": 2723,
"text": " Print"
},
{
"code": null,
"e": 2741,
"s": 2730,
"text": " Add Notes"
}
] |
Python Functools - total_ordering() - GeeksforGeeks
|
26 Mar, 2020
Functools module in python helps in implementing higher-order functions. Higher-order functions are dependent functions that call other functions. Total_ordering provides rich class comparison methods that help in comparing classes without explicitly defining a function for it. So, It helps in the redundancy of code.
The six rich class comparison methods are:
object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)
There are 2 essential conditions to implement these comparison methods:
At least one of the comparison methods must be defined from lt(less than), le(less than or equal to), gt(greater than) or ge(greater than or equal to).
The eq function must also be defined.
Example:
from functools import total_ordering @total_orderingclass Students: def __init__(self, cgpa): self.cgpa = cgpa def __lt__(self, other): return self.cgpa<other.cgpa def __eq__(self, other): return self.cgpa == other.cgpa def __le__(self, other): return self.cgpa<= other.cgpa def __ge__(self, other): return self.cgpa>= other.cgpa def __ne__(self, other): return self.cgpa != other.cgpa Arjun = Students(8.6) Ram = Students(7.5) print(Arjun.__lt__(Ram))print(Arjun.__le__(Ram))print(Arjun.__gt__(Ram))print(Arjun.__ge__(Ram))print(Arjun.__eq__(Ram))print(Arjun.__ne__(Ram))
Output
False
False
True
True
False
True
Note: Since the __gt__ method is not implemented, it shows βNot
Example 2:
from functools import total_ordering @total_orderingclass num: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): # Changing the functionality # of equality operator return self.value != other.value # Driver codeprint(num(2) < num(3))print(num(2) > num(3))print(num(3) == num(3))print(num(3) == num(5))
Output:
True
False
False
True
Python Decorators
Python functools-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24611,
"s": 24292,
"text": "Functools module in python helps in implementing higher-order functions. Higher-order functions are dependent functions that call other functions. Total_ordering provides rich class comparison methods that help in comparing classes without explicitly defining a function for it. So, It helps in the redundancy of code."
},
{
"code": null,
"e": 24654,
"s": 24611,
"text": "The six rich class comparison methods are:"
},
{
"code": null,
"e": 24681,
"s": 24654,
"text": "object.__lt__(self, other)"
},
{
"code": null,
"e": 24708,
"s": 24681,
"text": "object.__le__(self, other)"
},
{
"code": null,
"e": 24735,
"s": 24708,
"text": "object.__eq__(self, other)"
},
{
"code": null,
"e": 24762,
"s": 24735,
"text": "object.__ne__(self, other)"
},
{
"code": null,
"e": 24789,
"s": 24762,
"text": "object.__gt__(self, other)"
},
{
"code": null,
"e": 24816,
"s": 24789,
"text": "object.__ge__(self, other)"
},
{
"code": null,
"e": 24888,
"s": 24816,
"text": "There are 2 essential conditions to implement these comparison methods:"
},
{
"code": null,
"e": 25040,
"s": 24888,
"text": "At least one of the comparison methods must be defined from lt(less than), le(less than or equal to), gt(greater than) or ge(greater than or equal to)."
},
{
"code": null,
"e": 25078,
"s": 25040,
"text": "The eq function must also be defined."
},
{
"code": null,
"e": 25087,
"s": 25078,
"text": "Example:"
},
{
"code": "from functools import total_ordering @total_orderingclass Students: def __init__(self, cgpa): self.cgpa = cgpa def __lt__(self, other): return self.cgpa<other.cgpa def __eq__(self, other): return self.cgpa == other.cgpa def __le__(self, other): return self.cgpa<= other.cgpa def __ge__(self, other): return self.cgpa>= other.cgpa def __ne__(self, other): return self.cgpa != other.cgpa Arjun = Students(8.6) Ram = Students(7.5) print(Arjun.__lt__(Ram))print(Arjun.__le__(Ram))print(Arjun.__gt__(Ram))print(Arjun.__ge__(Ram))print(Arjun.__eq__(Ram))print(Arjun.__ne__(Ram))",
"e": 25748,
"s": 25087,
"text": null
},
{
"code": null,
"e": 25755,
"s": 25748,
"text": "Output"
},
{
"code": null,
"e": 25789,
"s": 25755,
"text": "False\nFalse\nTrue\nTrue\nFalse\nTrue\n"
},
{
"code": null,
"e": 25853,
"s": 25789,
"text": "Note: Since the __gt__ method is not implemented, it shows βNot"
},
{
"code": null,
"e": 25864,
"s": 25853,
"text": "Example 2:"
},
{
"code": "from functools import total_ordering @total_orderingclass num: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): # Changing the functionality # of equality operator return self.value != other.value # Driver codeprint(num(2) < num(3))print(num(2) > num(3))print(num(3) == num(3))print(num(3) == num(5))",
"e": 26332,
"s": 25864,
"text": null
},
{
"code": null,
"e": 26340,
"s": 26332,
"text": "Output:"
},
{
"code": null,
"e": 26362,
"s": 26340,
"text": "True\nFalse\nFalse\nTrue"
},
{
"code": null,
"e": 26380,
"s": 26362,
"text": "Python Decorators"
},
{
"code": null,
"e": 26404,
"s": 26380,
"text": "Python functools-module"
},
{
"code": null,
"e": 26411,
"s": 26404,
"text": "Python"
},
{
"code": null,
"e": 26509,
"s": 26411,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26518,
"s": 26509,
"text": "Comments"
},
{
"code": null,
"e": 26531,
"s": 26518,
"text": "Old Comments"
},
{
"code": null,
"e": 26563,
"s": 26531,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26619,
"s": 26563,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26674,
"s": 26619,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26716,
"s": 26674,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26758,
"s": 26716,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26789,
"s": 26758,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26828,
"s": 26789,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26857,
"s": 26828,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26879,
"s": 26857,
"text": "Defaultdict in Python"
}
] |
How to Sort object of objects by its key value JavaScript
|
Letβs say, we have an object with keys as string literals and their values as objects as well like
this β
const companies = {
'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
}
We are required to write a function that sorts the object according to its keys and returns it.
const companies = {
'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
};
const sortKeys = (obj) => {
return Object.assign(...Object.entries(obj).sort().map(([key, value])
=> {
return {
[key]: value
}
}));
};
console.log(sortKeys(companies));
The output in the console will be β
{
ambicure: { employees: 170, worth: '0.1m', CEO: 'Preetam Chawla' },
'colin & co': { employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
'dis n dat': { employees: 540, worth: '1m', CEO: 'Mohit Sharma' },
'landwaves ltd': { employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal' },
'motilal biscuits': { employees: 975, worth: '1m', CEO: 'Rahul Gupta' },
numbtree: { employees: 1500, worth: '1.5m', CEO: 'Jay Kumar' },
'solace pvt ltd': { employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'
}
}
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "Letβs say, we have an object with keys as string literals and their values as objects as well like\nthis β"
},
{
"code": null,
"e": 1699,
"s": 1168,
"text": "const companies = {\n 'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},\n 'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},\n 'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},\n 'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},\n 'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},\n 'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},\n 'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},\n}"
},
{
"code": null,
"e": 1795,
"s": 1699,
"text": "We are required to write a function that sorts the object according to its keys and returns it."
},
{
"code": null,
"e": 2526,
"s": 1795,
"text": "const companies = {\n 'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},\n 'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},\n 'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},\n 'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},\n 'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},\n 'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},\n 'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},\n};\nconst sortKeys = (obj) => {\n return Object.assign(...Object.entries(obj).sort().map(([key, value])\n => {\n return {\n [key]: value\n }\n }));\n};\nconsole.log(sortKeys(companies));"
},
{
"code": null,
"e": 2562,
"s": 2526,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 3086,
"s": 2562,
"text": "{\n ambicure: { employees: 170, worth: '0.1m', CEO: 'Preetam Chawla' },\n 'colin & co': { employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},\n 'dis n dat': { employees: 540, worth: '1m', CEO: 'Mohit Sharma' },\n 'landwaves ltd': { employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal' },\n 'motilal biscuits': { employees: 975, worth: '1m', CEO: 'Rahul Gupta' },\n numbtree: { employees: 1500, worth: '1.5m', CEO: 'Jay Kumar' },\n 'solace pvt ltd': { employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'\n }\n}"
}
] |
Check for NULL or empty variable in a MySQL stored procedure
|
To check for NULL or empty variable, use the IF condition. Let us create a stored procedure β
mysql> delimiter //
mysql> create procedure checkingForNullDemo(Name varchar(20))
begin
if Name is NULL OR Name='' then
select 'Adam Smith';
else
select Name;
end if ;
end
//
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
Case 1
When NULL is passed. Call the stored procedure using call command
mysql> call checkingForNullDemo(NULL);
This will produce the following output β
+------------+
| Adam Smith |
+------------+
| Adam Smith |
+------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Case 2
When a value is passed. Call the stored procedure using the call command
mysql> call checkingForNullDemo('John Doe');
This will produce the following output β
+----------+
| Name |
+----------+
| John Doe |
+----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
|
[
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To check for NULL or empty variable, use the IF condition. Let us create a stored procedure β"
},
{
"code": null,
"e": 1427,
"s": 1156,
"text": "mysql> delimiter //\nmysql> create procedure checkingForNullDemo(Name varchar(20))\n begin\n if Name is NULL OR Name='' then\n select 'Adam Smith';\n else\n select Name;\n end if ;\n end\n //\nQuery OK, 0 rows affected (0.00 sec)\nmysql> delimiter ;"
},
{
"code": null,
"e": 1434,
"s": 1427,
"text": "Case 1"
},
{
"code": null,
"e": 1500,
"s": 1434,
"text": "When NULL is passed. Call the stored procedure using call command"
},
{
"code": null,
"e": 1539,
"s": 1500,
"text": "mysql> call checkingForNullDemo(NULL);"
},
{
"code": null,
"e": 1580,
"s": 1539,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1727,
"s": 1580,
"text": "+------------+\n| Adam Smith |\n+------------+\n| Adam Smith |\n+------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected, 1 warning (0.00 sec)"
},
{
"code": null,
"e": 1734,
"s": 1727,
"text": "Case 2"
},
{
"code": null,
"e": 1807,
"s": 1734,
"text": "When a value is passed. Call the stored procedure using the call command"
},
{
"code": null,
"e": 1852,
"s": 1807,
"text": "mysql> call checkingForNullDemo('John Doe');"
},
{
"code": null,
"e": 1893,
"s": 1852,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2019,
"s": 1893,
"text": "+----------+\n| Name |\n+----------+\n| John Doe |\n+----------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.00 sec)"
}
] |
Log Book β Guide to Distance Measuring Approaches for K- Means Clustering | by dearC | Towards Data Science
|
Letβs begin with a brief introduction of clustering. Clustering is the task of dividing the data points into a number of groups such that data points in the same groups are more similar to other data points in the same group than those in other groups. In simple words, the aim is to segregate groups with similar features and assign them into clusters.
K-Means Clustering is one of the many clustering algorithms. The idea behind it is to define clusters so that the total intra-cluster variation (known as total within-cluster variation) is minimized. K-means algorithm can be summarized as follow:
1. Specify the number of clusters(k) to be created.2. Select randomly k objects from the data-set as the initial cluster centers or means.3. Assign each observation to their closest centroid, based on the specified distance[the type of distance is what we will be exploring in this article, in the above case it is Euclidean] between the object and the centroid.4. For each of the k clusters update the cluster centroid by calculating the new mean values of all the data points in the cluster. The centroid of a K-th cluster is a vector of length p containing the means of all variables for the observations in the K-th cluster; p is the number of variables.5. Iteratively minimize the total within sum of square. That is, iterate steps 3 and 4 until the cluster assignments stop changing or the maximum number of iterations is reached.
In R we calculate the K-Means cluster by:
Kmeans(x, centers, iter.max = 10, nstart = 1, method = "euclidean")wherex > Data framecenters > Number of clustersiter.max > The maximum number of iterations allowednstart > How many random sets of center should be chosenmethod > The distance measure to be usedThere are other options too of calculating kmeans clustering but this is the usual pattern.
There are different distance calculation methods like euclidean, maximum( Chebychev Distance), manhattan, hamming, canberra, pearson , abspearson , abscorrelation, spearman or kendall. So how do you choose which one to use?
The methods are defined into 2 groups, one is based on capturing the geometrical separation and another one is dependent on correlation. We will take a look at each.
Euclidean, Manhattan & Maximum(Chebychev) distance
To begin with, a lot of this material in this section has been referred from the now offline page of divingintodatascience, the site had been of great help.
Minkowski distance is a metric which tells us the distance between 2 points in space. Now Minkowski distance come of different orders and we will shortly see what it means and we will also see why I am talking about it instead of Euclidean and other distances.
The generic formula for Minkowski distance for 2 points p and q:
is given by:
Minkowski distance is typically used with r being 1 or 2, which correspond to the Manhattan distance and the Euclidean distance respectively. In the limiting case of r reaching infinity, we obtain the Chebychev distance.
An easier way to understand is with the below picture
Manhattan distance captures the distance between two points by aggregating the pairwise absolute difference between each variable while Euclidean distance captures the same by aggregating the squared difference in each variable. Therefore, if two points are close on most variables, but more discrepant on one of them, Euclidean distance will exaggerate that discrepancy, whereas Manhattan distance will shrug it off, being more influenced by the closeness of the other variables. The Chebychev distance calculates the maximum of the absolute differences between the features of a pair of data points.
Manhattan distance should give more robust results, whereas Euclidean distance is likely to be influenced by outliers. Same applies to the higher values of βpβ in Minkowski distance formula. As we increase the value of p, distance measure become more susceptible to lose the robustness and outliers in few dimensions start dominating the distance value.
An interesting observation can be made about the difference among these if we draw a βCircleβ using these different distance measures instead of default Euclidean one. As we know that a Circle is the locus of a point equidistant from a given point, the center of the circle. Now, if we use Manhattan or Chebychev distance measures to measure the distance of points from center, we actually get βsquaresβ instead of usual βround-shapeβ circles.
Canberra Distance
It is a weighted version of Manhattan distance. It measures the sum of absolute fractional differences between the features of a pair of data points and is very sensitive to a small change when both coordinates are nearest to zero.
Hamming Distance
For categorical variables (male/female, or small/medium/large), we can define the distance as 0 if two points are in the same category, and 1 otherwise. If all the variables are categorical, then you can use Hamming distance, which counts the number of mismatches. You can also expand categorical variables to indicator variables, one for each level of the variable.If the categories are ordered (like small/medium/large) so that some categories are βcloserβ to each other than others, then you can convert them to a numerical sequence. For example, (small/medium/large) might map to (1/2/3). Then you can use Euclidean distance, or other distances for quantitative data.
Mahalanobis Distance
We can think of the Mahalanobis distance from a point to its respective cluster center as its Euclidean distance divided by the square root of the variance in the direction of the point. The Mahalanobis distance metric is preferable to the Euclidean distance metric because it allows for some flexibility in the structure of the clusters and takes into account variances and covariances amongst the variables.
When you use Euclidean distance, you assume that the clusters have identity covariances. In 2D, this means that your clusters have circular shapes. Obviously, if the covariances of the natural groupings in your data are not identity matrices, e.g. in 2D, clusters have elliptical shaped covariances, then using Mahalanobis over Euclidean will be much better modeling.
Correlation-based distance considers two objects to be similar if their features are highly correlated, even though the observed values may be far apart in terms of geometrical distance. The distance between two objects is 0 when they are perfectly correlated. If you want to identify clusters of observations with the same overall profiles regardless of their magnitudes, then you should go with correlation-based distance as a dissimilarity measure.
If Euclidean distance is chosen, then observations with high values of features will be clustered together. The same holds true for observations with low values of features.
Pearson correlation distance
Pearson correlation measures the degree of a linear relationship between two profiles. Pearson correlation analysis is the most commonly used method. It is also known as a parametric correlation which depends on the distribution of the data. This distance is based on the Pearson correlation coefficient that is calculated from the sample values and their standard deviations. The correlation coefficient βrβ takes values from β1 (large, negative correlation) to +1 (large, positive correlation).
There are a few other variants of this distance:
Absolute Pearson Correlation distance : In this distance, the absolute value of the Pearson correlation coefficient is used; hence the corresponding distance lies between 0 and 1.Un-centered Correlation distance: This is the same as the Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between β1 and +1; hence the distance lies between 0 and 2.Absolute, Un-centered Correlation distance: This is the same as the Absolute Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between 0 and +1; hence the distance lies between 0 and 1.
Absolute Pearson Correlation distance : In this distance, the absolute value of the Pearson correlation coefficient is used; hence the corresponding distance lies between 0 and 1.
Un-centered Correlation distance: This is the same as the Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between β1 and +1; hence the distance lies between 0 and 2.
Absolute, Un-centered Correlation distance: This is the same as the Absolute Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between 0 and +1; hence the distance lies between 0 and 1.
Eisen cosine correlation distance
Itβs a special case of Pearsonβs correlation with x Μ and y Μ both replaced by zero:
Spearman & Kendall correlation distance
The Spearman correlation between two variables is equal to the Pearson correlation between the rank values of those two variables; while Pearsonβs correlation assesses linear relationships, Spearmanβs correlation assesses monotonic relationships (whether linear or not). If there are no repeated data values, a perfect Spearman correlation of +1 or β1 occurs when each of the variables is a perfect monotone function of the other.
Intuitively, the Spearman correlation between two variables will be high when observations have a similar (or identical for a correlation of 1) rank (i.e. relative position label of the observations within the variable: 1st, 2nd, 3rd, etc.) between the two variables, and low when observations have a dissimilar (or fully opposed for a correlation of β1) rank between the two variables.
The Kendall tau rank distance is a metric that counts the number of pairwise disagreements between two ranking lists. The larger the distance, the more dissimilar the two lists are. Kendall tau distance is also called bubble-sort distance since it is equivalent to the number of swaps that the bubble sort algorithm would take to place one list in the same order as the other list.
Spearmanβs coefficient is appropriate for both continuous and discrete ordinal variables. Both Spearmanβs Ο and Kendallβs Ο can be formulated as special cases of a more general correlation coefficient.
The value of distance measures is intimately related to the scale on which measurements are made. Therefore, variables are often scaled before measuring the inter-observation dissimilarities. This is particularly recommended when variables are measured in different scales (e.g: kilograms, kilometers, centimeters, ...); otherwise, the dissimilarity measures obtained will be severely affected.Standardization makes the four distance measure methods β Euclidean, Manhattan, Correlation and Eisen β more similar than they would be with non-transformed data. Note that, when the data are standardized, there is a functional relationship between the Pearson correlation coefficient & Euclidean distance.k-means works with continuous variables. It should not be done with data of mixed types. When your data consist of variables of mixed types, you can try using Gowerβs distance. There is an overview of Gowerβs distance here.
The value of distance measures is intimately related to the scale on which measurements are made. Therefore, variables are often scaled before measuring the inter-observation dissimilarities. This is particularly recommended when variables are measured in different scales (e.g: kilograms, kilometers, centimeters, ...); otherwise, the dissimilarity measures obtained will be severely affected.Standardization makes the four distance measure methods β Euclidean, Manhattan, Correlation and Eisen β more similar than they would be with non-transformed data. Note that, when the data are standardized, there is a functional relationship between the Pearson correlation coefficient & Euclidean distance.
k-means works with continuous variables. It should not be done with data of mixed types. When your data consist of variables of mixed types, you can try using Gowerβs distance. There is an overview of Gowerβs distance here.
There is only a best distance measure for a given data-set. The choice of the distance measure WILL influence your clustering, but it depends on the data-set and on the objective, which distance measure is most adequate for your particular application.
|
[
{
"code": null,
"e": 401,
"s": 47,
"text": "Letβs begin with a brief introduction of clustering. Clustering is the task of dividing the data points into a number of groups such that data points in the same groups are more similar to other data points in the same group than those in other groups. In simple words, the aim is to segregate groups with similar features and assign them into clusters."
},
{
"code": null,
"e": 648,
"s": 401,
"text": "K-Means Clustering is one of the many clustering algorithms. The idea behind it is to define clusters so that the total intra-cluster variation (known as total within-cluster variation) is minimized. K-means algorithm can be summarized as follow:"
},
{
"code": null,
"e": 1485,
"s": 648,
"text": "1. Specify the number of clusters(k) to be created.2. Select randomly k objects from the data-set as the initial cluster centers or means.3. Assign each observation to their closest centroid, based on the specified distance[the type of distance is what we will be exploring in this article, in the above case it is Euclidean] between the object and the centroid.4. For each of the k clusters update the cluster centroid by calculating the new mean values of all the data points in the cluster. The centroid of a K-th cluster is a vector of length p containing the means of all variables for the observations in the K-th cluster; p is the number of variables.5. Iteratively minimize the total within sum of square. That is, iterate steps 3 and 4 until the cluster assignments stop changing or the maximum number of iterations is reached."
},
{
"code": null,
"e": 1527,
"s": 1485,
"text": "In R we calculate the K-Means cluster by:"
},
{
"code": null,
"e": 1892,
"s": 1527,
"text": "Kmeans(x, centers, iter.max = 10, nstart = 1, method = \"euclidean\")wherex > Data framecenters > Number of clustersiter.max > The maximum number of iterations allowednstart > How many random sets of center should be chosenmethod > The distance measure to be usedThere are other options too of calculating kmeans clustering but this is the usual pattern."
},
{
"code": null,
"e": 2116,
"s": 1892,
"text": "There are different distance calculation methods like euclidean, maximum( Chebychev Distance), manhattan, hamming, canberra, pearson , abspearson , abscorrelation, spearman or kendall. So how do you choose which one to use?"
},
{
"code": null,
"e": 2282,
"s": 2116,
"text": "The methods are defined into 2 groups, one is based on capturing the geometrical separation and another one is dependent on correlation. We will take a look at each."
},
{
"code": null,
"e": 2333,
"s": 2282,
"text": "Euclidean, Manhattan & Maximum(Chebychev) distance"
},
{
"code": null,
"e": 2490,
"s": 2333,
"text": "To begin with, a lot of this material in this section has been referred from the now offline page of divingintodatascience, the site had been of great help."
},
{
"code": null,
"e": 2751,
"s": 2490,
"text": "Minkowski distance is a metric which tells us the distance between 2 points in space. Now Minkowski distance come of different orders and we will shortly see what it means and we will also see why I am talking about it instead of Euclidean and other distances."
},
{
"code": null,
"e": 2816,
"s": 2751,
"text": "The generic formula for Minkowski distance for 2 points p and q:"
},
{
"code": null,
"e": 2829,
"s": 2816,
"text": "is given by:"
},
{
"code": null,
"e": 3050,
"s": 2829,
"text": "Minkowski distance is typically used with r being 1 or 2, which correspond to the Manhattan distance and the Euclidean distance respectively. In the limiting case of r reaching infinity, we obtain the Chebychev distance."
},
{
"code": null,
"e": 3104,
"s": 3050,
"text": "An easier way to understand is with the below picture"
},
{
"code": null,
"e": 3706,
"s": 3104,
"text": "Manhattan distance captures the distance between two points by aggregating the pairwise absolute difference between each variable while Euclidean distance captures the same by aggregating the squared difference in each variable. Therefore, if two points are close on most variables, but more discrepant on one of them, Euclidean distance will exaggerate that discrepancy, whereas Manhattan distance will shrug it off, being more influenced by the closeness of the other variables. The Chebychev distance calculates the maximum of the absolute differences between the features of a pair of data points."
},
{
"code": null,
"e": 4060,
"s": 3706,
"text": "Manhattan distance should give more robust results, whereas Euclidean distance is likely to be influenced by outliers. Same applies to the higher values of βpβ in Minkowski distance formula. As we increase the value of p, distance measure become more susceptible to lose the robustness and outliers in few dimensions start dominating the distance value."
},
{
"code": null,
"e": 4504,
"s": 4060,
"text": "An interesting observation can be made about the difference among these if we draw a βCircleβ using these different distance measures instead of default Euclidean one. As we know that a Circle is the locus of a point equidistant from a given point, the center of the circle. Now, if we use Manhattan or Chebychev distance measures to measure the distance of points from center, we actually get βsquaresβ instead of usual βround-shapeβ circles."
},
{
"code": null,
"e": 4522,
"s": 4504,
"text": "Canberra Distance"
},
{
"code": null,
"e": 4754,
"s": 4522,
"text": "It is a weighted version of Manhattan distance. It measures the sum of absolute fractional differences between the features of a pair of data points and is very sensitive to a small change when both coordinates are nearest to zero."
},
{
"code": null,
"e": 4771,
"s": 4754,
"text": "Hamming Distance"
},
{
"code": null,
"e": 5443,
"s": 4771,
"text": "For categorical variables (male/female, or small/medium/large), we can define the distance as 0 if two points are in the same category, and 1 otherwise. If all the variables are categorical, then you can use Hamming distance, which counts the number of mismatches. You can also expand categorical variables to indicator variables, one for each level of the variable.If the categories are ordered (like small/medium/large) so that some categories are βcloserβ to each other than others, then you can convert them to a numerical sequence. For example, (small/medium/large) might map to (1/2/3). Then you can use Euclidean distance, or other distances for quantitative data."
},
{
"code": null,
"e": 5464,
"s": 5443,
"text": "Mahalanobis Distance"
},
{
"code": null,
"e": 5874,
"s": 5464,
"text": "We can think of the Mahalanobis distance from a point to its respective cluster center as its Euclidean distance divided by the square root of the variance in the direction of the point. The Mahalanobis distance metric is preferable to the Euclidean distance metric because it allows for some flexibility in the structure of the clusters and takes into account variances and covariances amongst the variables."
},
{
"code": null,
"e": 6242,
"s": 5874,
"text": "When you use Euclidean distance, you assume that the clusters have identity covariances. In 2D, this means that your clusters have circular shapes. Obviously, if the covariances of the natural groupings in your data are not identity matrices, e.g. in 2D, clusters have elliptical shaped covariances, then using Mahalanobis over Euclidean will be much better modeling."
},
{
"code": null,
"e": 6694,
"s": 6242,
"text": "Correlation-based distance considers two objects to be similar if their features are highly correlated, even though the observed values may be far apart in terms of geometrical distance. The distance between two objects is 0 when they are perfectly correlated. If you want to identify clusters of observations with the same overall profiles regardless of their magnitudes, then you should go with correlation-based distance as a dissimilarity measure."
},
{
"code": null,
"e": 6868,
"s": 6694,
"text": "If Euclidean distance is chosen, then observations with high values of features will be clustered together. The same holds true for observations with low values of features."
},
{
"code": null,
"e": 6897,
"s": 6868,
"text": "Pearson correlation distance"
},
{
"code": null,
"e": 7394,
"s": 6897,
"text": "Pearson correlation measures the degree of a linear relationship between two profiles. Pearson correlation analysis is the most commonly used method. It is also known as a parametric correlation which depends on the distribution of the data. This distance is based on the Pearson correlation coefficient that is calculated from the sample values and their standard deviations. The correlation coefficient βrβ takes values from β1 (large, negative correlation) to +1 (large, positive correlation)."
},
{
"code": null,
"e": 7443,
"s": 7394,
"text": "There are a few other variants of this distance:"
},
{
"code": null,
"e": 8191,
"s": 7443,
"text": "Absolute Pearson Correlation distance : In this distance, the absolute value of the Pearson correlation coefficient is used; hence the corresponding distance lies between 0 and 1.Un-centered Correlation distance: This is the same as the Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between β1 and +1; hence the distance lies between 0 and 2.Absolute, Un-centered Correlation distance: This is the same as the Absolute Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between 0 and +1; hence the distance lies between 0 and 1."
},
{
"code": null,
"e": 8371,
"s": 8191,
"text": "Absolute Pearson Correlation distance : In this distance, the absolute value of the Pearson correlation coefficient is used; hence the corresponding distance lies between 0 and 1."
},
{
"code": null,
"e": 8647,
"s": 8371,
"text": "Un-centered Correlation distance: This is the same as the Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between β1 and +1; hence the distance lies between 0 and 2."
},
{
"code": null,
"e": 8941,
"s": 8647,
"text": "Absolute, Un-centered Correlation distance: This is the same as the Absolute Pearson correlation, except that the sample means are set to zero in the expression for un-centered correlation. The un-centered correlation coefficient lies between 0 and +1; hence the distance lies between 0 and 1."
},
{
"code": null,
"e": 8975,
"s": 8941,
"text": "Eisen cosine correlation distance"
},
{
"code": null,
"e": 9060,
"s": 8975,
"text": "Itβs a special case of Pearsonβs correlation with x Μ and y Μ both replaced by zero:"
},
{
"code": null,
"e": 9100,
"s": 9060,
"text": "Spearman & Kendall correlation distance"
},
{
"code": null,
"e": 9531,
"s": 9100,
"text": "The Spearman correlation between two variables is equal to the Pearson correlation between the rank values of those two variables; while Pearsonβs correlation assesses linear relationships, Spearmanβs correlation assesses monotonic relationships (whether linear or not). If there are no repeated data values, a perfect Spearman correlation of +1 or β1 occurs when each of the variables is a perfect monotone function of the other."
},
{
"code": null,
"e": 9918,
"s": 9531,
"text": "Intuitively, the Spearman correlation between two variables will be high when observations have a similar (or identical for a correlation of 1) rank (i.e. relative position label of the observations within the variable: 1st, 2nd, 3rd, etc.) between the two variables, and low when observations have a dissimilar (or fully opposed for a correlation of β1) rank between the two variables."
},
{
"code": null,
"e": 10300,
"s": 9918,
"text": "The Kendall tau rank distance is a metric that counts the number of pairwise disagreements between two ranking lists. The larger the distance, the more dissimilar the two lists are. Kendall tau distance is also called bubble-sort distance since it is equivalent to the number of swaps that the bubble sort algorithm would take to place one list in the same order as the other list."
},
{
"code": null,
"e": 10502,
"s": 10300,
"text": "Spearmanβs coefficient is appropriate for both continuous and discrete ordinal variables. Both Spearmanβs Ο and Kendallβs Ο can be formulated as special cases of a more general correlation coefficient."
},
{
"code": null,
"e": 11426,
"s": 10502,
"text": "The value of distance measures is intimately related to the scale on which measurements are made. Therefore, variables are often scaled before measuring the inter-observation dissimilarities. This is particularly recommended when variables are measured in different scales (e.g: kilograms, kilometers, centimeters, ...); otherwise, the dissimilarity measures obtained will be severely affected.Standardization makes the four distance measure methods β Euclidean, Manhattan, Correlation and Eisen β more similar than they would be with non-transformed data. Note that, when the data are standardized, there is a functional relationship between the Pearson correlation coefficient & Euclidean distance.k-means works with continuous variables. It should not be done with data of mixed types. When your data consist of variables of mixed types, you can try using Gowerβs distance. There is an overview of Gowerβs distance here."
},
{
"code": null,
"e": 12127,
"s": 11426,
"text": "The value of distance measures is intimately related to the scale on which measurements are made. Therefore, variables are often scaled before measuring the inter-observation dissimilarities. This is particularly recommended when variables are measured in different scales (e.g: kilograms, kilometers, centimeters, ...); otherwise, the dissimilarity measures obtained will be severely affected.Standardization makes the four distance measure methods β Euclidean, Manhattan, Correlation and Eisen β more similar than they would be with non-transformed data. Note that, when the data are standardized, there is a functional relationship between the Pearson correlation coefficient & Euclidean distance."
},
{
"code": null,
"e": 12351,
"s": 12127,
"text": "k-means works with continuous variables. It should not be done with data of mixed types. When your data consist of variables of mixed types, you can try using Gowerβs distance. There is an overview of Gowerβs distance here."
}
] |
Android - SQLite Database
|
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c
The main package is android.database.sqlite that contains the classes to manage your own databases
In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Apart from this , there are other functions available in the database package , that does this job. They are listed below
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase method.
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath()
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same job but take some additional parameter is given below
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing data in database using bind arguments
We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes
getColumnCount()
This method return the total number of columns of the table.
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column
getColumnNames()
This method returns the array of all the column names of the table.
getCount()
This method returns the total number of rows in the cursor
getPosition()
This method returns the current position of the cursor in the table
isClosed()
This method returns true if the cursor is closed and return false otherwise
For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera is supported.
Following is the content of the modified MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
Following is the modified content of display contact activity DisplayContact.java
package com.example.sairamkrishna.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(),
phone.getText().toString(), email.getText().toString(),
street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(),
email.getText().toString(), street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}
}
Following is the content of Database class DBHelper.java
package com.example.sairamkrishna.myapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
Following is the content of the 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</ScrollView>
</RelativeLayout>
Following is the content of the res/layout/activity_display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>
<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />
</RelativeLayout>
</ScrollView>
Following is the content of the res/value/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete it.</string>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
</menu>
Following is the content of the res/menu/display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>
</menu>
This is the defualt AndroidManifest.xml of this project
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DisplayContact"/>
</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 Run icon from the tool bar. Before starting your application,Android studio will display following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display following screen β
Now open your optional menu, it will show as below image: Optional menu appears different places on different versions
Click on the add button of the menu screen to add a new contact. It will display the following screen β
It will display the following fields. Please enter the required information and click on save contact. It will bring you back to main screen.
Now our contact sai has been added.In order to see that where is your database is created. Open your android studio, connect your mobile. Go tools/android/android device monitor. Now browse the file explorer tab. Now browse this folder /data/data/<your.package.name>/databases<database-name>.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3751,
"s": 3607,
"text": "SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation."
},
{
"code": null,
"e": 3919,
"s": 3751,
"text": "SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c"
},
{
"code": null,
"e": 4018,
"s": 3919,
"text": "The main package is android.database.sqlite that contains the classes to manage your own databases"
},
{
"code": null,
"e": 4265,
"s": 4018,
"text": "In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below"
},
{
"code": null,
"e": 4356,
"s": 4265,
"text": "SQLiteDatabase mydatabase = openOrCreateDatabase(\"your database name\",MODE_PRIVATE,null);\n"
},
{
"code": null,
"e": 4478,
"s": 4356,
"text": "Apart from this , there are other functions available in the database package , that does this job. They are listed below"
},
{
"code": null,
"e": 4588,
"s": 4478,
"text": "openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)"
},
{
"code": null,
"e": 4725,
"s": 4588,
"text": "This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY"
},
{
"code": null,
"e": 4800,
"s": 4725,
"text": "openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)"
},
{
"code": null,
"e": 4942,
"s": 4800,
"text": "It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases"
},
{
"code": null,
"e": 5014,
"s": 4942,
"text": "openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)"
},
{
"code": null,
"e": 5124,
"s": 5014,
"text": "It not only opens but create the database if it not exists. This method is equivalent to openDatabase method."
},
{
"code": null,
"e": 5194,
"s": 5124,
"text": "openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)"
},
{
"code": null,
"e": 5329,
"s": 5194,
"text": "This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath()"
},
{
"code": null,
"e": 5455,
"s": 5329,
"text": "we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below"
},
{
"code": null,
"e": 5632,
"s": 5455,
"text": "mydatabase.execSQL(\"CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);\");\nmydatabase.execSQL(\"INSERT INTO TutorialsPoint VALUES('admin','admin');\");\n"
},
{
"code": null,
"e": 5786,
"s": 5632,
"text": "This will insert some values into our table in our database. Another method that also does the same job but take some additional parameter is given below"
},
{
"code": null,
"e": 5825,
"s": 5786,
"text": "execSQL(String sql, Object[] bindArgs)"
},
{
"code": null,
"e": 5949,
"s": 5825,
"text": "This method not only insert data , but also used to update or modify already existing data in database using bind arguments"
},
{
"code": null,
"e": 6201,
"s": 5949,
"text": "We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data."
},
{
"code": null,
"e": 6387,
"s": 6201,
"text": "Cursor resultSet = mydatbase.rawQuery(\"Select * from TutorialsPoint\",null);\nresultSet.moveToFirst();\nString username = resultSet.getString(0);\nString password = resultSet.getString(1);\n"
},
{
"code": null,
"e": 6506,
"s": 6387,
"text": "There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes"
},
{
"code": null,
"e": 6523,
"s": 6506,
"text": "getColumnCount()"
},
{
"code": null,
"e": 6584,
"s": 6523,
"text": "This method return the total number of columns of the table."
},
{
"code": null,
"e": 6618,
"s": 6584,
"text": "getColumnIndex(String columnName)"
},
{
"code": null,
"e": 6704,
"s": 6618,
"text": "This method returns the index number of a column by specifying the name of the column"
},
{
"code": null,
"e": 6735,
"s": 6704,
"text": "getColumnName(int columnIndex)"
},
{
"code": null,
"e": 6816,
"s": 6735,
"text": "This method returns the name of the column by specifying the index of the column"
},
{
"code": null,
"e": 6833,
"s": 6816,
"text": "getColumnNames()"
},
{
"code": null,
"e": 6901,
"s": 6833,
"text": "This method returns the array of all the column names of the table."
},
{
"code": null,
"e": 6912,
"s": 6901,
"text": "getCount()"
},
{
"code": null,
"e": 6971,
"s": 6912,
"text": "This method returns the total number of rows in the cursor"
},
{
"code": null,
"e": 6985,
"s": 6971,
"text": "getPosition()"
},
{
"code": null,
"e": 7053,
"s": 6985,
"text": "This method returns the current position of the cursor in the table"
},
{
"code": null,
"e": 7064,
"s": 7053,
"text": "isClosed()"
},
{
"code": null,
"e": 7140,
"s": 7064,
"text": "This method returns true if the cursor is closed and return false otherwise"
},
{
"code": null,
"e": 7353,
"s": 7140,
"text": "For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is given below"
},
{
"code": null,
"e": 7605,
"s": 7353,
"text": "public class DBHelper extends SQLiteOpenHelper {\n public DBHelper(){\n super(context,DATABASE_NAME,null,1);\n }\n public void onCreate(SQLiteDatabase db) {}\n public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}\n}"
},
{
"code": null,
"e": 7769,
"s": 7605,
"text": "Here is an example demonstrating the use of SQLite Database. It creates a basic contacts applications that allows insertion, deletion and modification of contacts."
},
{
"code": null,
"e": 7873,
"s": 7769,
"text": "To experiment with this example, you need to run this on an actual device on which camera is supported."
},
{
"code": null,
"e": 7933,
"s": 7873,
"text": "Following is the content of the modified MainActivity.java."
},
{
"code": null,
"e": 10587,
"s": 7933,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\n\nimport android.view.KeyEvent;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\n\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.AdapterView.OnItemClickListener;\nimport android.widget.ListView;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class MainActivity extends ActionBarActivity {\n public final static String EXTRA_MESSAGE = \"MESSAGE\";\n private ListView obj;\n DBHelper mydb;\n \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n mydb = new DBHelper(this);\n ArrayList array_list = mydb.getAllCotacts();\n ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);\n \n obj = (ListView)findViewById(R.id.listView1);\n obj.setAdapter(arrayAdapter);\n obj.setOnItemClickListener(new OnItemClickListener(){\n @Override\n public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {\n // TODO Auto-generated method stub\n int id_To_Search = arg2 + 1;\n \n Bundle dataBundle = new Bundle();\n dataBundle.putInt(\"id\", id_To_Search);\n \n Intent intent = new Intent(getApplicationContext(),DisplayContact.class);\n \n intent.putExtras(dataBundle);\n startActivity(intent);\n }\n });\n }\n \n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_main, menu);\n return true;\n }\n \n @Override\n public boolean onOptionsItemSelected(MenuItem item){\n super.onOptionsItemSelected(item);\n \n switch(item.getItemId()) {\n case R.id.item1:Bundle dataBundle = new Bundle();\n dataBundle.putInt(\"id\", 0);\n \n Intent intent = new Intent(getApplicationContext(),DisplayContact.class);\n intent.putExtras(dataBundle);\n \n startActivity(intent);\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n }\n \n public boolean onKeyDown(int keycode, KeyEvent event) {\n if (keycode == KeyEvent.KEYCODE_BACK) {\n moveTaskToBack(true);\n }\n return super.onKeyDown(keycode, event);\n }\n}"
},
{
"code": null,
"e": 10669,
"s": 10587,
"text": "Following is the modified content of display contact activity DisplayContact.java"
},
{
"code": null,
"e": 17231,
"s": 10669,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.os.Bundle;\nimport android.app.Activity;\nimport android.app.AlertDialog;\n\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.database.Cursor;\n\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class DisplayContact extends Activity {\n int from_Where_I_Am_Coming = 0;\n private DBHelper mydb ;\n \n TextView name ;\n TextView phone;\n TextView email;\n TextView street;\n TextView place;\n int id_To_Update = 0;\n \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_display_contact);\n name = (TextView) findViewById(R.id.editTextName);\n phone = (TextView) findViewById(R.id.editTextPhone);\n email = (TextView) findViewById(R.id.editTextStreet);\n street = (TextView) findViewById(R.id.editTextEmail);\n place = (TextView) findViewById(R.id.editTextCity);\n\n mydb = new DBHelper(this);\n\n Bundle extras = getIntent().getExtras(); \n if(extras !=null) {\n int Value = extras.getInt(\"id\");\n \n if(Value>0){\n //means this is the view part not the add contact part.\n Cursor rs = mydb.getData(Value);\n id_To_Update = Value;\n rs.moveToFirst();\n \n String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));\n String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));\n String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));\n String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));\n String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));\n \n if (!rs.isClosed()) {\n rs.close();\n }\n Button b = (Button)findViewById(R.id.button1);\n b.setVisibility(View.INVISIBLE);\n\n name.setText((CharSequence)nam);\n name.setFocusable(false);\n name.setClickable(false);\n\n phone.setText((CharSequence)phon);\n phone.setFocusable(false); \n phone.setClickable(false);\n\n email.setText((CharSequence)emai);\n email.setFocusable(false);\n email.setClickable(false);\n\n street.setText((CharSequence)stree);\n street.setFocusable(false); \n street.setClickable(false);\n\n place.setText((CharSequence)plac);\n place.setFocusable(false);\n place.setClickable(false);\n }\n }\n }\n \n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n Bundle extras = getIntent().getExtras(); \n \n if(extras !=null) {\n int Value = extras.getInt(\"id\");\n if(Value>0){\n getMenuInflater().inflate(R.menu.display_contact, menu);\n } else{\n getMenuInflater().inflate(R.menu.menu_main menu);\n }\n }\n return true;\n }\n\n public boolean onOptionsItemSelected(MenuItem item) { \n super.onOptionsItemSelected(item); \n switch(item.getItemId()) { \n case R.id.Edit_Contact: \n Button b = (Button)findViewById(R.id.button1);\n b.setVisibility(View.VISIBLE);\n name.setEnabled(true);\n name.setFocusableInTouchMode(true);\n name.setClickable(true);\n\n phone.setEnabled(true);\n phone.setFocusableInTouchMode(true);\n phone.setClickable(true);\n\n email.setEnabled(true);\n email.setFocusableInTouchMode(true);\n email.setClickable(true);\n\n street.setEnabled(true);\n street.setFocusableInTouchMode(true);\n street.setClickable(true);\n\n place.setEnabled(true);\n place.setFocusableInTouchMode(true);\n place.setClickable(true);\n\n return true; \n case R.id.Delete_Contact:\n\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setMessage(R.string.deleteContact)\n .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n mydb.deleteContact(id_To_Update);\n Toast.makeText(getApplicationContext(), \"Deleted Successfully\", \n Toast.LENGTH_SHORT).show(); \n Intent intent = new Intent(getApplicationContext(),MainActivity.class);\n startActivity(intent);\n }\n })\n .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n // User cancelled the dialog\n }\n });\n\t\t\t\n AlertDialog d = builder.create();\n d.setTitle(\"Are you sure\");\n d.show();\n\n return true;\n default: \n return super.onOptionsItemSelected(item); \n \n } \n } \n\n public void run(View view) {\t\n Bundle extras = getIntent().getExtras();\n if(extras !=null) {\n int Value = extras.getInt(\"id\");\n if(Value>0){\n if(mydb.updateContact(id_To_Update,name.getText().toString(),\n phone.getText().toString(), email.getText().toString(), \n\t\t\t\t street.getText().toString(), place.getText().toString())){\n Toast.makeText(getApplicationContext(), \"Updated\", Toast.LENGTH_SHORT).show();\t\n Intent intent = new Intent(getApplicationContext(),MainActivity.class);\n startActivity(intent);\n } else{\n Toast.makeText(getApplicationContext(), \"not Updated\", Toast.LENGTH_SHORT).show();\t\n }\n } else{\n if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), \n\t\t\t\t email.getText().toString(), street.getText().toString(), \n\t\t\t\t place.getText().toString())){\n Toast.makeText(getApplicationContext(), \"done\",\n\t\t\t\t\t\t Toast.LENGTH_SHORT).show();\t\n } else{\n Toast.makeText(getApplicationContext(), \"not done\", \n\t\t\t\t\t Toast.LENGTH_SHORT).show();\t\n }\n Intent intent = new Intent(getApplicationContext(),MainActivity.class);\n startActivity(intent);\n }\n }\n }\n}"
},
{
"code": null,
"e": 17288,
"s": 17231,
"text": "Following is the content of Database class DBHelper.java"
},
{
"code": null,
"e": 20932,
"s": 17288,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Hashtable;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.DatabaseUtils;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport android.database.sqlite.SQLiteDatabase;\n\npublic class DBHelper extends SQLiteOpenHelper {\n\n public static final String DATABASE_NAME = \"MyDBName.db\";\n public static final String CONTACTS_TABLE_NAME = \"contacts\";\n public static final String CONTACTS_COLUMN_ID = \"id\";\n public static final String CONTACTS_COLUMN_NAME = \"name\";\n public static final String CONTACTS_COLUMN_EMAIL = \"email\";\n public static final String CONTACTS_COLUMN_STREET = \"street\";\n public static final String CONTACTS_COLUMN_CITY = \"place\";\n public static final String CONTACTS_COLUMN_PHONE = \"phone\";\n private HashMap hp;\n\n public DBHelper(Context context) {\n super(context, DATABASE_NAME , null, 1);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n // TODO Auto-generated method stub\n db.execSQL(\n \"create table contacts \" +\n \"(id integer primary key, name text,phone text,email text, street text,place text)\"\n );\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n // TODO Auto-generated method stub\n db.execSQL(\"DROP TABLE IF EXISTS contacts\");\n onCreate(db);\n }\n\n public boolean insertContact (String name, String phone, String email, String street,String place) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", name);\n contentValues.put(\"phone\", phone);\n contentValues.put(\"email\", email);\t\n contentValues.put(\"street\", street);\n contentValues.put(\"place\", place);\n db.insert(\"contacts\", null, contentValues);\n return true;\n }\n \n public Cursor getData(int id) {\n SQLiteDatabase db = this.getReadableDatabase();\n Cursor res = db.rawQuery( \"select * from contacts where id=\"+id+\"\", null );\n return res;\n }\n \n public int numberOfRows(){\n SQLiteDatabase db = this.getReadableDatabase();\n int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);\n return numRows;\n }\n \n public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", name);\n contentValues.put(\"phone\", phone);\n contentValues.put(\"email\", email);\n contentValues.put(\"street\", street);\n contentValues.put(\"place\", place);\n db.update(\"contacts\", contentValues, \"id = ? \", new String[] { Integer.toString(id) } );\n return true;\n }\n\n public Integer deleteContact (Integer id) {\n SQLiteDatabase db = this.getWritableDatabase();\n return db.delete(\"contacts\", \n \"id = ? \", \n new String[] { Integer.toString(id) });\n }\n \n public ArrayList<String> getAllCotacts() {\n ArrayList<String> array_list = new ArrayList<String>();\n \n //hp = new HashMap();\n SQLiteDatabase db = this.getReadableDatabase();\n Cursor res = db.rawQuery( \"select * from contacts\", null );\n res.moveToFirst();\n \n while(res.isAfterLast() == false){\n array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));\n res.moveToNext();\n }\n return array_list;\n }\n}"
},
{
"code": null,
"e": 20993,
"s": 20932,
"text": "Following is the content of the res/layout/activity_main.xml"
},
{
"code": null,
"e": 23080,
"s": 20993,
"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\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\"\n android:text=\"Data Base\" />\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials Point\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"35dp\"\n android:textColor=\"#ff16ff01\" />\n\n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:layout_below=\"@+id/textView2\"\n android:layout_centerHorizontal=\"true\"\n android:src=\"@drawable/logo\"/>\n\n <ScrollView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/scrollView\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\">\n \n <ListView\n android:id=\"@+id/listView1\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\" >\n </ListView>\n\t\t\n </ScrollView>\n\n</RelativeLayout>"
},
{
"code": null,
"e": 23152,
"s": 23080,
"text": "Following is the content of the res/layout/activity_display_contact.xml"
},
{
"code": null,
"e": 27888,
"s": 23152,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/scrollView1\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n tools:context=\".DisplayContact\" >\n\n <RelativeLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"370dp\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\">\n\n <EditText\n android:id=\"@+id/editTextName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentLeft=\"true\"\n android:layout_marginTop=\"5dp\"\n android:layout_marginLeft=\"82dp\"\n android:ems=\"10\"\n android:inputType=\"text\" >\n </EditText>\n\n <EditText\n android:id=\"@+id/editTextEmail\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignLeft=\"@+id/editTextStreet\"\n android:layout_below=\"@+id/editTextStreet\"\n android:layout_marginTop=\"22dp\"\n android:ems=\"10\"\n android:inputType=\"textEmailAddress\" />\n\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignBottom=\"@+id/editTextName\"\n android:layout_alignParentLeft=\"true\"\n android:text=\"@string/name\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <Button\n android:id=\"@+id/button1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignLeft=\"@+id/editTextCity\"\n android:layout_alignParentBottom=\"true\"\n android:layout_marginBottom=\"28dp\"\n android:onClick=\"run\"\n android:text=\"@string/save\" />\n\n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignBottom=\"@+id/editTextEmail\"\n android:layout_alignLeft=\"@+id/textView1\"\n android:text=\"@string/email\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <TextView\n android:id=\"@+id/textView5\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignBottom=\"@+id/editTextPhone\"\n android:layout_alignLeft=\"@+id/textView1\"\n android:text=\"@string/phone\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <TextView\n android:id=\"@+id/textView4\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@+id/editTextEmail\"\n android:layout_alignLeft=\"@+id/textView5\"\n android:text=\"@string/street\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <EditText\n android:id=\"@+id/editTextCity\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignRight=\"@+id/editTextName\"\n android:layout_below=\"@+id/editTextEmail\"\n android:layout_marginTop=\"30dp\"\n android:ems=\"10\"\n android:inputType=\"text\" />\n\n <TextView\n android:id=\"@+id/textView3\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignBaseline=\"@+id/editTextCity\"\n android:layout_alignBottom=\"@+id/editTextCity\"\n android:layout_alignParentLeft=\"true\"\n android:layout_toLeftOf=\"@+id/editTextEmail\"\n android:text=\"@string/country\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n <EditText\n android:id=\"@+id/editTextStreet\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignLeft=\"@+id/editTextName\"\n android:layout_below=\"@+id/editTextPhone\"\n android:ems=\"10\"\n android:inputType=\"text\" >\n\n <requestFocus />\n </EditText>\n\n <EditText\n android:id=\"@+id/editTextPhone\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignLeft=\"@+id/editTextStreet\"\n android:layout_below=\"@+id/editTextName\"\n android:ems=\"10\"\n android:inputType=\"phone|text\" />\n\n </RelativeLayout>\n</ScrollView>"
},
{
"code": null,
"e": 27941,
"s": 27888,
"text": "Following is the content of the res/value/string.xml"
},
{
"code": null,
"e": 28765,
"s": 27941,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">Address Book</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"Add_New\">Add New</string>\n <string name=\"edit\">Edit Contact</string>\n <string name=\"delete\">Delete Contact</string>\n <string name=\"title_activity_display_contact\">DisplayContact</string>\n <string name=\"name\">Name</string>\n <string name=\"phone\">Phone</string>\n <string name=\"email\">Email</string>\n <string name=\"street\">Street</string>\n <string name=\"country\">City/State/Zip</string>\n <string name=\"save\">Save Contact</string>\n <string name=\"deleteContact\">Are you sure, you want to delete it.</string>\n <string name=\"yes\">Yes</string>\n <string name=\"no\">No</string>\n</resources>"
},
{
"code": null,
"e": 28820,
"s": 28765,
"text": "Following is the content of the res/menu/main_menu.xml"
},
{
"code": null,
"e": 29062,
"s": 28820,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n \n <item android:id=\"@+id/item1\" \n android:icon=\"@drawable/add\"\n android:title=\"@string/Add_New\" >\n </item>\n \n</menu>"
},
{
"code": null,
"e": 29123,
"s": 29062,
"text": "Following is the content of the res/menu/display_contact.xml"
},
{
"code": null,
"e": 29484,
"s": 29123,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n <item\n android:id=\"@+id/Edit_Contact\"\n android:orderInCategory=\"100\"\n android:title=\"@string/edit\"/>\n \n <item\n android:id=\"@+id/Delete_Contact\"\n android:orderInCategory=\"100\"\n android:title=\"@string/delete\"/>\n\n</menu>"
},
{
"code": null,
"e": 29540,
"s": 29484,
"text": "This is the defualt AndroidManifest.xml of this project"
},
{
"code": null,
"e": 30298,
"s": 29540,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n <activity android:name=\".DisplayContact\"/>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 30679,
"s": 30298,
"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 Run icon from the tool bar. Before starting your application,Android studio will display following window to select an option where you want to run your Android application."
},
{
"code": null,
"e": 30790,
"s": 30679,
"text": "Select your mobile device as an option and then check your mobile device which will display following screen β"
},
{
"code": null,
"e": 30909,
"s": 30790,
"text": "Now open your optional menu, it will show as below image: Optional menu appears different places on different versions"
},
{
"code": null,
"e": 31013,
"s": 30909,
"text": "Click on the add button of the menu screen to add a new contact. It will display the following screen β"
},
{
"code": null,
"e": 31155,
"s": 31013,
"text": "It will display the following fields. Please enter the required information and click on save contact. It will bring you back to main screen."
},
{
"code": null,
"e": 31448,
"s": 31155,
"text": "Now our contact sai has been added.In order to see that where is your database is created. Open your android studio, connect your mobile. Go tools/android/android device monitor. Now browse the file explorer tab. Now browse this folder /data/data/<your.package.name>/databases<database-name>."
},
{
"code": null,
"e": 31483,
"s": 31448,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 31495,
"s": 31483,
"text": " Aditya Dua"
},
{
"code": null,
"e": 31530,
"s": 31495,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 31544,
"s": 31530,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 31576,
"s": 31544,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 31593,
"s": 31576,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 31628,
"s": 31593,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 31645,
"s": 31628,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 31680,
"s": 31645,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 31697,
"s": 31680,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 31730,
"s": 31697,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 31747,
"s": 31730,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 31754,
"s": 31747,
"text": " Print"
},
{
"code": null,
"e": 31765,
"s": 31754,
"text": " Add Notes"
}
] |
Create a sorted linked list from the given Binary Tree - GeeksforGeeks
|
21 Jun, 2021
Given a binary tree, the task is to convert it into a sorted linked list.Examples:
Input:
1
/ \
2 3
Output: 1 2 3
Input:
2
/ \
4 8
/ \ / \
7 3 5 1
Output: 1 2 3 4 5 7 8
Input:
3
/
4
/
1
/
9
Output: 1 3 4 9
Approach: Recursively iterate the given binary tree and add each node to its correct position in the resultant linked list (initially empty) using insertion sort.Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // A linked list nodeclass Node {public: int data; Node* next; Node(int data) { this->data = data; this->next = NULL; }}; // A binary tree nodeclass treeNode {public: int data; treeNode* left; treeNode* right; treeNode(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Function to print the linked listvoid print(Node* head){ if (head == NULL) { return; } Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; }} // Function to create Linked list from given binary treeNode* sortedList(Node* head, treeNode* root){ // return head if root is null if (root == NULL) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root->left); Node* newNode = new Node(root->data); Node* temp = head; Node* prev = NULL; // If linked list is empty add the // node to the head if (temp == NULL) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != NULL) { if (temp->data > root->data) { break; } else { prev = temp; temp = temp->next; } } // Given node is to be attached // at the end of the list if (temp == NULL) { prev->next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == NULL) { newNode->next = temp; head = newNode; } else { // Insertion in between the list newNode->next = temp; prev->next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root->right); return head;} // Driver codeint main(){ /* Tree: 10 / \ 15 2 / \ 1 5*/ treeNode* root = new treeNode(10); root->left = new treeNode(15); root->right = new treeNode(2); root->left->left = new treeNode(1); root->left->right = new treeNode(5); Node* head = sortedList(NULL, root); print(head); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // A linked list nodestatic class Node{ int data; Node next; Node(int data) { this.data = data; this.next = null; }}; // A binary tree nodestatic class treeNode{ int data; treeNode left; treeNode right; treeNode(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print the linked liststatic void print(Node head){ if (head == null) { return; } Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; }} // Function to create Linked list from given binary treestatic Node sortedList(Node head, treeNode root){ // return head if root is null if (root == null) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root.left); Node newNode = new Node(root.data); Node temp = head; Node prev = null; // If linked list is empty add the // node to the head if (temp == null) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != null) { if (temp.data > root.data) { break; } else { prev = temp; temp = temp.next; } } // Given node is to be attached // at the end of the list if (temp == null) { prev.next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == null) { newNode.next = temp; head = newNode; } else { // Insertion in between the list newNode.next = temp; prev.next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root.right); return head;} // Driver codepublic static void main(String[] args){ /* Tree: 10 / \ 15 2 / \ 1 5*/ treeNode root = new treeNode(10); root.left = new treeNode(15); root.right = new treeNode(2); root.left.left = new treeNode(1); root.left.right = new treeNode(5); Node head = sortedList(null, root); print(head);}} // This code is contributed by 29AjayKumar
// C# implementation of the approachusing System; class GFG{ // A linked list nodeclass Node{ public int data; public Node next; public Node(int data) { this.data = data; this.next = null; }}; // A binary tree nodeclass treeNode{ public int data; public treeNode left; public treeNode right; public treeNode(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print the linked liststatic void print(Node head){ if (head == null) { return; } Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; }} // Function to create Linked list// from given binary treestatic Node sortedList(Node head, treeNode root){ // return head if root is null if (root == null) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root.left); Node newNode = new Node(root.data); Node temp = head; Node prev = null; // If linked list is empty add the // node to the head if (temp == null) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != null) { if (temp.data > root.data) { break; } else { prev = temp; temp = temp.next; } } // Given node is to be attached // at the end of the list if (temp == null) { prev.next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == null) { newNode.next = temp; head = newNode; } else { // Insertion in between the list newNode.next = temp; prev.next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root.right); return head;} // Driver codepublic static void Main(String[] args){ /* Tree: 10 / \ 15 2 / \ 1 5 */ treeNode root = new treeNode(10); root.left = new treeNode(15); root.right = new treeNode(2); root.left.left = new treeNode(1); root.left.right = new treeNode(5); Node head = sortedList(null, root); print(head);}} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approach # A linked list nodeclass Node: def __init__(self, data = 0): self.data = data self.next = None # A binary tree nodeclass treeNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to print the linked listdef print_(head): if (head == None): return temp = head while (temp != None): print ( temp.data, end = " " ) temp = temp.next # Function to create Linked list from given binary treedef sortedList( head, root): # return head if root is None if (root == None) : return head # First make the sorted linked list # of the left sub-tree head = sortedList(head, root.left) newNode = Node(root.data) temp = head prev = None # If linked list is empty add the # node to the head if (temp == None) : head = newNode else: # Find the correct position of the node # in the given linked list while (temp != None): if (temp.data > root.data) : break else: prev = temp temp = temp.next # Given node is to be attached # at the end of the list if (temp == None): prev.next = newNode else: # Given node is to be attached # at the head of the list if (prev == None) : newNode.next = temp head = newNode else: # Insertion in between the list newNode.next = temp prev.next = newNode # Now add the nodes of the right sub-tree # to the sorted linked list head = sortedList(head, root.right) return head # Driver code # Tree:# 10# / \# 15 2# / \#1 5 root = treeNode(10)root.left = treeNode(15)root.right = treeNode(2)root.left.left = treeNode(1)root.left.right = treeNode(5) head = sortedList(None, root) print_(head) # This code is contributed by Arnab Kundu
<script> // JavaScript implementation of the approach // A linked list nodeclass Node { constructor(data) { this.data = data; this.next = null; }}; // A binary tree nodeclass treeNode { constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Function to print the linked listfunction print(head){ if (head == null) { return; } var temp = head; while (temp != null) { document.write( temp.data + " "); temp = temp.next; }} // Function to create Linked list from given binary treefunction sortedList(head, root){ // return head if root is null if (root == null) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root.left); var newNode = new Node(root.data); var temp = head; var prev = null; // If linked list is empty add the // node to the head if (temp == null) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != null) { if (temp.data > root.data) { break; } else { prev = temp; temp = temp.next; } } // Given node is to be attached // at the end of the list if (temp == null) { prev.next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == null) { newNode.next = temp; head = newNode; } else { // Insertion in between the list newNode.next = temp; prev.next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root.right); return head;} // Driver code /* Tree: 10 / \ 15 2 / \ 1 5*/var root = new treeNode(10);root.left = new treeNode(15);root.right = new treeNode(2);root.left.left = new treeNode(1);root.left.right = new treeNode(5);var head = sortedList(null, root);print(head); </script>
1 2 5 10 15
Time Complexity: O(n2)
29AjayKumar
princiraj1992
andrew1234
itsok
Linked List
Tree
Linked List
Tree
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
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Real-time application of Data Structures
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
|
[
{
"code": null,
"e": 26315,
"s": 26287,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 26400,
"s": 26315,
"text": "Given a binary tree, the task is to convert it into a sorted linked list.Examples: "
},
{
"code": null,
"e": 26625,
"s": 26400,
"text": "Input:\n 1 \n / \\ \n 2 3 \nOutput: 1 2 3\n\nInput:\n 2\n / \\\n 4 8\n / \\ / \\\n 7 3 5 1\nOutput: 1 2 3 4 5 7 8\n\nInput:\n 3 \n / \n 4 \n / \n 1\n /\n 9\nOutput: 1 3 4 9"
},
{
"code": null,
"e": 26842,
"s": 26627,
"text": "Approach: Recursively iterate the given binary tree and add each node to its correct position in the resultant linked list (initially empty) using insertion sort.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26846,
"s": 26842,
"text": "C++"
},
{
"code": null,
"e": 26851,
"s": 26846,
"text": "Java"
},
{
"code": null,
"e": 26854,
"s": 26851,
"text": "C#"
},
{
"code": null,
"e": 26862,
"s": 26854,
"text": "Python3"
},
{
"code": null,
"e": 26873,
"s": 26862,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // A linked list nodeclass Node {public: int data; Node* next; Node(int data) { this->data = data; this->next = NULL; }}; // A binary tree nodeclass treeNode {public: int data; treeNode* left; treeNode* right; treeNode(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Function to print the linked listvoid print(Node* head){ if (head == NULL) { return; } Node* temp = head; while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; }} // Function to create Linked list from given binary treeNode* sortedList(Node* head, treeNode* root){ // return head if root is null if (root == NULL) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root->left); Node* newNode = new Node(root->data); Node* temp = head; Node* prev = NULL; // If linked list is empty add the // node to the head if (temp == NULL) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != NULL) { if (temp->data > root->data) { break; } else { prev = temp; temp = temp->next; } } // Given node is to be attached // at the end of the list if (temp == NULL) { prev->next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == NULL) { newNode->next = temp; head = newNode; } else { // Insertion in between the list newNode->next = temp; prev->next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root->right); return head;} // Driver codeint main(){ /* Tree: 10 / \\ 15 2 / \\ 1 5*/ treeNode* root = new treeNode(10); root->left = new treeNode(15); root->right = new treeNode(2); root->left->left = new treeNode(1); root->left->right = new treeNode(5); Node* head = sortedList(NULL, root); print(head); return 0;}",
"e": 29328,
"s": 26873,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // A linked list nodestatic class Node{ int data; Node next; Node(int data) { this.data = data; this.next = null; }}; // A binary tree nodestatic class treeNode{ int data; treeNode left; treeNode right; treeNode(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print the linked liststatic void print(Node head){ if (head == null) { return; } Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; }} // Function to create Linked list from given binary treestatic Node sortedList(Node head, treeNode root){ // return head if root is null if (root == null) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root.left); Node newNode = new Node(root.data); Node temp = head; Node prev = null; // If linked list is empty add the // node to the head if (temp == null) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != null) { if (temp.data > root.data) { break; } else { prev = temp; temp = temp.next; } } // Given node is to be attached // at the end of the list if (temp == null) { prev.next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == null) { newNode.next = temp; head = newNode; } else { // Insertion in between the list newNode.next = temp; prev.next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root.right); return head;} // Driver codepublic static void main(String[] args){ /* Tree: 10 / \\ 15 2 / \\ 1 5*/ treeNode root = new treeNode(10); root.left = new treeNode(15); root.right = new treeNode(2); root.left.left = new treeNode(1); root.left.right = new treeNode(5); Node head = sortedList(null, root); print(head);}} // This code is contributed by 29AjayKumar",
"e": 31886,
"s": 29328,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // A linked list nodeclass Node{ public int data; public Node next; public Node(int data) { this.data = data; this.next = null; }}; // A binary tree nodeclass treeNode{ public int data; public treeNode left; public treeNode right; public treeNode(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to print the linked liststatic void print(Node head){ if (head == null) { return; } Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; }} // Function to create Linked list// from given binary treestatic Node sortedList(Node head, treeNode root){ // return head if root is null if (root == null) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root.left); Node newNode = new Node(root.data); Node temp = head; Node prev = null; // If linked list is empty add the // node to the head if (temp == null) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != null) { if (temp.data > root.data) { break; } else { prev = temp; temp = temp.next; } } // Given node is to be attached // at the end of the list if (temp == null) { prev.next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == null) { newNode.next = temp; head = newNode; } else { // Insertion in between the list newNode.next = temp; prev.next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root.right); return head;} // Driver codepublic static void Main(String[] args){ /* Tree: 10 / \\ 15 2 / \\ 1 5 */ treeNode root = new treeNode(10); root.left = new treeNode(15); root.right = new treeNode(2); root.left.left = new treeNode(1); root.left.right = new treeNode(5); Node head = sortedList(null, root); print(head);}} // This code is contributed by PrinciRaj1992",
"e": 34476,
"s": 31886,
"text": null
},
{
"code": "# Python3 implementation of the approach # A linked list nodeclass Node: def __init__(self, data = 0): self.data = data self.next = None # A binary tree nodeclass treeNode: def __init__(self, data): self.data = data self.left = None self.right = None # Function to print the linked listdef print_(head): if (head == None): return temp = head while (temp != None): print ( temp.data, end = \" \" ) temp = temp.next # Function to create Linked list from given binary treedef sortedList( head, root): # return head if root is None if (root == None) : return head # First make the sorted linked list # of the left sub-tree head = sortedList(head, root.left) newNode = Node(root.data) temp = head prev = None # If linked list is empty add the # node to the head if (temp == None) : head = newNode else: # Find the correct position of the node # in the given linked list while (temp != None): if (temp.data > root.data) : break else: prev = temp temp = temp.next # Given node is to be attached # at the end of the list if (temp == None): prev.next = newNode else: # Given node is to be attached # at the head of the list if (prev == None) : newNode.next = temp head = newNode else: # Insertion in between the list newNode.next = temp prev.next = newNode # Now add the nodes of the right sub-tree # to the sorted linked list head = sortedList(head, root.right) return head # Driver code # Tree:# 10# / \\# 15 2# / \\#1 5 root = treeNode(10)root.left = treeNode(15)root.right = treeNode(2)root.left.left = treeNode(1)root.left.right = treeNode(5) head = sortedList(None, root) print_(head) # This code is contributed by Arnab Kundu",
"e": 36571,
"s": 34476,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // A linked list nodeclass Node { constructor(data) { this.data = data; this.next = null; }}; // A binary tree nodeclass treeNode { constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Function to print the linked listfunction print(head){ if (head == null) { return; } var temp = head; while (temp != null) { document.write( temp.data + \" \"); temp = temp.next; }} // Function to create Linked list from given binary treefunction sortedList(head, root){ // return head if root is null if (root == null) { return head; } // First make the sorted linked list // of the left sub-tree head = sortedList(head, root.left); var newNode = new Node(root.data); var temp = head; var prev = null; // If linked list is empty add the // node to the head if (temp == null) { head = newNode; } else { // Find the correct position of the node // in the given linked list while (temp != null) { if (temp.data > root.data) { break; } else { prev = temp; temp = temp.next; } } // Given node is to be attached // at the end of the list if (temp == null) { prev.next = newNode; } else { // Given node is to be attached // at the head of the list if (prev == null) { newNode.next = temp; head = newNode; } else { // Insertion in between the list newNode.next = temp; prev.next = newNode; } } } // Now add the nodes of the right sub-tree // to the sorted linked list head = sortedList(head, root.right); return head;} // Driver code /* Tree: 10 / \\ 15 2 / \\ 1 5*/var root = new treeNode(10);root.left = new treeNode(15);root.right = new treeNode(2);root.left.left = new treeNode(1);root.left.right = new treeNode(5);var head = sortedList(null, root);print(head); </script>",
"e": 38824,
"s": 36571,
"text": null
},
{
"code": null,
"e": 38836,
"s": 38824,
"text": "1 2 5 10 15"
},
{
"code": null,
"e": 38862,
"s": 38838,
"text": "Time Complexity: O(n2) "
},
{
"code": null,
"e": 38874,
"s": 38862,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38888,
"s": 38874,
"text": "princiraj1992"
},
{
"code": null,
"e": 38899,
"s": 38888,
"text": "andrew1234"
},
{
"code": null,
"e": 38905,
"s": 38899,
"text": "itsok"
},
{
"code": null,
"e": 38917,
"s": 38905,
"text": "Linked List"
},
{
"code": null,
"e": 38922,
"s": 38917,
"text": "Tree"
},
{
"code": null,
"e": 38934,
"s": 38922,
"text": "Linked List"
},
{
"code": null,
"e": 38939,
"s": 38934,
"text": "Tree"
},
{
"code": null,
"e": 39037,
"s": 38939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39078,
"s": 39037,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 39128,
"s": 39078,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 39168,
"s": 39128,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 39239,
"s": 39168,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 39280,
"s": 39239,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 39330,
"s": 39280,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 39359,
"s": 39330,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 39394,
"s": 39359,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 39428,
"s": 39394,
"text": "Level Order Binary Tree Traversal"
}
] |
Using Line Plots from Matplotlib to Create Simple Log Plots of Well Log Data | by Andy McDonald | Towards Data Science
|
Well log plots are a common visualization tool within geoscience and petrophysics. They allow easy visualization of data (for example, Gamma Ray, Neutron Porosity, Bulk Density, etc) that have been acquired along the length (depth) of a wellbore. On these plots, we display our logging measurements on the x-axis and measured depth or true vertical depth on the y-axis.
In this short article, we will see how to create a simple log plot visualisation from one of the Volve Wells that was released as part of a larger dataset by Equinor in 2018.
I have previously covered different aspects of making these plots in the following articles:
Displaying Lithology Data on a Well Log Plot Using Python
Displaying Logging While Drilling (LWD) Image Logs in Python
Enhancing Visualization of Well Logs With Plot Fills
For this tutorial, the notebook can be found here and the following video also accompanies it.
The first stage of any python project or notebook is to import the required libraries. In this case, we are going to be using lasio to load our las file, pandas for storing our well log data, and matplotlib for visualising our data.
import pandas as pdimport lasioimport matplotlib.pyplot as plt
To read the data we will use the lasio library which we explored in the previous notebook and video.
las = lasio.read("Data/15-9-19_SR_COMP.LAS")
Once the file has been loaded, we can check the contents of the file by using df.head() . This will return back the first five rows of our dataframe.
df = las.df()df.head()
We can see from the returned results that we have several columns of data, each column represents measurements that have been taken whilst the logging tools have been moved along the well.
The columns represent the following:
AC for acoustic compressional slowness
CALI for borehole caliper
DEN for bulk density
GR for gamma ray
NEU for neutron porosity
RDEP for deep resisitivity
RMED for medium resistivity
To make it easier to work with our dataframe, we can convert the dataframe index, which is set to depth, to a column within the dataframe. We can achieve this by resetting the index like so.
df.reset_index(inplace=True)
Note that inplace=True allows us to make the changes to the original dataframe object.
We can call upon df.head() again to ensure our new column has been created.
df.head()
We also need to do a slight rename on the DEPT column and change it to DEPTH
df.rename(columns={'DEPT':'DEPTH'}, inplace=True)df.head()
Now that our data is in the right format, and the columns are correctly labeled, we can move onto generating our log plot.
We can easily create a simple plot by calling upon df.plot() and passing in two of our columns
df.plot('GR', 'DEPTH')
When we run this cell, we get a very simple plot that is hard to read and is also upside down.
If we want to view all of the columns within the dataframe, we can generate a subplot grid.
This is done by taking the same line as before (df.plot()), and instead of passing in curve names, we pass in subplots=True. We can also specify a figure size (figsize(), which controls how large the plot will appear.
df.plot(subplots=True, figsize=(15, 15))
And we now see a grid of plots, one for each of the columns within the dataframe. This is a useful way to check where we have data and where we may have gaps.
However, we do not have much control over this plot. In the following sections we will see how we can start building up a well log plot with multiple measurements.
There are many ways to generate subplots in using matplotlib. For this particular tutorial, we will work with subplot2grid.
fig = plt.subplots(figsize=(10,10))#Set up the plot axisax1 = plt.subplot2grid((1,1), (0,0), rowspan=1, colspan = 1) ax1.plot("GR", "DEPTH", data = df, color = "green") # Call the data from the df dataframeax1.set_xlabel("Gamma") # Assign a track titleax1.set_xlim(0, 200) # Change the limits for the curve being plottedax1.set_ylim(4700, 3500) # Set the depth rangeax1.grid() # Display the grid
In the above code, we first have to define a figure (fig) and assign it to plt.subplots. Within the subplots arguments we can pass in the figure size, which we will set to 10 by 10.
Next, we need to create an axis on our figure object. We can do this by assigning ax1 is equal to plt.subplot2grid()..We first pass in the shape of the subplot grid, which for this example we will set 1 by 1.
Next we specify the location of our subplot using index positions. As we only have 1 subplot, we will set the location to zero, zero (0,0). Rowspan and colspan are both set to 1, which means they will only be 1 column wide by 1 row high.
Then, we need to tell matplotlib what we want to plot. In this case we are going use ax1.plot, and pass in our Gamma Ray and Depth columns.
Using the ax notation, we can further customise the plot by setting the x and y limits, and displaying the grid.
When we run this code we generate the following plot.
Great! There we have a much better looking plot, and we can now start adding new tracks / subplots to our overall log plot.
To add a new track / subplot to our figure, we can repeat what we did above and add a new axis, ax2.
We then increment the second digit in the layout argument of plt.subplot2grid() so it is now 1 row, by 2 columns.
For ax2, we need to place it in the second subplot and this is done by changing the location argument from (0,0) to (0,1).
We then end up with:
ax1 = plt.subplot2grid((1,2), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,2), (0,1), rowspan=1, colspan = 1)
Also, as resistivity is normally scaled logarithmically, we need to add in the line: ax2.semilogx().
fig = plt.subplots(figsize=(10,10))#Set up the plot axesax1 = plt.subplot2grid((1,2), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,2), (0,1), rowspan=1, colspan = 1)ax1.plot("GR", "DEPTH", data = df, color = "green") # Call the data from the well dataframeax1.set_xlabel("Gamma") # Assign a track titleax1.set_xlim(0, 200) # Change the limits for the curve being plottedax1.set_ylim(4700, 3500) # Set the depth rangeax1.grid() # Display the gridax2.plot("RDEP", "DEPTH", data = df, color = "red")ax2.set_xlabel("Deep Res.")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax2.set_ylim(4700, 3500)ax2.grid()
To add a third track / subplot, we can repeat the above by adding in the density as a new subplot.
fig = plt.subplots(figsize=(10,10))#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)ax1.plot("GR", "DEPTH", data = df, color = "green") # Call the data from the well dataframeax1.set_xlabel("Gamma") # Assign a track titleax1.set_xlim(0, 200) # Change the limits for the curve being plottedax1.set_ylim(4700, 3500) # Set the depth rangeax1.grid() # Display the gridax2.plot("RDEP", "DEPTH", data = df, color = "red")ax2.set_xlabel("Deep Res.")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax2.set_ylim(4700, 3500)ax2.grid()ax3.plot("DEN", "DEPTH", data = df, color = "red")ax3.set_xlabel("Density")ax3.set_xlim(1.95, 2.95)ax3.set_ylim(4700, 3500)ax3.grid()
We can see from the previous code snippet that we have a number of elements that are repeated in each of the axis calls such as ax.set_ylim(4700, 3500). We can separate these out so that we only need to call these functions once. This saves on the amount of lines we need to write and makes the code more readable.
To achieve this, we add in a new for loop which will loop over the axes within fig.axes.
for i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.grid() ax.set_xlabel(curve_names[i])
Our final code, after separating out the common elements looks like this:
fig, axes = plt.subplots(figsize=(10,10))curve_names = ['Gamma', 'Deep Res', 'Density']#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)ax1.plot("GR", "DEPTH", data = df, color = "green")ax1.set_xlim(0, 200) ax2.plot("RDEP", "DEPTH", data = df, color = "red")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax3.plot("DEN", "DEPTH", data = df, color = "red")ax3.set_xlim(1.95, 2.95)for i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.grid() ax.set_xlabel(curve_names[i])
To tidy the plot up a little more, we can remove the depth labels in between each subplot / track and reduce the space between them. This is achieved by the looping over only ax2 and ax3, and by adjusting the width of the padding between plots.
#Hide tick labels on the y-axis for ax in [ax2, ax3]: plt.setp(ax.get_yticklabels(), visible = False)#Reduce the space between each subplotfig.subplots_adjust(wspace = 0.05)
We then end up with the following:
fig, axes = plt.subplots(figsize=(10,10))curve_names = ['Gamma', 'Deep Res', 'Density']#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)#Set up the individual log tracks / subplotsax1.plot("GR", "DEPTH", data = df, color = "green")ax1.set_xlim(0, 200) ax2.plot("RDEP", "DEPTH", data = df, color = "red")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax3.plot("DEN", "DEPTH", data = df, color = "red")ax3.set_xlim(1.95, 2.95)#Set up the common elements between the subplotsfor i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.grid() ax.set_xlabel(curve_names[i])#Hide tick labels on the y-axis for ax in [ax2, ax3]: plt.setp(ax.get_yticklabels(), visible = False)#Reduce the space between each subplotfig.subplots_adjust(wspace = 0.05)
It is standard to plot bulk density and neutron porosity on the same subplot / track. The interaction of these two curves allows us to identify lithology variations and hydrocarbon presence.
As the two measurements are on different units and scales (1.95 to 2.95 g/cc for Bulk Density and -15 to 60 for Neutron Porosity) we need to add another subplot on top using the twiny function. This allows us to use the same y-axis between the plots, but the x-axis can vary.
All labels have been moved to the top of the plot which is done by using ax.xaxis.set_ticks_position('top') and ax.xaxis.set_label_position('top').
We then need to modify the main for loop to check when we reach ax4 (which will be when i = 3, as Python indexes from 0) and then adjust the spine so that it sits above the Density label.
fig, axes = plt.subplots(figsize=(10,10))curve_names = ['Gamma', 'Deep Res', 'Density', 'Neutron']#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)ax4 = ax3.twiny()#Set up the individual log tracks / subplotsax1.plot("GR", "DEPTH", data = df, color = "green", lw = 0.5)ax1.set_xlim(0, 200) ax2.plot("RDEP", "DEPTH", data = df, color = "red", lw = 0.5)ax2.set_xlim(0.2, 2000)ax2.semilogx()ax3.plot("DEN", "DEPTH", data = df, color = "red", lw = 0.5)ax3.set_xlim(1.95, 2.95)ax4.plot("NEU", "DEPTH", data = df, color = "blue", lw = 0.5)ax4.set_xlim(45, -15)#Set up the common elements between the subplotsfor i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.xaxis.set_ticks_position("top") ax.xaxis.set_label_position("top") ax.set_xlabel(curve_names[i]) if i == 3: ax.spines["top"].set_position(("axes", 1.08)) else: ax.grid() #Hide tick labels on the y-axis for ax in [ax2, ax3]: plt.setp(ax.get_yticklabels(), visible = False)#Reduce the space between each subplotfig.subplots_adjust(wspace = 0.05)
In this short tutorial, we have covered the basics of how to display a well log plot using matplotlib, how to add multiple tracks/subplots, and plot two curves on top of each other. Matplotlib provides a great way to build simple log plots from scratch and is a great library to learn.
Thanks for reading!
If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub.
If you want to get in touch you can find me on LinkedIn or at my website.
Interested in learning more about python and well log data or petrophysics? Follow me on Medium.
|
[
{
"code": null,
"e": 541,
"s": 171,
"text": "Well log plots are a common visualization tool within geoscience and petrophysics. They allow easy visualization of data (for example, Gamma Ray, Neutron Porosity, Bulk Density, etc) that have been acquired along the length (depth) of a wellbore. On these plots, we display our logging measurements on the x-axis and measured depth or true vertical depth on the y-axis."
},
{
"code": null,
"e": 716,
"s": 541,
"text": "In this short article, we will see how to create a simple log plot visualisation from one of the Volve Wells that was released as part of a larger dataset by Equinor in 2018."
},
{
"code": null,
"e": 809,
"s": 716,
"text": "I have previously covered different aspects of making these plots in the following articles:"
},
{
"code": null,
"e": 867,
"s": 809,
"text": "Displaying Lithology Data on a Well Log Plot Using Python"
},
{
"code": null,
"e": 928,
"s": 867,
"text": "Displaying Logging While Drilling (LWD) Image Logs in Python"
},
{
"code": null,
"e": 981,
"s": 928,
"text": "Enhancing Visualization of Well Logs With Plot Fills"
},
{
"code": null,
"e": 1076,
"s": 981,
"text": "For this tutorial, the notebook can be found here and the following video also accompanies it."
},
{
"code": null,
"e": 1309,
"s": 1076,
"text": "The first stage of any python project or notebook is to import the required libraries. In this case, we are going to be using lasio to load our las file, pandas for storing our well log data, and matplotlib for visualising our data."
},
{
"code": null,
"e": 1372,
"s": 1309,
"text": "import pandas as pdimport lasioimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1473,
"s": 1372,
"text": "To read the data we will use the lasio library which we explored in the previous notebook and video."
},
{
"code": null,
"e": 1518,
"s": 1473,
"text": "las = lasio.read(\"Data/15-9-19_SR_COMP.LAS\")"
},
{
"code": null,
"e": 1668,
"s": 1518,
"text": "Once the file has been loaded, we can check the contents of the file by using df.head() . This will return back the first five rows of our dataframe."
},
{
"code": null,
"e": 1691,
"s": 1668,
"text": "df = las.df()df.head()"
},
{
"code": null,
"e": 1880,
"s": 1691,
"text": "We can see from the returned results that we have several columns of data, each column represents measurements that have been taken whilst the logging tools have been moved along the well."
},
{
"code": null,
"e": 1917,
"s": 1880,
"text": "The columns represent the following:"
},
{
"code": null,
"e": 1956,
"s": 1917,
"text": "AC for acoustic compressional slowness"
},
{
"code": null,
"e": 1982,
"s": 1956,
"text": "CALI for borehole caliper"
},
{
"code": null,
"e": 2003,
"s": 1982,
"text": "DEN for bulk density"
},
{
"code": null,
"e": 2020,
"s": 2003,
"text": "GR for gamma ray"
},
{
"code": null,
"e": 2045,
"s": 2020,
"text": "NEU for neutron porosity"
},
{
"code": null,
"e": 2072,
"s": 2045,
"text": "RDEP for deep resisitivity"
},
{
"code": null,
"e": 2100,
"s": 2072,
"text": "RMED for medium resistivity"
},
{
"code": null,
"e": 2291,
"s": 2100,
"text": "To make it easier to work with our dataframe, we can convert the dataframe index, which is set to depth, to a column within the dataframe. We can achieve this by resetting the index like so."
},
{
"code": null,
"e": 2320,
"s": 2291,
"text": "df.reset_index(inplace=True)"
},
{
"code": null,
"e": 2407,
"s": 2320,
"text": "Note that inplace=True allows us to make the changes to the original dataframe object."
},
{
"code": null,
"e": 2483,
"s": 2407,
"text": "We can call upon df.head() again to ensure our new column has been created."
},
{
"code": null,
"e": 2493,
"s": 2483,
"text": "df.head()"
},
{
"code": null,
"e": 2570,
"s": 2493,
"text": "We also need to do a slight rename on the DEPT column and change it to DEPTH"
},
{
"code": null,
"e": 2629,
"s": 2570,
"text": "df.rename(columns={'DEPT':'DEPTH'}, inplace=True)df.head()"
},
{
"code": null,
"e": 2752,
"s": 2629,
"text": "Now that our data is in the right format, and the columns are correctly labeled, we can move onto generating our log plot."
},
{
"code": null,
"e": 2847,
"s": 2752,
"text": "We can easily create a simple plot by calling upon df.plot() and passing in two of our columns"
},
{
"code": null,
"e": 2870,
"s": 2847,
"text": "df.plot('GR', 'DEPTH')"
},
{
"code": null,
"e": 2965,
"s": 2870,
"text": "When we run this cell, we get a very simple plot that is hard to read and is also upside down."
},
{
"code": null,
"e": 3057,
"s": 2965,
"text": "If we want to view all of the columns within the dataframe, we can generate a subplot grid."
},
{
"code": null,
"e": 3275,
"s": 3057,
"text": "This is done by taking the same line as before (df.plot()), and instead of passing in curve names, we pass in subplots=True. We can also specify a figure size (figsize(), which controls how large the plot will appear."
},
{
"code": null,
"e": 3316,
"s": 3275,
"text": "df.plot(subplots=True, figsize=(15, 15))"
},
{
"code": null,
"e": 3475,
"s": 3316,
"text": "And we now see a grid of plots, one for each of the columns within the dataframe. This is a useful way to check where we have data and where we may have gaps."
},
{
"code": null,
"e": 3639,
"s": 3475,
"text": "However, we do not have much control over this plot. In the following sections we will see how we can start building up a well log plot with multiple measurements."
},
{
"code": null,
"e": 3763,
"s": 3639,
"text": "There are many ways to generate subplots in using matplotlib. For this particular tutorial, we will work with subplot2grid."
},
{
"code": null,
"e": 4159,
"s": 3763,
"text": "fig = plt.subplots(figsize=(10,10))#Set up the plot axisax1 = plt.subplot2grid((1,1), (0,0), rowspan=1, colspan = 1) ax1.plot(\"GR\", \"DEPTH\", data = df, color = \"green\") # Call the data from the df dataframeax1.set_xlabel(\"Gamma\") # Assign a track titleax1.set_xlim(0, 200) # Change the limits for the curve being plottedax1.set_ylim(4700, 3500) # Set the depth rangeax1.grid() # Display the grid"
},
{
"code": null,
"e": 4341,
"s": 4159,
"text": "In the above code, we first have to define a figure (fig) and assign it to plt.subplots. Within the subplots arguments we can pass in the figure size, which we will set to 10 by 10."
},
{
"code": null,
"e": 4550,
"s": 4341,
"text": "Next, we need to create an axis on our figure object. We can do this by assigning ax1 is equal to plt.subplot2grid()..We first pass in the shape of the subplot grid, which for this example we will set 1 by 1."
},
{
"code": null,
"e": 4788,
"s": 4550,
"text": "Next we specify the location of our subplot using index positions. As we only have 1 subplot, we will set the location to zero, zero (0,0). Rowspan and colspan are both set to 1, which means they will only be 1 column wide by 1 row high."
},
{
"code": null,
"e": 4928,
"s": 4788,
"text": "Then, we need to tell matplotlib what we want to plot. In this case we are going use ax1.plot, and pass in our Gamma Ray and Depth columns."
},
{
"code": null,
"e": 5041,
"s": 4928,
"text": "Using the ax notation, we can further customise the plot by setting the x and y limits, and displaying the grid."
},
{
"code": null,
"e": 5095,
"s": 5041,
"text": "When we run this code we generate the following plot."
},
{
"code": null,
"e": 5219,
"s": 5095,
"text": "Great! There we have a much better looking plot, and we can now start adding new tracks / subplots to our overall log plot."
},
{
"code": null,
"e": 5320,
"s": 5219,
"text": "To add a new track / subplot to our figure, we can repeat what we did above and add a new axis, ax2."
},
{
"code": null,
"e": 5434,
"s": 5320,
"text": "We then increment the second digit in the layout argument of plt.subplot2grid() so it is now 1 row, by 2 columns."
},
{
"code": null,
"e": 5557,
"s": 5434,
"text": "For ax2, we need to place it in the second subplot and this is done by changing the location argument from (0,0) to (0,1)."
},
{
"code": null,
"e": 5578,
"s": 5557,
"text": "We then end up with:"
},
{
"code": null,
"e": 5700,
"s": 5578,
"text": "ax1 = plt.subplot2grid((1,2), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,2), (0,1), rowspan=1, colspan = 1)"
},
{
"code": null,
"e": 5801,
"s": 5700,
"text": "Also, as resistivity is normally scaled logarithmically, we need to add in the line: ax2.semilogx()."
},
{
"code": null,
"e": 6408,
"s": 5801,
"text": "fig = plt.subplots(figsize=(10,10))#Set up the plot axesax1 = plt.subplot2grid((1,2), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,2), (0,1), rowspan=1, colspan = 1)ax1.plot(\"GR\", \"DEPTH\", data = df, color = \"green\") # Call the data from the well dataframeax1.set_xlabel(\"Gamma\") # Assign a track titleax1.set_xlim(0, 200) # Change the limits for the curve being plottedax1.set_ylim(4700, 3500) # Set the depth rangeax1.grid() # Display the gridax2.plot(\"RDEP\", \"DEPTH\", data = df, color = \"red\")ax2.set_xlabel(\"Deep Res.\")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax2.set_ylim(4700, 3500)ax2.grid()"
},
{
"code": null,
"e": 6507,
"s": 6408,
"text": "To add a third track / subplot, we can repeat the above by adding in the density as a new subplot."
},
{
"code": null,
"e": 7307,
"s": 6507,
"text": "fig = plt.subplots(figsize=(10,10))#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)ax1.plot(\"GR\", \"DEPTH\", data = df, color = \"green\") # Call the data from the well dataframeax1.set_xlabel(\"Gamma\") # Assign a track titleax1.set_xlim(0, 200) # Change the limits for the curve being plottedax1.set_ylim(4700, 3500) # Set the depth rangeax1.grid() # Display the gridax2.plot(\"RDEP\", \"DEPTH\", data = df, color = \"red\")ax2.set_xlabel(\"Deep Res.\")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax2.set_ylim(4700, 3500)ax2.grid()ax3.plot(\"DEN\", \"DEPTH\", data = df, color = \"red\")ax3.set_xlabel(\"Density\")ax3.set_xlim(1.95, 2.95)ax3.set_ylim(4700, 3500)ax3.grid()"
},
{
"code": null,
"e": 7622,
"s": 7307,
"text": "We can see from the previous code snippet that we have a number of elements that are repeated in each of the axis calls such as ax.set_ylim(4700, 3500). We can separate these out so that we only need to call these functions once. This saves on the amount of lines we need to write and makes the code more readable."
},
{
"code": null,
"e": 7711,
"s": 7622,
"text": "To achieve this, we add in a new for loop which will loop over the axes within fig.axes."
},
{
"code": null,
"e": 7840,
"s": 7711,
"text": "for i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.grid() ax.set_xlabel(curve_names[i])"
},
{
"code": null,
"e": 7914,
"s": 7840,
"text": "Our final code, after separating out the common elements looks like this:"
},
{
"code": null,
"e": 8566,
"s": 7914,
"text": "fig, axes = plt.subplots(figsize=(10,10))curve_names = ['Gamma', 'Deep Res', 'Density']#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)ax1.plot(\"GR\", \"DEPTH\", data = df, color = \"green\")ax1.set_xlim(0, 200) ax2.plot(\"RDEP\", \"DEPTH\", data = df, color = \"red\")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax3.plot(\"DEN\", \"DEPTH\", data = df, color = \"red\")ax3.set_xlim(1.95, 2.95)for i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.grid() ax.set_xlabel(curve_names[i])"
},
{
"code": null,
"e": 8811,
"s": 8566,
"text": "To tidy the plot up a little more, we can remove the depth labels in between each subplot / track and reduce the space between them. This is achieved by the looping over only ax2 and ax3, and by adjusting the width of the padding between plots."
},
{
"code": null,
"e": 8988,
"s": 8811,
"text": "#Hide tick labels on the y-axis for ax in [ax2, ax3]: plt.setp(ax.get_yticklabels(), visible = False)#Reduce the space between each subplotfig.subplots_adjust(wspace = 0.05)"
},
{
"code": null,
"e": 9023,
"s": 8988,
"text": "We then end up with the following:"
},
{
"code": null,
"e": 9943,
"s": 9023,
"text": "fig, axes = plt.subplots(figsize=(10,10))curve_names = ['Gamma', 'Deep Res', 'Density']#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)#Set up the individual log tracks / subplotsax1.plot(\"GR\", \"DEPTH\", data = df, color = \"green\")ax1.set_xlim(0, 200) ax2.plot(\"RDEP\", \"DEPTH\", data = df, color = \"red\")ax2.set_xlim(0.2, 2000)ax2.semilogx()ax3.plot(\"DEN\", \"DEPTH\", data = df, color = \"red\")ax3.set_xlim(1.95, 2.95)#Set up the common elements between the subplotsfor i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.grid() ax.set_xlabel(curve_names[i])#Hide tick labels on the y-axis for ax in [ax2, ax3]: plt.setp(ax.get_yticklabels(), visible = False)#Reduce the space between each subplotfig.subplots_adjust(wspace = 0.05)"
},
{
"code": null,
"e": 10134,
"s": 9943,
"text": "It is standard to plot bulk density and neutron porosity on the same subplot / track. The interaction of these two curves allows us to identify lithology variations and hydrocarbon presence."
},
{
"code": null,
"e": 10410,
"s": 10134,
"text": "As the two measurements are on different units and scales (1.95 to 2.95 g/cc for Bulk Density and -15 to 60 for Neutron Porosity) we need to add another subplot on top using the twiny function. This allows us to use the same y-axis between the plots, but the x-axis can vary."
},
{
"code": null,
"e": 10558,
"s": 10410,
"text": "All labels have been moved to the top of the plot which is done by using ax.xaxis.set_ticks_position('top') and ax.xaxis.set_label_position('top')."
},
{
"code": null,
"e": 10746,
"s": 10558,
"text": "We then need to modify the main for loop to check when we reach ax4 (which will be when i = 3, as Python indexes from 0) and then adjust the spine so that it sits above the Density label."
},
{
"code": null,
"e": 11978,
"s": 10746,
"text": "fig, axes = plt.subplots(figsize=(10,10))curve_names = ['Gamma', 'Deep Res', 'Density', 'Neutron']#Set up the plot axesax1 = plt.subplot2grid((1,3), (0,0), rowspan=1, colspan = 1) ax2 = plt.subplot2grid((1,3), (0,1), rowspan=1, colspan = 1)ax3 = plt.subplot2grid((1,3), (0,2), rowspan=1, colspan = 1)ax4 = ax3.twiny()#Set up the individual log tracks / subplotsax1.plot(\"GR\", \"DEPTH\", data = df, color = \"green\", lw = 0.5)ax1.set_xlim(0, 200) ax2.plot(\"RDEP\", \"DEPTH\", data = df, color = \"red\", lw = 0.5)ax2.set_xlim(0.2, 2000)ax2.semilogx()ax3.plot(\"DEN\", \"DEPTH\", data = df, color = \"red\", lw = 0.5)ax3.set_xlim(1.95, 2.95)ax4.plot(\"NEU\", \"DEPTH\", data = df, color = \"blue\", lw = 0.5)ax4.set_xlim(45, -15)#Set up the common elements between the subplotsfor i, ax in enumerate(fig.axes): ax.set_ylim(4700, 3500) # Set the depth range ax.xaxis.set_ticks_position(\"top\") ax.xaxis.set_label_position(\"top\") ax.set_xlabel(curve_names[i]) if i == 3: ax.spines[\"top\"].set_position((\"axes\", 1.08)) else: ax.grid() #Hide tick labels on the y-axis for ax in [ax2, ax3]: plt.setp(ax.get_yticklabels(), visible = False)#Reduce the space between each subplotfig.subplots_adjust(wspace = 0.05)"
},
{
"code": null,
"e": 12264,
"s": 11978,
"text": "In this short tutorial, we have covered the basics of how to display a well log plot using matplotlib, how to add multiple tracks/subplots, and plot two curves on top of each other. Matplotlib provides a great way to build simple log plots from scratch and is a great library to learn."
},
{
"code": null,
"e": 12284,
"s": 12264,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 12496,
"s": 12284,
"text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub."
},
{
"code": null,
"e": 12570,
"s": 12496,
"text": "If you want to get in touch you can find me on LinkedIn or at my website."
}
] |
Graphics.Clear() Method in C# with Examples - GeeksforGeeks
|
04 Apr, 2019
Graphics.Clear(color) Method is used to clear the canvas and paints it up with the specified background color.
Syntax: public void Clear (System.Drawing.Color color);Parameter:color: Color identifier which contains RGB values, to colour the background of canvas.
Example 1:
// C# snippet to print GeeksForGeeksusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace GFG { class PrintableForm : Form { // Main Method public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs e) { Font font = new Font("Arial", 16); SolidBrush brush = new SolidBrush(Color.Black); PointF point = new PointF(10.0F, 10.0F); e.Graphics.DrawString("GeeksForGeeks", font, brush, point); }}}
Output:
Example 2:
// C# program to illustrate the Clear Method// C# snippet to print GeeksForGeeksusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace GFG { class PrintableForm : Form { // Main Method public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs e) { e.Graphics.Clear(Color.Coral); }}}
Output:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.drawing.graphics.clear?view=netframework-4.7.2
CSharp-Drawing-Namespace
CSharp-Graphics-Class
CSharp-method
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#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
|
[
{
"code": null,
"e": 25657,
"s": 25629,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 25768,
"s": 25657,
"text": "Graphics.Clear(color) Method is used to clear the canvas and paints it up with the specified background color."
},
{
"code": null,
"e": 25920,
"s": 25768,
"text": "Syntax: public void Clear (System.Drawing.Color color);Parameter:color: Color identifier which contains RGB values, to colour the background of canvas."
},
{
"code": null,
"e": 25931,
"s": 25920,
"text": "Example 1:"
},
{
"code": "// C# snippet to print GeeksForGeeksusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace GFG { class PrintableForm : Form { // Main Method public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs e) { Font font = new Font(\"Arial\", 16); SolidBrush brush = new SolidBrush(Color.Black); PointF point = new PointF(10.0F, 10.0F); e.Graphics.DrawString(\"GeeksForGeeks\", font, brush, point); }}}",
"e": 26551,
"s": 25931,
"text": null
},
{
"code": null,
"e": 26559,
"s": 26551,
"text": "Output:"
},
{
"code": null,
"e": 26570,
"s": 26559,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the Clear Method// C# snippet to print GeeksForGeeksusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace GFG { class PrintableForm : Form { // Main Method public static void Main() { Application.Run(new PrintableForm()); } public PrintableForm() { ResizeRedraw = true; } protected override void OnPaint(PaintEventArgs e) { e.Graphics.Clear(Color.Coral); }}}",
"e": 27063,
"s": 26570,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27063,
"text": "Output:"
},
{
"code": null,
"e": 27082,
"s": 27071,
"text": "Reference:"
},
{
"code": null,
"e": 27180,
"s": 27082,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.drawing.graphics.clear?view=netframework-4.7.2"
},
{
"code": null,
"e": 27205,
"s": 27180,
"text": "CSharp-Drawing-Namespace"
},
{
"code": null,
"e": 27227,
"s": 27205,
"text": "CSharp-Graphics-Class"
},
{
"code": null,
"e": 27241,
"s": 27227,
"text": "CSharp-method"
},
{
"code": null,
"e": 27244,
"s": 27241,
"text": "C#"
},
{
"code": null,
"e": 27342,
"s": 27244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27365,
"s": 27342,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27393,
"s": 27365,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27410,
"s": 27393,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27432,
"s": 27410,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27461,
"s": 27432,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27501,
"s": 27461,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27524,
"s": 27501,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 27567,
"s": 27524,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27607,
"s": 27567,
"text": "Convert String to Character Array in C#"
}
] |
How to control your mouse and keyboard using the pynput library in Python
|
The pynput library allows you to control and monitor/listen to your input devices such as they keyboard and mouse.
The pynput.mouse allows you control and monitor the mouse, while the pynput.keyboard allows you to control and monitor the keyboard.
In this article, we will be moving the cursor to a specific position, automate clicks, and simulate keystrokes from the keyboard.
Without further ado, letβs get started.
Since the pynput module does not come packaged with Python, you will have to manually download and install it using the pip package manager.
To do this, launch your terminal and use the command below.
pip install pynput
Once the library has been successfully downloaded and installed, you are all set to import its various module to your Python script.
Since we will be importing various modules for both the keyboard and mouse, we will discuss about the import statements later on.
In order to control and simulate your mouse using Python, you must import the mouse module from the pynput library. Since we will be simulating clicks and movement as well, we will import them along with the module.
from pynput.mouse import Button, Controller
Firstly, we will be using Controller() method to move the mouse around the screen.
mouse = Controller()
Now, if you want to move your mouse to any position on your screen, you just provide its coordinates.
mouse.position = (50,60)
If you want to see where your mouse moved, you can print it.
print('Current mouse position β> {0}'.format(mouse.position))
If you want to move the mouse relative to its current position, use the move function.
mouse.move(30,15)
If you want to simulate button presses,
mouse.press(Button.left)
mouse.release(Button.left)
mouse.press(Button.right)
mouse.release(Button.right)
For double clicks, use
mouse.click(Button.left, 2)
You can even simulate scrolls using pynput,
mouse.scroll(0,2)
This will scroll two steps down, the x coordinate is used to navigate the scroll from left to right and the y coordinate for top to bottom.
from pynput.mouse import Button, Controller
mouse = Controller()
mouse.position = (50,60)
print('Current mouse position β> {0}'.format(mouse.position))
mouse.move(30,15)
mouse.press(Button.left)
mouse.release(Button.left)
mouse.press(Button.right)
mouse.release(Button.right)
mouse.click(Button.left, 2)
mouse.scroll(0,2)
Using above methods, you can simulate drawing shapes on paint using basic coordinate geometry.
Firstly, we import the required modules and functions. In the keyboard module within the pynput library, we will be using the Key and Controller functions.
From pynput.keyboard import Key, Controller
We will be using the Controller method to control the Keyboard and simulate keystrokes.
keyboard = Controller()
Now, to simulate keystrokes, we have the press and release methods
keyboard.press('a')
keyboard.release('a')
This works for all alphabets, including upper case. For upper case, you just use βAβ instead of βaβ.
You can simulate other keypresses such as ctrl, alt, space etc as well.
keyboard.press(Key.space)
keyboard.release(Key.space)
keyboard.press(Key.ctrl)
keyboard.release(Key.ctrl)
If you want to simulate typing in sentences or words at once, you can use the type function.
keyboard.type('Hello World!!')
And thatβs basically how you control or simulate a keyboard device on Python.
from pynput.keyboard import Key, Controller
keyboard = Controller()
keyboard.press('a')
keyboard.release('a')
keyboard.press(Key.space)
keyboard.release(Key.space)
keyboard.press(Key.ctrl)
keyboard.release(Key.ctrl)
keyboard.type('Hello World!!')
You now know how to simulate keyboard and mouse input devices using Pythonβs pynput library.
Using this, you can build automated bots that perform clicking actions in clicker games, build a spam bot that sends out various different forms of messages at once. The applications are quite limitless as you can build any kind of automation tool using this method.
SpamBot mini project β https://github.com/SVijayB/Spamβbotz
If you want to read more about pynput and explore its various other functions, you can check out its official documentation at β
https://pynput.readthedocs.io/en/latest/index.html.
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "The pynput library allows you to control and monitor/listen to your input devices such as they keyboard and mouse."
},
{
"code": null,
"e": 1310,
"s": 1177,
"text": "The pynput.mouse allows you control and monitor the mouse, while the pynput.keyboard allows you to control and monitor the keyboard."
},
{
"code": null,
"e": 1440,
"s": 1310,
"text": "In this article, we will be moving the cursor to a specific position, automate clicks, and simulate keystrokes from the keyboard."
},
{
"code": null,
"e": 1480,
"s": 1440,
"text": "Without further ado, letβs get started."
},
{
"code": null,
"e": 1621,
"s": 1480,
"text": "Since the pynput module does not come packaged with Python, you will have to manually download and install it using the pip package manager."
},
{
"code": null,
"e": 1681,
"s": 1621,
"text": "To do this, launch your terminal and use the command below."
},
{
"code": null,
"e": 1700,
"s": 1681,
"text": "pip install pynput"
},
{
"code": null,
"e": 1833,
"s": 1700,
"text": "Once the library has been successfully downloaded and installed, you are all set to import its various module to your Python script."
},
{
"code": null,
"e": 1963,
"s": 1833,
"text": "Since we will be importing various modules for both the keyboard and mouse, we will discuss about the import statements later on."
},
{
"code": null,
"e": 2179,
"s": 1963,
"text": "In order to control and simulate your mouse using Python, you must import the mouse module from the pynput library. Since we will be simulating clicks and movement as well, we will import them along with the module."
},
{
"code": null,
"e": 2223,
"s": 2179,
"text": "from pynput.mouse import Button, Controller"
},
{
"code": null,
"e": 2306,
"s": 2223,
"text": "Firstly, we will be using Controller() method to move the mouse around the screen."
},
{
"code": null,
"e": 2327,
"s": 2306,
"text": "mouse = Controller()"
},
{
"code": null,
"e": 2429,
"s": 2327,
"text": "Now, if you want to move your mouse to any position on your screen, you just provide its coordinates."
},
{
"code": null,
"e": 2455,
"s": 2429,
"text": "mouse.position = (50,60)\n"
},
{
"code": null,
"e": 2516,
"s": 2455,
"text": "If you want to see where your mouse moved, you can print it."
},
{
"code": null,
"e": 2578,
"s": 2516,
"text": "print('Current mouse position β> {0}'.format(mouse.position))"
},
{
"code": null,
"e": 2665,
"s": 2578,
"text": "If you want to move the mouse relative to its current position, use the move function."
},
{
"code": null,
"e": 2683,
"s": 2665,
"text": "mouse.move(30,15)"
},
{
"code": null,
"e": 2723,
"s": 2683,
"text": "If you want to simulate button presses,"
},
{
"code": null,
"e": 2829,
"s": 2723,
"text": "mouse.press(Button.left)\nmouse.release(Button.left)\nmouse.press(Button.right)\nmouse.release(Button.right)"
},
{
"code": null,
"e": 2852,
"s": 2829,
"text": "For double clicks, use"
},
{
"code": null,
"e": 2880,
"s": 2852,
"text": "mouse.click(Button.left, 2)"
},
{
"code": null,
"e": 2924,
"s": 2880,
"text": "You can even simulate scrolls using pynput,"
},
{
"code": null,
"e": 2942,
"s": 2924,
"text": "mouse.scroll(0,2)"
},
{
"code": null,
"e": 3082,
"s": 2942,
"text": "This will scroll two steps down, the x coordinate is used to navigate the scroll from left to right and the y coordinate for top to bottom."
},
{
"code": null,
"e": 3404,
"s": 3082,
"text": "from pynput.mouse import Button, Controller\nmouse = Controller()\nmouse.position = (50,60)\nprint('Current mouse position β> {0}'.format(mouse.position))\nmouse.move(30,15)\nmouse.press(Button.left)\nmouse.release(Button.left)\nmouse.press(Button.right)\nmouse.release(Button.right)\nmouse.click(Button.left, 2)\nmouse.scroll(0,2)"
},
{
"code": null,
"e": 3499,
"s": 3404,
"text": "Using above methods, you can simulate drawing shapes on paint using basic coordinate geometry."
},
{
"code": null,
"e": 3655,
"s": 3499,
"text": "Firstly, we import the required modules and functions. In the keyboard module within the pynput library, we will be using the Key and Controller functions."
},
{
"code": null,
"e": 3699,
"s": 3655,
"text": "From pynput.keyboard import Key, Controller"
},
{
"code": null,
"e": 3787,
"s": 3699,
"text": "We will be using the Controller method to control the Keyboard and simulate keystrokes."
},
{
"code": null,
"e": 3811,
"s": 3787,
"text": "keyboard = Controller()"
},
{
"code": null,
"e": 3878,
"s": 3811,
"text": "Now, to simulate keystrokes, we have the press and release methods"
},
{
"code": null,
"e": 3920,
"s": 3878,
"text": "keyboard.press('a')\nkeyboard.release('a')"
},
{
"code": null,
"e": 4021,
"s": 3920,
"text": "This works for all alphabets, including upper case. For upper case, you just use βAβ instead of βaβ."
},
{
"code": null,
"e": 4093,
"s": 4021,
"text": "You can simulate other keypresses such as ctrl, alt, space etc as well."
},
{
"code": null,
"e": 4199,
"s": 4093,
"text": "keyboard.press(Key.space)\nkeyboard.release(Key.space)\nkeyboard.press(Key.ctrl)\nkeyboard.release(Key.ctrl)"
},
{
"code": null,
"e": 4292,
"s": 4199,
"text": "If you want to simulate typing in sentences or words at once, you can use the type function."
},
{
"code": null,
"e": 4323,
"s": 4292,
"text": "keyboard.type('Hello World!!')"
},
{
"code": null,
"e": 4401,
"s": 4323,
"text": "And thatβs basically how you control or simulate a keyboard device on Python."
},
{
"code": null,
"e": 4648,
"s": 4401,
"text": "from pynput.keyboard import Key, Controller\nkeyboard = Controller()\nkeyboard.press('a')\nkeyboard.release('a')\nkeyboard.press(Key.space)\nkeyboard.release(Key.space)\nkeyboard.press(Key.ctrl)\nkeyboard.release(Key.ctrl)\nkeyboard.type('Hello World!!')"
},
{
"code": null,
"e": 4741,
"s": 4648,
"text": "You now know how to simulate keyboard and mouse input devices using Pythonβs pynput library."
},
{
"code": null,
"e": 5008,
"s": 4741,
"text": "Using this, you can build automated bots that perform clicking actions in clicker games, build a spam bot that sends out various different forms of messages at once. The applications are quite limitless as you can build any kind of automation tool using this method."
},
{
"code": null,
"e": 5068,
"s": 5008,
"text": "SpamBot mini project β https://github.com/SVijayB/Spamβbotz"
},
{
"code": null,
"e": 5197,
"s": 5068,
"text": "If you want to read more about pynput and explore its various other functions, you can check out its official documentation at β"
},
{
"code": null,
"e": 5249,
"s": 5197,
"text": "https://pynput.readthedocs.io/en/latest/index.html."
}
] |
IIF() Function in SQL Server - GeeksforGeeks
|
16 Oct, 2020
The SQL Server IIF() function has three parameters. IIF() function judges or evaluates the first parameter and returns the second parameters if the first parameters is true; otherwise, it returns the third parameters. IIF() function used in SQL Server to add if-else logic to queries.>
Syntax :
IIF(boolean_value, true_value, false_value)
Parameters used in Syntax:
boolean_value βIt is a value to be judged. It must be a valid boolean value, or the function will raise an error.
true_value βIt is the value to be resulted if the boolean_value to true.
false_value βIt is the value to be resulted if the boolean_value to false.
Fact to know: The IIF() function is similar to a CASE expression β
CASE
WHEN boolean_expression
THEN true_value
ELSE
false_value
END
Example-1 :To use the IIF() function to check if 40 < 60 :
SELECT IIF(40 < 60, 'True', 'False') AS Result ;
Output :ResultTrue
Let us assume we have below sample table named βGeektableβ:
Example-2 :To use IIF() function with table column.Below example uses IIF()function within IIF() functions:
SELECT
IIF(G_status = 1, βWaitingβ,
IIF(G_status=2, βInProgressβ,
IIF(G_status=3, βRejectedβ,
IIF(G_status=4, βCompletedβ)
)
)
) AS Status,
COUNT(G_id) AS Count
FROM Geektable
GROUP BY G_status ;
Output :
Example-3 :To use IIF() function with aggregate functions.Below example uses IIF()function with the SUM() function:
SELECT
SUM(IIF(G_status = 1, 1, 0)) AS βWaitingβ,
SUM(IIF(G_status = 2, 1, 0)) AS βInProgressβ,
SUM(IIF(G_status = 3, 1, 0)) AS βRejectedβ,
SUM(IIF(G_status = 4, 1, 0)) AS βCompletedβ,
COUNT(*) AS Total
FROM Geektable;
Output :Here, the IIF() function results 1 or 0 if the status is matched. The SUM() function results the number of each status.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 24366,
"s": 24338,
"text": "\n16 Oct, 2020"
},
{
"code": null,
"e": 24652,
"s": 24366,
"text": "The SQL Server IIF() function has three parameters. IIF() function judges or evaluates the first parameter and returns the second parameters if the first parameters is true; otherwise, it returns the third parameters. IIF() function used in SQL Server to add if-else logic to queries.>"
},
{
"code": null,
"e": 24661,
"s": 24652,
"text": "Syntax :"
},
{
"code": null,
"e": 24706,
"s": 24661,
"text": "IIF(boolean_value, true_value, false_value)\n"
},
{
"code": null,
"e": 24733,
"s": 24706,
"text": "Parameters used in Syntax:"
},
{
"code": null,
"e": 24847,
"s": 24733,
"text": "boolean_value βIt is a value to be judged. It must be a valid boolean value, or the function will raise an error."
},
{
"code": null,
"e": 24920,
"s": 24847,
"text": "true_value βIt is the value to be resulted if the boolean_value to true."
},
{
"code": null,
"e": 24995,
"s": 24920,
"text": "false_value βIt is the value to be resulted if the boolean_value to false."
},
{
"code": null,
"e": 25063,
"s": 24995,
"text": "Fact to know: The IIF() function is similar to a CASE expression β "
},
{
"code": null,
"e": 25154,
"s": 25063,
"text": "CASE \n WHEN boolean_expression \n THEN true_value\n ELSE\n false_value\nEND\n"
},
{
"code": null,
"e": 25213,
"s": 25154,
"text": "Example-1 :To use the IIF() function to check if 40 < 60 :"
},
{
"code": null,
"e": 25264,
"s": 25213,
"text": "SELECT IIF(40 < 60, 'True', 'False') AS Result ; "
},
{
"code": null,
"e": 25283,
"s": 25264,
"text": "Output :ResultTrue"
},
{
"code": null,
"e": 25343,
"s": 25283,
"text": "Let us assume we have below sample table named βGeektableβ:"
},
{
"code": null,
"e": 25451,
"s": 25343,
"text": "Example-2 :To use IIF() function with table column.Below example uses IIF()function within IIF() functions:"
},
{
"code": null,
"e": 25715,
"s": 25451,
"text": "SELECT \n IIF(G_status = 1, βWaitingβ, \n IIF(G_status=2, βInProgressβ,\n IIF(G_status=3, βRejectedβ,\n IIF(G_status=4, βCompletedβ)\n )\n )\n ) AS Status,\n\n COUNT(G_id) AS Count\nFROM Geektable\nGROUP BY G_status ; "
},
{
"code": null,
"e": 25724,
"s": 25715,
"text": "Output :"
},
{
"code": null,
"e": 25840,
"s": 25724,
"text": "Example-3 :To use IIF() function with aggregate functions.Below example uses IIF()function with the SUM() function:"
},
{
"code": null,
"e": 26089,
"s": 25840,
"text": "SELECT \n SUM(IIF(G_status = 1, 1, 0)) AS βWaitingβ, \n SUM(IIF(G_status = 2, 1, 0)) AS βInProgressβ, \n SUM(IIF(G_status = 3, 1, 0)) AS βRejectedβ, \n SUM(IIF(G_status = 4, 1, 0)) AS βCompletedβ, \n COUNT(*) AS Total\n\nFROM Geektable;\n"
},
{
"code": null,
"e": 26217,
"s": 26089,
"text": "Output :Here, the IIF() function results 1 or 0 if the status is matched. The SUM() function results the number of each status."
},
{
"code": null,
"e": 26226,
"s": 26217,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26237,
"s": 26226,
"text": "SQL-Server"
},
{
"code": null,
"e": 26241,
"s": 26237,
"text": "SQL"
},
{
"code": null,
"e": 26245,
"s": 26241,
"text": "SQL"
},
{
"code": null,
"e": 26343,
"s": 26245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26409,
"s": 26343,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26466,
"s": 26409,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 26498,
"s": 26466,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26534,
"s": 26498,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26549,
"s": 26534,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26627,
"s": 26549,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26644,
"s": 26627,
"text": "SQL using Python"
},
{
"code": null,
"e": 26706,
"s": 26644,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 26772,
"s": 26706,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
}
] |
How to install MSI file using batch file in PowerShell?
|
Let say we have one MSI file and we need to install the MSI file on the remote computers using PowerShell but that MSI file should be deployed with the Batch file and should be executed using PowerShell.
In this example, we have a 7-zip MSI file and batch file we will first write the installation instructions as shown below.
msiexec /i "C:\temp\7z1900-x64.msi" /quiet
We have the installation MSI package located at the C:\temp location. We will save the above instruction inside the 7ZipInstaller.bat file.
Now we need to call the batch file as shown below. βWait will wait for the batch file to execute first and then moves to the next instruction if any and βNoNewWindow will
Start-Process C:\Temp\7zipInstaller.bat -Wait -NoNewWindow
Once you run the above command, it will install 7zip at the location specified. You can directly pass these instructions inside the Start-Process to execute MSI but if we need to execute the batch file then this is a good way because we can call this batch file remotely as well. The below command is for the remote computer.
Invoke-Command -ComputerName TestMachine1, TestMachine2 -ScriptBlock{
Start-Process C:\Temp\7zipInstaller.bat -Wait -NoNewWindow
}
This command will run on the computers Testmachine1 and Testmachine2. Make sure you copy the MSI package to the remote location before running this command.
|
[
{
"code": null,
"e": 1266,
"s": 1062,
"text": "Let say we have one MSI file and we need to install the MSI file on the remote computers using PowerShell but that MSI file should be deployed with the Batch file and should be executed using PowerShell."
},
{
"code": null,
"e": 1389,
"s": 1266,
"text": "In this example, we have a 7-zip MSI file and batch file we will first write the installation instructions as shown below."
},
{
"code": null,
"e": 1432,
"s": 1389,
"text": "msiexec /i \"C:\\temp\\7z1900-x64.msi\" /quiet"
},
{
"code": null,
"e": 1572,
"s": 1432,
"text": "We have the installation MSI package located at the C:\\temp location. We will save the above instruction inside the 7ZipInstaller.bat file."
},
{
"code": null,
"e": 1743,
"s": 1572,
"text": "Now we need to call the batch file as shown below. βWait will wait for the batch file to execute first and then moves to the next instruction if any and βNoNewWindow will"
},
{
"code": null,
"e": 1802,
"s": 1743,
"text": "Start-Process C:\\Temp\\7zipInstaller.bat -Wait -NoNewWindow"
},
{
"code": null,
"e": 2128,
"s": 1802,
"text": "Once you run the above command, it will install 7zip at the location specified. You can directly pass these instructions inside the Start-Process to execute MSI but if we need to execute the batch file then this is a good way because we can call this batch file remotely as well. The below command is for the remote computer."
},
{
"code": null,
"e": 2262,
"s": 2128,
"text": "Invoke-Command -ComputerName TestMachine1, TestMachine2 -ScriptBlock{\n Start-Process C:\\Temp\\7zipInstaller.bat -Wait -NoNewWindow\n}"
},
{
"code": null,
"e": 2419,
"s": 2262,
"text": "This command will run on the computers Testmachine1 and Testmachine2. Make sure you copy the MSI package to the remote location before running this command."
}
] |
PostgreSQL - Function Returning A Table - GeeksforGeeks
|
28 Aug, 2020
In this article, we will look into the process of developing functions that returns a table. We will use the film table in the sample database for the demonstration:
The following function returns all films whose titles match a particular pattern using ILIKE operator:
CREATE OR REPLACE FUNCTION get_film (p_pattern VARCHAR)
RETURNS TABLE (
film_title VARCHAR,
film_release_year INT
)
AS $$
BEGIN
RETURN QUERY SELECT
title,
cast( release_year as integer)
FROM
film
WHERE
title ILIKE p_pattern ;
END; $$
LANGUAGE 'plpgsql';
This get_film(varchar) function accepts one parameter p_pattern which is a pattern that you want to match with the film title.
To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, ).
In the function, we return a query that is a result of a SELECT statement. Notice that the columns in the SELECT statement must match with the columns of the table that we want to return. Because the data type of release_yearof the film table is not an integer, we have to convert it into an integer using CAST.
We can test the function using the following statement:
SELECT
*
FROM
get_film ('Al%');
We called the get_film(varchar) function to get all films whose title starts with Al. The following is the result:
Notice that if you call the function using the following statement:
SELECT
get_film ('Al%');
PostgreSQL returns a table with one column that holds the array of films.
In practice, you often process each individual row before appending it in the functionβs result set. The following example illustrates the idea.
CREATE OR REPLACE FUNCTION get_film (p_pattern VARCHAR, p_year INT)
RETURNS TABLE (
film_title VARCHAR,
film_release_year INT
) AS $$
DECLARE
var_r record;
BEGIN
FOR var_r IN(SELECT
title,
release_year
FROM film
WHERE title ILIKE p_pattern AND
release_year = p_year)
LOOP
film_title := upper(var_r.title) ;
film_release_year := var_r.release_year;
RETURN NEXT;
END LOOP;
END; $$
LANGUAGE 'plpgsql';
We have created a function with the similar name get_film(varchar, int) but accepts two parameters:
The first parameter is the p_pattern that we used to search for a film if the title matches with this pattern.
The second parameter is the release year of the film.
The RETURN NEXT statement adds a row to the result set of the function. The execution continues and the result set is building up in each iteration of the loop.
See the following test case:
SELECT
*
FROM
get_film ('%er', 2006);
Output:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - REPLACE Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - TIME Data Type
PostgreSQL - Rename Table
PostgreSQL - Cursor
PostgreSQL - SELECT
|
[
{
"code": null,
"e": 25363,
"s": 25335,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 25529,
"s": 25363,
"text": "In this article, we will look into the process of developing functions that returns a table. We will use the film table in the sample database for the demonstration:"
},
{
"code": null,
"e": 25632,
"s": 25529,
"text": "The following function returns all films whose titles match a particular pattern using ILIKE operator:"
},
{
"code": null,
"e": 25955,
"s": 25632,
"text": "CREATE OR REPLACE FUNCTION get_film (p_pattern VARCHAR) \n RETURNS TABLE (\n film_title VARCHAR,\n film_release_year INT\n) \nAS $$\nBEGIN\n RETURN QUERY SELECT\n title,\n cast( release_year as integer)\n FROM\n film\n WHERE\n title ILIKE p_pattern ;\nEND; $$ \n\nLANGUAGE 'plpgsql';\n"
},
{
"code": null,
"e": 26082,
"s": 25955,
"text": "This get_film(varchar) function accepts one parameter p_pattern which is a pattern that you want to match with the film title."
},
{
"code": null,
"e": 26228,
"s": 26082,
"text": "To return a table from the function, you use RETURNS TABLE syntax and specify the columns of the table. Each column is separated by a comma (, )."
},
{
"code": null,
"e": 26540,
"s": 26228,
"text": "In the function, we return a query that is a result of a SELECT statement. Notice that the columns in the SELECT statement must match with the columns of the table that we want to return. Because the data type of release_yearof the film table is not an integer, we have to convert it into an integer using CAST."
},
{
"code": null,
"e": 26596,
"s": 26540,
"text": "We can test the function using the following statement:"
},
{
"code": null,
"e": 26637,
"s": 26596,
"text": "SELECT\n *\nFROM\n get_film ('Al%');\n"
},
{
"code": null,
"e": 26752,
"s": 26637,
"text": "We called the get_film(varchar) function to get all films whose title starts with Al. The following is the result:"
},
{
"code": null,
"e": 26820,
"s": 26752,
"text": "Notice that if you call the function using the following statement:"
},
{
"code": null,
"e": 26850,
"s": 26820,
"text": "SELECT\n get_film ('Al%');\n"
},
{
"code": null,
"e": 26924,
"s": 26850,
"text": "PostgreSQL returns a table with one column that holds the array of films."
},
{
"code": null,
"e": 27069,
"s": 26924,
"text": "In practice, you often process each individual row before appending it in the functionβs result set. The following example illustrates the idea."
},
{
"code": null,
"e": 27620,
"s": 27069,
"text": "CREATE OR REPLACE FUNCTION get_film (p_pattern VARCHAR, p_year INT) \n RETURNS TABLE (\n film_title VARCHAR,\n film_release_year INT\n) AS $$\nDECLARE \n var_r record;\nBEGIN\n FOR var_r IN(SELECT \n title, \n release_year \n FROM film \n WHERE title ILIKE p_pattern AND \n release_year = p_year) \n LOOP\n film_title := upper(var_r.title) ; \n film_release_year := var_r.release_year;\n RETURN NEXT;\n END LOOP;\nEND; $$ \nLANGUAGE 'plpgsql';\n"
},
{
"code": null,
"e": 27720,
"s": 27620,
"text": "We have created a function with the similar name get_film(varchar, int) but accepts two parameters:"
},
{
"code": null,
"e": 27831,
"s": 27720,
"text": "The first parameter is the p_pattern that we used to search for a film if the title matches with this pattern."
},
{
"code": null,
"e": 27885,
"s": 27831,
"text": "The second parameter is the release year of the film."
},
{
"code": null,
"e": 28046,
"s": 27885,
"text": "The RETURN NEXT statement adds a row to the result set of the function. The execution continues and the result set is building up in each iteration of the loop."
},
{
"code": null,
"e": 28075,
"s": 28046,
"text": "See the following test case:"
},
{
"code": null,
"e": 28122,
"s": 28075,
"text": "SELECT\n *\nFROM\n get_film ('%er', 2006);\n"
},
{
"code": null,
"e": 28130,
"s": 28122,
"text": "Output:"
},
{
"code": null,
"e": 28150,
"s": 28130,
"text": "PostgreSQL-function"
},
{
"code": null,
"e": 28161,
"s": 28150,
"text": "PostgreSQL"
},
{
"code": null,
"e": 28259,
"s": 28161,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28289,
"s": 28259,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 28318,
"s": 28289,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 28342,
"s": 28318,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 28366,
"s": 28342,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 28396,
"s": 28366,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 28423,
"s": 28396,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 28451,
"s": 28423,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 28477,
"s": 28451,
"text": "PostgreSQL - Rename Table"
},
{
"code": null,
"e": 28497,
"s": 28477,
"text": "PostgreSQL - Cursor"
}
] |
C Program for Matrix Chain Multiplication | DP-8 - GeeksforGeeks
|
12 Dec, 2018
Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.
We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:
(ABC)D = (AB)(CD) = A(BCD) = ....
However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 Γ 30 matrix, B is a 30 Γ 5 matrix, and C is a 5 Γ 60 matrix. Then,
(AB)C = (10Γ30Γ5) + (10Γ5Γ60) = 1500 + 3000 = 4500 operations
A(BC) = (30Γ5Γ60) + (10Γ30Γ60) = 9000 + 18000 = 27000 operations.
Clearly the first parenthesization requires less number of operations.
Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.
Input: p[] = {40, 20, 30, 10, 30}
Output: 26000
There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
Let the input 4 matrices be A, B, C and D. The minimum number of
multiplications are obtained by putting parenthesis in following way
(A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30
Input: p[] = {10, 20, 30, 40, 30}
Output: 30000
There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30.
Let the input 4 matrices be A, B, C and D. The minimum number of
multiplications are obtained by putting parenthesis in following way
((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30
Input: p[] = {10, 20, 30}
Output: 6000
There are only two matrices of dimensions 10x20 and 20x30. So there
is only one way to multiply the matrices, cost of which is 10*20*30
Following is a recursive implementation that simply follows the above optimal substructure property.
C
/* A naive recursive implementation that simply follows the above optimal substructure property */#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int i, int j){ if (i == j) return 0; int k; int min = INT_MAX; int count; // place parenthesis at different places between first // and last matrix, recursively calculate count of // multiplications for each parenthesis placement and // return the minimum count for (k = i; k < j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver program to test above functionint main(){ int arr[] = { 1, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, 1, n - 1)); getchar(); return 0;}
Minimum number of multiplications is 30
Dynamic Programming Solution
C
// See the Cormen book for details of the following algorithm#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} int main(){ int arr[] = { 1, 2, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, size)); getchar(); return 0;}
Minimum number of multiplications is 18
Please refer complete article on Matrix Chain Multiplication | DP-8 for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to Append a Character to a String in C
C program to sort an array in ascending order
Producer Consumer Problem in C
Program to find Prime Numbers Between given Interval
time() function in C
Program to calculate First and Follow sets of given grammar
C Program to Swap two Numbers
Flex (Fast Lexical Analyzer Generator )
|
[
{
"code": null,
"e": 24764,
"s": 24736,
"text": "\n12 Dec, 2018"
},
{
"code": null,
"e": 24987,
"s": 24764,
"text": "Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications."
},
{
"code": null,
"e": 25242,
"s": 24987,
"text": "We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:"
},
{
"code": null,
"e": 25281,
"s": 25242,
"text": " (ABC)D = (AB)(CD) = A(BCD) = ....\n"
},
{
"code": null,
"e": 25536,
"s": 25281,
"text": "However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 Γ 30 matrix, B is a 30 Γ 5 matrix, and C is a 5 Γ 60 matrix. Then,"
},
{
"code": null,
"e": 25673,
"s": 25536,
"text": " (AB)C = (10Γ30Γ5) + (10Γ5Γ60) = 1500 + 3000 = 4500 operations\n A(BC) = (30Γ5Γ60) + (10Γ30Γ60) = 9000 + 18000 = 27000 operations.\n"
},
{
"code": null,
"e": 25744,
"s": 25673,
"text": "Clearly the first parenthesization requires less number of operations."
},
{
"code": null,
"e": 25995,
"s": 25744,
"text": "Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain."
},
{
"code": null,
"e": 26806,
"s": 25995,
"text": " Input: p[] = {40, 20, 30, 10, 30} \n Output: 26000 \n There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.\n Let the input 4 matrices be A, B, C and D. The minimum number of \n multiplications are obtained by putting parenthesis in following way\n (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30\n\n Input: p[] = {10, 20, 30, 40, 30} \n Output: 30000 \n There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. \n Let the input 4 matrices be A, B, C and D. The minimum number of \n multiplications are obtained by putting parenthesis in following way\n ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30\n\n Input: p[] = {10, 20, 30} \n Output: 6000 \n There are only two matrices of dimensions 10x20 and 20x30. So there \n is only one way to multiply the matrices, cost of which is 10*20*30\n"
},
{
"code": null,
"e": 26907,
"s": 26806,
"text": "Following is a recursive implementation that simply follows the above optimal substructure property."
},
{
"code": null,
"e": 26909,
"s": 26907,
"text": "C"
},
{
"code": "/* A naive recursive implementation that simply follows the above optimal substructure property */#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int i, int j){ if (i == j) return 0; int k; int min = INT_MAX; int count; // place parenthesis at different places between first // and last matrix, recursively calculate count of // multiplications for each parenthesis placement and // return the minimum count for (k = i; k < j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j]; if (count < min) min = count; } // Return minimum count return min;} // Driver program to test above functionint main(){ int arr[] = { 1, 2, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Minimum number of multiplications is %d \", MatrixChainOrder(arr, 1, n - 1)); getchar(); return 0;}",
"e": 27943,
"s": 26909,
"text": null
},
{
"code": null,
"e": 27984,
"s": 27943,
"text": "Minimum number of multiplications is 30\n"
},
{
"code": null,
"e": 28013,
"s": 27984,
"text": "Dynamic Programming Solution"
},
{
"code": null,
"e": 28015,
"s": 28013,
"text": "C"
},
{
"code": "// See the Cormen book for details of the following algorithm#include <limits.h>#include <stdio.h> // Matrix Ai has dimension p[i-1] x p[i] for i = 1..nint MatrixChainOrder(int p[], int n){ /* For simplicity of the program, one extra row and one extra column are allocated in m[][]. 0th row and 0th column of m[][] are not used */ int m[n][n]; int i, j, k, L, q; /* m[i, j] = Minimum number of scalar multiplications needed to compute the matrix A[i]A[i+1]...A[j] = A[i..j] where dimension of A[i] is p[i-1] x p[i] */ // cost is zero when multiplying one matrix. for (i = 1; i < n; i++) m[i][i] = 0; // L is chain length. for (L = 2; L < n; L++) { for (i = 1; i < n - L + 1; i++) { j = i + L - 1; m[i][j] = INT_MAX; for (k = i; k <= j - 1; k++) { // q = cost/scalar multiplications q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) m[i][j] = q; } } } return m[1][n - 1];} int main(){ int arr[] = { 1, 2, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Minimum number of multiplications is %d \", MatrixChainOrder(arr, size)); getchar(); return 0;}",
"e": 29317,
"s": 28015,
"text": null
},
{
"code": null,
"e": 29358,
"s": 29317,
"text": "Minimum number of multiplications is 18\n"
},
{
"code": null,
"e": 29444,
"s": 29358,
"text": "Please refer complete article on Matrix Chain Multiplication | DP-8 for more details!"
},
{
"code": null,
"e": 29455,
"s": 29444,
"text": "C Programs"
},
{
"code": null,
"e": 29553,
"s": 29455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29562,
"s": 29553,
"text": "Comments"
},
{
"code": null,
"e": 29575,
"s": 29562,
"text": "Old Comments"
},
{
"code": null,
"e": 29616,
"s": 29575,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29651,
"s": 29616,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29694,
"s": 29651,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 29740,
"s": 29694,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 29771,
"s": 29740,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 29824,
"s": 29771,
"text": "Program to find Prime Numbers Between given Interval"
},
{
"code": null,
"e": 29845,
"s": 29824,
"text": "time() function in C"
},
{
"code": null,
"e": 29905,
"s": 29845,
"text": "Program to calculate First and Follow sets of given grammar"
},
{
"code": null,
"e": 29935,
"s": 29905,
"text": "C Program to Swap two Numbers"
}
] |
How to Replace null with β-β JavaScript
|
We have to write a function that takes in an object with many keys and replaces all false values
with a dash (β - β). We will simply iterate over the original object, checking for the keys that
contain false values, and we will replace those false values with β-β without consuming any extra
space (i.e., in place)
const obj = {
key1: 'Hello',
key2: 'World',
key3: '',
key4: 45,
key5: 'can i use arrays',
key6: null,
key7: 'fast n furious',
key8: undefined,
key9: '',
key10: NaN,
};
const swapValue = (obj) => {
Object.keys(obj).forEach(key => {
if(!obj[key]){
obj[key] = '-';
}
});
};
swapValue(obj);
console.log(obj);
The output in the console will be β
{
key1: 'Hello',
key2: 'World',
key3: '-',
key4: 45,
key5: 'can i use arrays',
key6: '-',
key7: 'fast n furious',
key8: '-',
key9: '-',
key10: '-'
}
|
[
{
"code": null,
"e": 1377,
"s": 1062,
"text": "We have to write a function that takes in an object with many keys and replaces all false values\nwith a dash (β - β). We will simply iterate over the original object, checking for the keys that\ncontain false values, and we will replace those false values with β-β without consuming any extra\nspace (i.e., in place)"
},
{
"code": null,
"e": 1739,
"s": 1377,
"text": "const obj = {\n key1: 'Hello',\n key2: 'World',\n key3: '',\n key4: 45,\n key5: 'can i use arrays',\n key6: null,\n key7: 'fast n furious',\n key8: undefined,\n key9: '',\n key10: NaN,\n};\nconst swapValue = (obj) => {\n Object.keys(obj).forEach(key => {\n if(!obj[key]){\n obj[key] = '-';\n }\n });\n};\nswapValue(obj);\nconsole.log(obj);"
},
{
"code": null,
"e": 1775,
"s": 1739,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 1954,
"s": 1775,
"text": "{\n key1: 'Hello',\n key2: 'World',\n key3: '-',\n key4: 45,\n key5: 'can i use arrays',\n key6: '-',\n key7: 'fast n furious',\n key8: '-',\n key9: '-',\n key10: '-'\n}"
}
] |
A Data Science Web App to Predict Real Estate Price | by K G Prajwal | Towards Data Science
|
Web Development and Data Science have been a long time passion of mine. It has always been an idea to combine these two interests and merge them together and make a project. Finally, I have managed to accomplish this task by building a web app that predicts the real estate price for properties and houses across the city of Bengaluru, India. It has been a huge project and has taken a while. I shall make sure to walk you through every step that I have followed.
The project mainly has 4 steps:
Data Science
Machine Learning
Backend
Frontend
The first step is typical data science work where we take a data set from Kaggle called βBengaluru House price dataβ .We will perform some extensive data cleaning work on it to ensure that it gives accurate results during prediction.
This jupyter notebook entitled βRealEstatePricePredictor.ipynbβ is where we perform all the data science related work. As the jupyter notebook is self-explanatory I shall briefly touch upon the concepts that I have implemented. Our dataset requires a lot of work in terms of data cleaning. In fact, 70% of the notebook is all about data cleaning where we drop empty rows and remove unnecessary columns that wonβt help in prediction.
Next step, Feature Engineering which is the process of extracting useful and important information from the dataset that will contribute the most towards a successful prediction.
The final step is handling outliers. Outliers are anomalies that cause an enormous amount of damage to data and prediction. There is a lot of things to understand from the dataset logically to detect and remove these outliers.
Again, all of these have been explained in the jupyter notebook.
In the end, the original dataset which had almost 13000 rows and 9 columns are reduced to almost 7000 rows and 5 columns.
The final data obtained is subjected to a machine learning model. We will mainly use K-fold Cross Validation and GridSearchCV technique to perform hyper parameter tuning to obtain the best algorithm and parameters for the model.
Turns out linear regression model gives the best results for our data with a score above 80% which is not bad.
Now, our model needs to be exported into a pickle file (Bengaluru_House_Data.pickle) which converts python objects into a character stream. Also, we need to export the locations(columns) into a json(columns.json) file to be able to interact with it from the frontend.
We will use a Flask server as our backend to host the application locally. In the server folder we will set up two files:
server.py
The server.py file will be responsible for handling the routes for fetching the location names and predicting the house price. It also gets the form data from the front end and feeds it to the util.py. These routes can be tested using Postman app.
util.py
The util.py file is the main brains behind the back end. It has a function to load the JSON and pickle file. This file takes the form data from server.py and uses the model to predict the estimated price of the property.
The front end is made up of simple HTML, CSS and JavaScript. The user can select the number of square feet area, BHK, bathrooms and location in the form and hit on βESTIMATEβ button to get the estimated price. The JavaScript file is responsible for interacting with both the backend flask server routes and the frontend HTML. It gets the form data filled by the user and calls the function that uses the prediction model and renders the estimated price in lakhs rupees (1 lakh = 100000).
Let's see how our project works. Run the server.py file in the backend and open up the HTML web page we created. Input the area of the property in square feet, the number of BHK, the number of bathrooms and the location and hit βESTIMATEβ. π²Yay! We predicted the price of what could be the dream house of someone.
This part is quite tricky so make sure to do every step along with me.
As of now, the project is only local, we will learn how to deploy the application to the web using AWS EC2 instance.
We will use nginx which is a web server that can serve HTTP requests. The nginx can then interact with our Flask Server.
Download nginx from here and install it.
STEP 1: To make the estimation, in the script.js file, initially we had these two lines:
var url = "http://127.0.0.1:5000/predict_home_price";var url = "http://127.0.0.1:5000/get_location_names";
These two were just for the sake of running our app locally, now we must change these two lines into:
var url = "/api/predict_home_price";var url = "/api/get_location_names";
We need to configure the reverse proxy on nginx server so that all requests to β/apiβ are routed to port 5000 only.
STEP 2: Log in to your AWS console. You will need to know how to launch an AWS EC2 instance free-of-cost. While following the steps to launch your instance under step 6 make sure to add HTTP and HTTPS request type to make sure people can access your website.
STEP 3: Create new key pair, enter a name, download key(.pem file) and launch EC2 Instance.
STEP 4: Click on the βConnectβ option beside βLaunch Instanceβ where there will be a command under βExampleβ.
Copy this command. It would look something like this.
STEP 5: Open up bash shell and paste this command but replace the blacked out area with the path to your downloaded pem file.
You are now connected to the Linux machine on AWS cloud.
STEP 6: Now you need to copy your project onto that virtual machine using WinSCP. Download and launch WinSCP.
STEP 7: On your AWS if we click on βConnectβ again there is a command above βExampleβ, that looks something like:
Copy this to your WinSCP host name as this is the host name of your virtual machine.
STEP 7: Username is βubuntuβ. Before entering the password, we need to convert the .pem file into .ppk file using PuTTYgen. Please download PuTTYgen from this link.
Click on the βAdvancedβ button under the Password field. Select the downloaded .pem file, itβll open up PuTTYgen to convert the .pem file to .ppk file. Select the new .ppk and click βOKβ.
Hit βLoginβ.
Copy your whole root project folder(RealEstatePricePrediction) from your machine to the cloud server.
On the ubuntu shell of the server execute the following commands:
sudo apt-get updatesudo apt-get install nginx
Copy-paste the hostname in the βConnectβ dialog box which we saw earlier into the browser.
You should see the homepage of nginx running.
STEP 8: Execute the following commands:
cd /etc/nginx/sites-enabled/sudo unlink defaultcd ../sites-available/sudo vim BengaluruHousePrediction.conf
Copy-paste the following code in the .conf file. This is the reverse proxy setup.
server { listen 80; server_name BegaluruHousePrediction; root /home/ubuntu/RealEstatePricePrediction/client; index index.html; location /api/ { rewrite ^/api(.*) $1 break; proxy_pass http://127.0.0.1:5000; }}
Exit from the vim and execute the following commands:
cd ../sites-enabled/ln -v -s /etc/nginx/sites-available/BengaluruHousePrediction.conf inside /etc/nginx/sites-enabled
What we are doing in the above command is establishing a symbolic link.
Restart the server using:
sudo service nginx restart
Check status using:
sudo service nginx status
Go to your browser and enter the hostname link in the url. You should see your application frontend loading, yet the backend doesnβt work yet.
STEP 9: Go back to the terminal and type:
cd ~cd RealEstatePricePrediction/server/sudo apt-get python3-pipsudo pip3 install Flasksudo pip3 install scikit-learnsudo pip3 install numpy
Start backend server using:
python server.py
Your application is now live on the internet accessible from any place in the world.
I understand if the deployment phase was a little tough. You can contact me on my LinkedIn if you run into any errors. Feel free to check out the entire code-base on my GitHub.
I hope you all understood and learnt many things along the way.
|
[
{
"code": null,
"e": 636,
"s": 172,
"text": "Web Development and Data Science have been a long time passion of mine. It has always been an idea to combine these two interests and merge them together and make a project. Finally, I have managed to accomplish this task by building a web app that predicts the real estate price for properties and houses across the city of Bengaluru, India. It has been a huge project and has taken a while. I shall make sure to walk you through every step that I have followed."
},
{
"code": null,
"e": 668,
"s": 636,
"text": "The project mainly has 4 steps:"
},
{
"code": null,
"e": 681,
"s": 668,
"text": "Data Science"
},
{
"code": null,
"e": 698,
"s": 681,
"text": "Machine Learning"
},
{
"code": null,
"e": 706,
"s": 698,
"text": "Backend"
},
{
"code": null,
"e": 715,
"s": 706,
"text": "Frontend"
},
{
"code": null,
"e": 949,
"s": 715,
"text": "The first step is typical data science work where we take a data set from Kaggle called βBengaluru House price dataβ .We will perform some extensive data cleaning work on it to ensure that it gives accurate results during prediction."
},
{
"code": null,
"e": 1382,
"s": 949,
"text": "This jupyter notebook entitled βRealEstatePricePredictor.ipynbβ is where we perform all the data science related work. As the jupyter notebook is self-explanatory I shall briefly touch upon the concepts that I have implemented. Our dataset requires a lot of work in terms of data cleaning. In fact, 70% of the notebook is all about data cleaning where we drop empty rows and remove unnecessary columns that wonβt help in prediction."
},
{
"code": null,
"e": 1561,
"s": 1382,
"text": "Next step, Feature Engineering which is the process of extracting useful and important information from the dataset that will contribute the most towards a successful prediction."
},
{
"code": null,
"e": 1788,
"s": 1561,
"text": "The final step is handling outliers. Outliers are anomalies that cause an enormous amount of damage to data and prediction. There is a lot of things to understand from the dataset logically to detect and remove these outliers."
},
{
"code": null,
"e": 1853,
"s": 1788,
"text": "Again, all of these have been explained in the jupyter notebook."
},
{
"code": null,
"e": 1975,
"s": 1853,
"text": "In the end, the original dataset which had almost 13000 rows and 9 columns are reduced to almost 7000 rows and 5 columns."
},
{
"code": null,
"e": 2204,
"s": 1975,
"text": "The final data obtained is subjected to a machine learning model. We will mainly use K-fold Cross Validation and GridSearchCV technique to perform hyper parameter tuning to obtain the best algorithm and parameters for the model."
},
{
"code": null,
"e": 2315,
"s": 2204,
"text": "Turns out linear regression model gives the best results for our data with a score above 80% which is not bad."
},
{
"code": null,
"e": 2583,
"s": 2315,
"text": "Now, our model needs to be exported into a pickle file (Bengaluru_House_Data.pickle) which converts python objects into a character stream. Also, we need to export the locations(columns) into a json(columns.json) file to be able to interact with it from the frontend."
},
{
"code": null,
"e": 2705,
"s": 2583,
"text": "We will use a Flask server as our backend to host the application locally. In the server folder we will set up two files:"
},
{
"code": null,
"e": 2715,
"s": 2705,
"text": "server.py"
},
{
"code": null,
"e": 2963,
"s": 2715,
"text": "The server.py file will be responsible for handling the routes for fetching the location names and predicting the house price. It also gets the form data from the front end and feeds it to the util.py. These routes can be tested using Postman app."
},
{
"code": null,
"e": 2971,
"s": 2963,
"text": "util.py"
},
{
"code": null,
"e": 3192,
"s": 2971,
"text": "The util.py file is the main brains behind the back end. It has a function to load the JSON and pickle file. This file takes the form data from server.py and uses the model to predict the estimated price of the property."
},
{
"code": null,
"e": 3680,
"s": 3192,
"text": "The front end is made up of simple HTML, CSS and JavaScript. The user can select the number of square feet area, BHK, bathrooms and location in the form and hit on βESTIMATEβ button to get the estimated price. The JavaScript file is responsible for interacting with both the backend flask server routes and the frontend HTML. It gets the form data filled by the user and calls the function that uses the prediction model and renders the estimated price in lakhs rupees (1 lakh = 100000)."
},
{
"code": null,
"e": 3994,
"s": 3680,
"text": "Let's see how our project works. Run the server.py file in the backend and open up the HTML web page we created. Input the area of the property in square feet, the number of BHK, the number of bathrooms and the location and hit βESTIMATEβ. π²Yay! We predicted the price of what could be the dream house of someone."
},
{
"code": null,
"e": 4065,
"s": 3994,
"text": "This part is quite tricky so make sure to do every step along with me."
},
{
"code": null,
"e": 4182,
"s": 4065,
"text": "As of now, the project is only local, we will learn how to deploy the application to the web using AWS EC2 instance."
},
{
"code": null,
"e": 4303,
"s": 4182,
"text": "We will use nginx which is a web server that can serve HTTP requests. The nginx can then interact with our Flask Server."
},
{
"code": null,
"e": 4344,
"s": 4303,
"text": "Download nginx from here and install it."
},
{
"code": null,
"e": 4433,
"s": 4344,
"text": "STEP 1: To make the estimation, in the script.js file, initially we had these two lines:"
},
{
"code": null,
"e": 4540,
"s": 4433,
"text": "var url = \"http://127.0.0.1:5000/predict_home_price\";var url = \"http://127.0.0.1:5000/get_location_names\";"
},
{
"code": null,
"e": 4642,
"s": 4540,
"text": "These two were just for the sake of running our app locally, now we must change these two lines into:"
},
{
"code": null,
"e": 4715,
"s": 4642,
"text": "var url = \"/api/predict_home_price\";var url = \"/api/get_location_names\";"
},
{
"code": null,
"e": 4831,
"s": 4715,
"text": "We need to configure the reverse proxy on nginx server so that all requests to β/apiβ are routed to port 5000 only."
},
{
"code": null,
"e": 5090,
"s": 4831,
"text": "STEP 2: Log in to your AWS console. You will need to know how to launch an AWS EC2 instance free-of-cost. While following the steps to launch your instance under step 6 make sure to add HTTP and HTTPS request type to make sure people can access your website."
},
{
"code": null,
"e": 5182,
"s": 5090,
"text": "STEP 3: Create new key pair, enter a name, download key(.pem file) and launch EC2 Instance."
},
{
"code": null,
"e": 5292,
"s": 5182,
"text": "STEP 4: Click on the βConnectβ option beside βLaunch Instanceβ where there will be a command under βExampleβ."
},
{
"code": null,
"e": 5346,
"s": 5292,
"text": "Copy this command. It would look something like this."
},
{
"code": null,
"e": 5472,
"s": 5346,
"text": "STEP 5: Open up bash shell and paste this command but replace the blacked out area with the path to your downloaded pem file."
},
{
"code": null,
"e": 5529,
"s": 5472,
"text": "You are now connected to the Linux machine on AWS cloud."
},
{
"code": null,
"e": 5639,
"s": 5529,
"text": "STEP 6: Now you need to copy your project onto that virtual machine using WinSCP. Download and launch WinSCP."
},
{
"code": null,
"e": 5753,
"s": 5639,
"text": "STEP 7: On your AWS if we click on βConnectβ again there is a command above βExampleβ, that looks something like:"
},
{
"code": null,
"e": 5838,
"s": 5753,
"text": "Copy this to your WinSCP host name as this is the host name of your virtual machine."
},
{
"code": null,
"e": 6003,
"s": 5838,
"text": "STEP 7: Username is βubuntuβ. Before entering the password, we need to convert the .pem file into .ppk file using PuTTYgen. Please download PuTTYgen from this link."
},
{
"code": null,
"e": 6191,
"s": 6003,
"text": "Click on the βAdvancedβ button under the Password field. Select the downloaded .pem file, itβll open up PuTTYgen to convert the .pem file to .ppk file. Select the new .ppk and click βOKβ."
},
{
"code": null,
"e": 6204,
"s": 6191,
"text": "Hit βLoginβ."
},
{
"code": null,
"e": 6306,
"s": 6204,
"text": "Copy your whole root project folder(RealEstatePricePrediction) from your machine to the cloud server."
},
{
"code": null,
"e": 6372,
"s": 6306,
"text": "On the ubuntu shell of the server execute the following commands:"
},
{
"code": null,
"e": 6418,
"s": 6372,
"text": "sudo apt-get updatesudo apt-get install nginx"
},
{
"code": null,
"e": 6509,
"s": 6418,
"text": "Copy-paste the hostname in the βConnectβ dialog box which we saw earlier into the browser."
},
{
"code": null,
"e": 6555,
"s": 6509,
"text": "You should see the homepage of nginx running."
},
{
"code": null,
"e": 6595,
"s": 6555,
"text": "STEP 8: Execute the following commands:"
},
{
"code": null,
"e": 6703,
"s": 6595,
"text": "cd /etc/nginx/sites-enabled/sudo unlink defaultcd ../sites-available/sudo vim BengaluruHousePrediction.conf"
},
{
"code": null,
"e": 6785,
"s": 6703,
"text": "Copy-paste the following code in the .conf file. This is the reverse proxy setup."
},
{
"code": null,
"e": 7054,
"s": 6785,
"text": "server { listen 80; server_name BegaluruHousePrediction; root /home/ubuntu/RealEstatePricePrediction/client; index index.html; location /api/ { rewrite ^/api(.*) $1 break; proxy_pass http://127.0.0.1:5000; }}"
},
{
"code": null,
"e": 7108,
"s": 7054,
"text": "Exit from the vim and execute the following commands:"
},
{
"code": null,
"e": 7226,
"s": 7108,
"text": "cd ../sites-enabled/ln -v -s /etc/nginx/sites-available/BengaluruHousePrediction.conf inside /etc/nginx/sites-enabled"
},
{
"code": null,
"e": 7298,
"s": 7226,
"text": "What we are doing in the above command is establishing a symbolic link."
},
{
"code": null,
"e": 7324,
"s": 7298,
"text": "Restart the server using:"
},
{
"code": null,
"e": 7351,
"s": 7324,
"text": "sudo service nginx restart"
},
{
"code": null,
"e": 7371,
"s": 7351,
"text": "Check status using:"
},
{
"code": null,
"e": 7397,
"s": 7371,
"text": "sudo service nginx status"
},
{
"code": null,
"e": 7540,
"s": 7397,
"text": "Go to your browser and enter the hostname link in the url. You should see your application frontend loading, yet the backend doesnβt work yet."
},
{
"code": null,
"e": 7582,
"s": 7540,
"text": "STEP 9: Go back to the terminal and type:"
},
{
"code": null,
"e": 7723,
"s": 7582,
"text": "cd ~cd RealEstatePricePrediction/server/sudo apt-get python3-pipsudo pip3 install Flasksudo pip3 install scikit-learnsudo pip3 install numpy"
},
{
"code": null,
"e": 7751,
"s": 7723,
"text": "Start backend server using:"
},
{
"code": null,
"e": 7769,
"s": 7751,
"text": " python server.py"
},
{
"code": null,
"e": 7854,
"s": 7769,
"text": "Your application is now live on the internet accessible from any place in the world."
},
{
"code": null,
"e": 8031,
"s": 7854,
"text": "I understand if the deployment phase was a little tough. You can contact me on my LinkedIn if you run into any errors. Feel free to check out the entire code-base on my GitHub."
}
] |
Chocolate Distribution Problem | Practice | GeeksforGeeks
|
Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that :
1. Each student gets exactly one packet.
2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum.
Example 1:
Input:
N = 8, M = 5
A = {3, 4, 1, 9, 56, 7, 9, 12}
Output: 6
Explanation: The minimum difference between
maximum chocolates and minimum chocolates
is 9 - 3 = 6 by choosing following M packets :
{3, 4, 9, 7, 9}.
Example 2:
Input:
N = 7, M = 3
A = {7, 3, 2, 4, 9, 12, 56}
Output: 2
Explanation: The minimum difference between
maximum chocolates and minimum chocolates
is 4 - 2 = 2 by choosing following M packets :
{3, 2, 4}.
Your Task:
You don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student.
Expected Time Complexity: O(N*Log(N))
Expected Auxiliary Space: O(1)
Constraints:
1 β€ T β€ 100
1 β€ N β€ 105
1 β€ Ai β€ 109
1 β€ M β€ N
0
milindprajapatmst194 days ago
# define ll long long
class Solution {
public:
ll findMinDiff(vector<ll> arr, int n, int m) {
sort(arr.begin(), arr.end());
m--;
ll result = LLONG_MAX;
for (ll i = m; i < n; i++)
result = min(result, arr[i] - arr[i - m]);
return result;
}
};
0
parikshitgaikwad1721 week ago
long long findMinDiff(vector<long long> a, long long n, long long m){
//code
sort(a.begin(),a.end());
long long int diff=INT_MAX;
for(int i=0;i<n;i++){
if(i+m-1>=n){
break;
}
long long int sum=(a[i+m-1]-a[i]);
diff= min(diff,sum);
}
return diff;
}
0
6780apoorvyadav1 week ago
long long findMinDiff(vector<long long> a, long long n, long long m){
//code
sort(a.begin(), a.end());
long long mini = LONG_MAX;
for(long long i=0;i+m-1<n;i++){
long long d = a[i+m-1] - a[i];
mini = min(mini, d);
}
return mini;
}
0
sourabhkush991 week ago
long long findMinDiff(vector<long long> a, long long n, long long m){
sort(a.begin(),a.end()); long long diff = INT_MAX; for(int i=0; (i+m-1)<=n-1; i++){ if(a[i+m-1]-a[i] < diff){ diff = a[i+m-1]-a[i]; } } return diff; }
0
bhavinraichura281 week ago
long long findMinDiff(vector<long long> a, long long n, long long m){ //code long long min_count=INT_MAX; sort(a.begin(),a.end()); if (m==1){ return 0; } if(n==m){ return a[n-1]-a[0]; } int j =m-1; for (int i =0;i<=(n-m);i++){ min_count=min(min_count, a[j]-a[i]); j++; } return min_count; }
0
sachinupreti1901 week ago
vector<int>vec; unordered_map<int,int>m3; for(i=0;i<v.size();i++) { m3[v[i]]++; } for(i=0;i<v.size();i++) { if(m3[v[i]]!=-1) { vec.push_back(v[i]); m3[v[i]]=-1; } } return vec;
0
badgujarsachin832 weeks ago
long long findMinDiff(vector<long long> a, long long n, long long m){
//code
sort(a.begin(),a.end());
int i=0,j=m-1;
long long di=a[n-1];
while(j<n){
di=min(di,a[j]-a[i]);
i++;j++;
}
return di;
}
0
nagasivakrishnav2 weeks ago
Python code - Easy short 0.92s:
def findMinDiff(self, A,N,M):
# code here ans = [] A.sort() for idx in range(N-M+1): # 1 3 4 7 9 9 12 56 # 0 1 2 3 4 5 6 7 ans.append(A[idx+M-1]-A[idx]) return min(ans)
0
1712himanshukumar2 weeks ago
class Solution{ public long findMinDiff (ArrayList<Long> a, long n, long m) { Collections.sort(a); long diff=Long.MAX_VALUE; long i=0; long j=0; long ans=Long.MAX_VALUE; while(j<n && i<n){ if(j-i+1<m){ j++; } else if(j-i+1==m){ diff=Math.min(diff,a.get((int)j)-a.get((int)i)); // line a i++; j++; } ans=Math.min(diff,ans); } return ans; }}
Tc=o(nlogn)
Sc=o(1)
if we cannot change long to int , this cause loosy long int error,
so see in code line a where i convert index long to int.
0
itsmeshahid2 weeks ago
SIMPLE O(nlogn) Solution :
long long findMinDiff(vector<long long> a, long long n, long long m){ sort(a.begin(), a.end()); int i=0; int j=m-1; long long diff=a[n-1];//storing maximum value for comparison. while(j<n){ diff=min(diff, a[j]-a[i]); //compare and store only minimum value. i++; j++; } return diff;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 684,
"s": 238,
"text": "Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that :\n1. Each student gets exactly one packet.\n2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum."
},
{
"code": null,
"e": 695,
"s": 684,
"text": "Example 1:"
},
{
"code": null,
"e": 909,
"s": 695,
"text": "Input:\nN = 8, M = 5\nA = {3, 4, 1, 9, 56, 7, 9, 12}\nOutput: 6\nExplanation: The minimum difference between \nmaximum chocolates and minimum chocolates \nis 9 - 3 = 6 by choosing following M packets :\n{3, 4, 9, 7, 9}.\n"
},
{
"code": null,
"e": 920,
"s": 909,
"text": "Example 2:"
},
{
"code": null,
"e": 1122,
"s": 920,
"text": "Input:\nN = 7, M = 3\nA = {7, 3, 2, 4, 9, 12, 56}\nOutput: 2\nExplanation: The minimum difference between\nmaximum chocolates and minimum chocolates\nis 4 - 2 = 2 by choosing following M packets :\n{3, 2, 4}."
},
{
"code": null,
"e": 1442,
"s": 1122,
"text": "Your Task:\nYou don't need to take any input or print anything. Your task is to complete the function findMinDiff() which takes array A[ ], N and M as input parameters and returns the minimum possible difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student."
},
{
"code": null,
"e": 1511,
"s": 1442,
"text": "Expected Time Complexity: O(N*Log(N))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1571,
"s": 1511,
"text": "Constraints:\n1 β€ T β€ 100\n1 β€ N β€ 105\n1 β€ Ai β€ 109\n1 β€ M β€ N"
},
{
"code": null,
"e": 1573,
"s": 1571,
"text": "0"
},
{
"code": null,
"e": 1603,
"s": 1573,
"text": "milindprajapatmst194 days ago"
},
{
"code": null,
"e": 1912,
"s": 1603,
"text": "# define ll long long\nclass Solution {\n public:\n ll findMinDiff(vector<ll> arr, int n, int m) {\n sort(arr.begin(), arr.end());\n m--;\n ll result = LLONG_MAX;\n for (ll i = m; i < n; i++)\n result = min(result, arr[i] - arr[i - m]);\n return result;\n } \n};"
},
{
"code": null,
"e": 1914,
"s": 1912,
"text": "0"
},
{
"code": null,
"e": 1944,
"s": 1914,
"text": "parikshitgaikwad1721 week ago"
},
{
"code": null,
"e": 2318,
"s": 1944,
"text": "long long findMinDiff(vector<long long> a, long long n, long long m){\n //code\n sort(a.begin(),a.end());\n long long int diff=INT_MAX;\n for(int i=0;i<n;i++){\n if(i+m-1>=n){\n break;\n }\n long long int sum=(a[i+m-1]-a[i]);\n diff= min(diff,sum);\n \n }\n return diff;\n } "
},
{
"code": null,
"e": 2320,
"s": 2318,
"text": "0"
},
{
"code": null,
"e": 2346,
"s": 2320,
"text": "6780apoorvyadav1 week ago"
},
{
"code": null,
"e": 2652,
"s": 2346,
"text": "long long findMinDiff(vector<long long> a, long long n, long long m){\n //code\n sort(a.begin(), a.end());\n long long mini = LONG_MAX;\n for(long long i=0;i+m-1<n;i++){\n long long d = a[i+m-1] - a[i];\n mini = min(mini, d);\n }\n return mini;\n } "
},
{
"code": null,
"e": 2654,
"s": 2652,
"text": "0"
},
{
"code": null,
"e": 2678,
"s": 2654,
"text": "sourabhkush991 week ago"
},
{
"code": null,
"e": 2752,
"s": 2678,
"text": " long long findMinDiff(vector<long long> a, long long n, long long m){"
},
{
"code": null,
"e": 2970,
"s": 2752,
"text": " sort(a.begin(),a.end()); long long diff = INT_MAX; for(int i=0; (i+m-1)<=n-1; i++){ if(a[i+m-1]-a[i] < diff){ diff = a[i+m-1]-a[i]; } } return diff; } "
},
{
"code": null,
"e": 2972,
"s": 2970,
"text": "0"
},
{
"code": null,
"e": 2999,
"s": 2972,
"text": "bhavinraichura281 week ago"
},
{
"code": null,
"e": 3405,
"s": 2999,
"text": "long long findMinDiff(vector<long long> a, long long n, long long m){ //code long long min_count=INT_MAX; sort(a.begin(),a.end()); if (m==1){ return 0; } if(n==m){ return a[n-1]-a[0]; } int j =m-1; for (int i =0;i<=(n-m);i++){ min_count=min(min_count, a[j]-a[i]); j++; } return min_count; }"
},
{
"code": null,
"e": 3407,
"s": 3405,
"text": "0"
},
{
"code": null,
"e": 3433,
"s": 3407,
"text": "sachinupreti1901 week ago"
},
{
"code": null,
"e": 3739,
"s": 3433,
"text": " vector<int>vec; unordered_map<int,int>m3; for(i=0;i<v.size();i++) { m3[v[i]]++; } for(i=0;i<v.size();i++) { if(m3[v[i]]!=-1) { vec.push_back(v[i]); m3[v[i]]=-1; } } return vec;"
},
{
"code": null,
"e": 3741,
"s": 3739,
"text": "0"
},
{
"code": null,
"e": 3769,
"s": 3741,
"text": "badgujarsachin832 weeks ago"
},
{
"code": null,
"e": 4017,
"s": 3769,
"text": " long long findMinDiff(vector<long long> a, long long n, long long m){\n //code\n sort(a.begin(),a.end());\n int i=0,j=m-1;\n long long di=a[n-1];\n while(j<n){\n di=min(di,a[j]-a[i]);\n i++;j++;\n }\n return di;\n } "
},
{
"code": null,
"e": 4019,
"s": 4017,
"text": "0"
},
{
"code": null,
"e": 4047,
"s": 4019,
"text": "nagasivakrishnav2 weeks ago"
},
{
"code": null,
"e": 4079,
"s": 4047,
"text": "Python code - Easy short 0.92s:"
},
{
"code": null,
"e": 4111,
"s": 4081,
"text": "def findMinDiff(self, A,N,M):"
},
{
"code": null,
"e": 4312,
"s": 4111,
"text": " # code here ans = [] A.sort() for idx in range(N-M+1): # 1 3 4 7 9 9 12 56 # 0 1 2 3 4 5 6 7 ans.append(A[idx+M-1]-A[idx]) return min(ans)"
},
{
"code": null,
"e": 4314,
"s": 4312,
"text": "0"
},
{
"code": null,
"e": 4343,
"s": 4314,
"text": "1712himanshukumar2 weeks ago"
},
{
"code": null,
"e": 4846,
"s": 4343,
"text": "class Solution{ public long findMinDiff (ArrayList<Long> a, long n, long m) { Collections.sort(a); long diff=Long.MAX_VALUE; long i=0; long j=0; long ans=Long.MAX_VALUE; while(j<n && i<n){ if(j-i+1<m){ j++; } else if(j-i+1==m){ diff=Math.min(diff,a.get((int)j)-a.get((int)i)); // line a i++; j++; } ans=Math.min(diff,ans); } return ans; }}"
},
{
"code": null,
"e": 4858,
"s": 4846,
"text": "Tc=o(nlogn)"
},
{
"code": null,
"e": 4866,
"s": 4858,
"text": "Sc=o(1)"
},
{
"code": null,
"e": 4934,
"s": 4866,
"text": "if we cannot change long to int , this cause loosy long int error,"
},
{
"code": null,
"e": 4993,
"s": 4934,
"text": "so see in code line a where i convert index long to int."
},
{
"code": null,
"e": 4995,
"s": 4993,
"text": "0"
},
{
"code": null,
"e": 5018,
"s": 4995,
"text": "itsmeshahid2 weeks ago"
},
{
"code": null,
"e": 5045,
"s": 5018,
"text": "SIMPLE O(nlogn) Solution :"
},
{
"code": null,
"e": 5403,
"s": 5045,
"text": "long long findMinDiff(vector<long long> a, long long n, long long m){ sort(a.begin(), a.end()); int i=0; int j=m-1; long long diff=a[n-1];//storing maximum value for comparison. while(j<n){ diff=min(diff, a[j]-a[i]); //compare and store only minimum value. i++; j++; } return diff;"
},
{
"code": null,
"e": 5411,
"s": 5403,
"text": " } "
},
{
"code": null,
"e": 5557,
"s": 5411,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5593,
"s": 5557,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5603,
"s": 5593,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5613,
"s": 5603,
"text": "\nContest\n"
},
{
"code": null,
"e": 5676,
"s": 5613,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5824,
"s": 5676,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6032,
"s": 5824,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6138,
"s": 6032,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Auto Search StackOverflow for Errors in Code using Python - GeeksforGeeks
|
09 Dec, 2021
Ever faced great difficulty in copying the error youβre stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Worry Not, Hereβs the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related to our error that were previously been answered also.
The subprocess module is used to run new applications or programs through Python code by creating new processes. The subprocess module was created with the intention of replacing several methods available in the os module, which were not considered to be very efficient.
The requests module allows you to send HTTP requests using Python.
The webbrowser module allows us to launch the web browser.
Approach: We will divide the script into three parts, i.e. we will create three functions as follows:
execute_return(cmd): On the first function, we are going to write code to read and run python file, and store its output or error.mak_req(error): This function will make an HTTP request using Stack Overflow API and the error we get from the 1st function and finally returns the JSON file.get_urls(json_dict): This function takes the JSON from the 2nd function, and fetches and stores the URLs of those solutions which are marked as βansweredβ by StackOverflow. And then finally open up the tabs containing answers from StackOverflow on the browser.
execute_return(cmd): On the first function, we are going to write code to read and run python file, and store its output or error.
mak_req(error): This function will make an HTTP request using Stack Overflow API and the error we get from the 1st function and finally returns the JSON file.
get_urls(json_dict): This function takes the JSON from the 2nd function, and fetches and stores the URLs of those solutions which are marked as βansweredβ by StackOverflow. And then finally open up the tabs containing answers from StackOverflow on the browser.
Note: One more thing, before we jump into the code, you should be clear with the concept of the strip and split function.
Python3
# Import dependenciesfrom subprocess import Popen, PIPEimport requestsimport webbrowser # We are going to write code to read and run python# file, and store its output or error.def execute_return(cmd): args = cmd.split() proc = Popen(args, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() return out, err # This function will make an HTTP request using StackOverflow# API and the error we get from the 1st function and finally# returns the JSON file.def mak_req(error): resp = requests.get("https://api.stackexchange.com/" + "/2.2/search?order=desc&tagged=python&sort=activity&intitle={}&site=stackoverflow".format(error)) return resp.json() # This function takes the JSON from the 2nd function, and# fetches and stores the URLs of those solutions which are# marked as "answered" by StackOverflow. And then finally# open up the tabs containing answers from StackOverflow on# the browser.def get_urls(json_dict): url_list = [] count = 0 for i in json_dict['items']: if i['is_answered']: url_list.append(i["link"]) count += 1 if count == 3 or count == len(i): break for i in url_list: webbrowser.open(i) # Below line will go through the provided python file# And stores the output and error.out, err = execute_return("python C:/Users/Saurabh/Desktop/test.py") # This line is used to store that part of error we are interested in.error = err.decode("utf-8").strip().split("\r\n")[-1]print(error) # A simple if condition, if error is found then execute 2nd and# 3rd function, otherwise print "No error".if error: filter_error = error.split(":") json1 = mak_req(filter_error[0]) json2 = mak_req(filter_error[1]) json = mak_req(error) get_urls(json1) get_urls(json2) get_urls(json) else: print("No error")
Output:
Media error: Format(s) not supported or source(s) not found
sweetyty
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 24616,
"s": 24212,
"text": "Ever faced great difficulty in copying the error youβre stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Worry Not, Hereβs the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related to our error that were previously been answered also."
},
{
"code": null,
"e": 24887,
"s": 24616,
"text": "The subprocess module is used to run new applications or programs through Python code by creating new processes. The subprocess module was created with the intention of replacing several methods available in the os module, which were not considered to be very efficient."
},
{
"code": null,
"e": 24954,
"s": 24887,
"text": "The requests module allows you to send HTTP requests using Python."
},
{
"code": null,
"e": 25013,
"s": 24954,
"text": "The webbrowser module allows us to launch the web browser."
},
{
"code": null,
"e": 25116,
"s": 25013,
"text": "Approach: We will divide the script into three parts, i.e. we will create three functions as follows: "
},
{
"code": null,
"e": 25665,
"s": 25116,
"text": "execute_return(cmd): On the first function, we are going to write code to read and run python file, and store its output or error.mak_req(error): This function will make an HTTP request using Stack Overflow API and the error we get from the 1st function and finally returns the JSON file.get_urls(json_dict): This function takes the JSON from the 2nd function, and fetches and stores the URLs of those solutions which are marked as βansweredβ by StackOverflow. And then finally open up the tabs containing answers from StackOverflow on the browser."
},
{
"code": null,
"e": 25796,
"s": 25665,
"text": "execute_return(cmd): On the first function, we are going to write code to read and run python file, and store its output or error."
},
{
"code": null,
"e": 25955,
"s": 25796,
"text": "mak_req(error): This function will make an HTTP request using Stack Overflow API and the error we get from the 1st function and finally returns the JSON file."
},
{
"code": null,
"e": 26216,
"s": 25955,
"text": "get_urls(json_dict): This function takes the JSON from the 2nd function, and fetches and stores the URLs of those solutions which are marked as βansweredβ by StackOverflow. And then finally open up the tabs containing answers from StackOverflow on the browser."
},
{
"code": null,
"e": 26338,
"s": 26216,
"text": "Note: One more thing, before we jump into the code, you should be clear with the concept of the strip and split function."
},
{
"code": null,
"e": 26346,
"s": 26338,
"text": "Python3"
},
{
"code": "# Import dependenciesfrom subprocess import Popen, PIPEimport requestsimport webbrowser # We are going to write code to read and run python# file, and store its output or error.def execute_return(cmd): args = cmd.split() proc = Popen(args, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() return out, err # This function will make an HTTP request using StackOverflow# API and the error we get from the 1st function and finally# returns the JSON file.def mak_req(error): resp = requests.get(\"https://api.stackexchange.com/\" + \"/2.2/search?order=desc&tagged=python&sort=activity&intitle={}&site=stackoverflow\".format(error)) return resp.json() # This function takes the JSON from the 2nd function, and# fetches and stores the URLs of those solutions which are# marked as \"answered\" by StackOverflow. And then finally# open up the tabs containing answers from StackOverflow on# the browser.def get_urls(json_dict): url_list = [] count = 0 for i in json_dict['items']: if i['is_answered']: url_list.append(i[\"link\"]) count += 1 if count == 3 or count == len(i): break for i in url_list: webbrowser.open(i) # Below line will go through the provided python file# And stores the output and error.out, err = execute_return(\"python C:/Users/Saurabh/Desktop/test.py\") # This line is used to store that part of error we are interested in.error = err.decode(\"utf-8\").strip().split(\"\\r\\n\")[-1]print(error) # A simple if condition, if error is found then execute 2nd and# 3rd function, otherwise print \"No error\".if error: filter_error = error.split(\":\") json1 = mak_req(filter_error[0]) json2 = mak_req(filter_error[1]) json = mak_req(error) get_urls(json1) get_urls(json2) get_urls(json) else: print(\"No error\")",
"e": 28196,
"s": 26346,
"text": null
},
{
"code": null,
"e": 28204,
"s": 28196,
"text": "Output:"
},
{
"code": null,
"e": 28264,
"s": 28204,
"text": "Media error: Format(s) not supported or source(s) not found"
},
{
"code": null,
"e": 28273,
"s": 28264,
"text": "sweetyty"
},
{
"code": null,
"e": 28289,
"s": 28273,
"text": "Python-requests"
},
{
"code": null,
"e": 28304,
"s": 28289,
"text": "python-utility"
},
{
"code": null,
"e": 28311,
"s": 28304,
"text": "Python"
},
{
"code": null,
"e": 28409,
"s": 28311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28418,
"s": 28409,
"text": "Comments"
},
{
"code": null,
"e": 28431,
"s": 28418,
"text": "Old Comments"
},
{
"code": null,
"e": 28463,
"s": 28431,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28519,
"s": 28463,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28540,
"s": 28519,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 28579,
"s": 28540,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28621,
"s": 28579,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28648,
"s": 28621,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28679,
"s": 28648,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28721,
"s": 28679,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28757,
"s": 28721,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Advanced JavaScript Backend Basics
|
JavaScript programming language that is usually used for web scripting. It is a lightweight, interpreted programming language. JavaScript is one of the most programming languages for web development. For running JavaScript
each browser has its own engine which enables the proper functioning of JavaScript in the browser. Some common Browsers and their JavaScript engines are β
Spider Monkey for firefox
V8 for Google Chrome
JavaScript code for Safari
Chakra for Microsoft Internet Explorer/ edge
To make JavaScript universe and stop a browser from describing their own scripts. There is a standard set for JavaScript which will be used throughout the browser. there is an Association named ECMA ( European computer manufacturers Association) which sets standards for JavaScript.
For proper running of JavaScript code, the JavaScript engine works in two different phases to make sure the script created work properly irrespective of the browser.
Creation phase β In the creation phase, the JavaScript engine well goes through the entire code and check the syntax of the program and throw a synthetic error if it occurs. the engine will declare and provide some memory chunks to variables as well as to the functions that are declared in the JavaScript code.
Creation phase β In the creation phase, the JavaScript engine well goes through the entire code and check the syntax of the program and throw a synthetic error if it occurs. the engine will declare and provide some memory chunks to variables as well as to the functions that are declared in the JavaScript code.
Execution phase β in the execution phase, the engine will run the code. Also, the variables are declared and throw any other error that may occur.
Execution phase β in the execution phase, the engine will run the code. Also, the variables are declared and throw any other error that may occur.
In JavaScript, there are two types of equality operators.
== operator is used to test for checking abstract equality of two values. This means in this comparison the equality of values is checked, the type of data is not checked for equality.
=== operator is used to check for strict equality of two values. This means in this comparison both types and equality of the data are checked.
<script>
document.write(34 == "34");
document.write('<br>')
document.write(98 === "98");
</script>
true
false
Boolean variables are those variables in programming languages that have only two types of values. The valid boolean values in Javascript programming language are TRUE and FALSE.
The TRUE value in programming corresponds to the values other than 0, which triggers the conditional statements in Javascript.
Some values that convert back to TRUE boolean value are β
{} - empty object
[] - empty array
!False values are TRUE
FALSE values in programming correspond to 0 values, that does not ignore conditional statements in Javascript.
Some values that convert back to FALSE boolean value are β
0 - numerical value of FALSE
undefined - value that is undefined is false
null - null value is always false
|
[
{
"code": null,
"e": 1440,
"s": 1062,
"text": "JavaScript programming language that is usually used for web scripting. It is a lightweight, interpreted programming language. JavaScript is one of the most programming languages for web development. For running JavaScript\neach browser has its own engine which enables the proper functioning of JavaScript in the browser. Some common Browsers and their JavaScript engines are β"
},
{
"code": null,
"e": 1466,
"s": 1440,
"text": "Spider Monkey for firefox"
},
{
"code": null,
"e": 1487,
"s": 1466,
"text": "V8 for Google Chrome"
},
{
"code": null,
"e": 1514,
"s": 1487,
"text": "JavaScript code for Safari"
},
{
"code": null,
"e": 1559,
"s": 1514,
"text": "Chakra for Microsoft Internet Explorer/ edge"
},
{
"code": null,
"e": 1842,
"s": 1559,
"text": "To make JavaScript universe and stop a browser from describing their own scripts. There is a standard set for JavaScript which will be used throughout the browser. there is an Association named ECMA ( European computer manufacturers Association) which sets standards for JavaScript."
},
{
"code": null,
"e": 2008,
"s": 1842,
"text": "For proper running of JavaScript code, the JavaScript engine works in two different phases to make sure the script created work properly irrespective of the browser."
},
{
"code": null,
"e": 2320,
"s": 2008,
"text": "Creation phase β In the creation phase, the JavaScript engine well goes through the entire code and check the syntax of the program and throw a synthetic error if it occurs. the engine will declare and provide some memory chunks to variables as well as to the functions that are declared in the JavaScript code."
},
{
"code": null,
"e": 2632,
"s": 2320,
"text": "Creation phase β In the creation phase, the JavaScript engine well goes through the entire code and check the syntax of the program and throw a synthetic error if it occurs. the engine will declare and provide some memory chunks to variables as well as to the functions that are declared in the JavaScript code."
},
{
"code": null,
"e": 2779,
"s": 2632,
"text": "Execution phase β in the execution phase, the engine will run the code. Also, the variables are declared and throw any other error that may occur."
},
{
"code": null,
"e": 2926,
"s": 2779,
"text": "Execution phase β in the execution phase, the engine will run the code. Also, the variables are declared and throw any other error that may occur."
},
{
"code": null,
"e": 2984,
"s": 2926,
"text": "In JavaScript, there are two types of equality operators."
},
{
"code": null,
"e": 3169,
"s": 2984,
"text": "== operator is used to test for checking abstract equality of two values. This means in this comparison the equality of values is checked, the type of data is not checked for equality."
},
{
"code": null,
"e": 3313,
"s": 3169,
"text": "=== operator is used to check for strict equality of two values. This means in this comparison both types and equality of the data are checked."
},
{
"code": null,
"e": 3412,
"s": 3313,
"text": "<script>\ndocument.write(34 == \"34\");\ndocument.write('<br>')\ndocument.write(98 === \"98\");\n</script>"
},
{
"code": null,
"e": 3423,
"s": 3412,
"text": "true\nfalse"
},
{
"code": null,
"e": 3602,
"s": 3423,
"text": "Boolean variables are those variables in programming languages that have only two types of values. The valid boolean values in Javascript programming language are TRUE and FALSE."
},
{
"code": null,
"e": 3729,
"s": 3602,
"text": "The TRUE value in programming corresponds to the values other than 0, which triggers the conditional statements in Javascript."
},
{
"code": null,
"e": 3787,
"s": 3729,
"text": "Some values that convert back to TRUE boolean value are β"
},
{
"code": null,
"e": 3805,
"s": 3787,
"text": "{} - empty object"
},
{
"code": null,
"e": 3822,
"s": 3805,
"text": "[] - empty array"
},
{
"code": null,
"e": 3845,
"s": 3822,
"text": "!False values are TRUE"
},
{
"code": null,
"e": 3956,
"s": 3845,
"text": "FALSE values in programming correspond to 0 values, that does not ignore conditional statements in Javascript."
},
{
"code": null,
"e": 4015,
"s": 3956,
"text": "Some values that convert back to FALSE boolean value are β"
},
{
"code": null,
"e": 4044,
"s": 4015,
"text": "0 - numerical value of FALSE"
},
{
"code": null,
"e": 4089,
"s": 4044,
"text": "undefined - value that is undefined is false"
},
{
"code": null,
"e": 4123,
"s": 4089,
"text": "null - null value is always false"
}
] |
Angular7 - Materials/CDK-Drag and Drop
|
The new Drag and Drop feature added to Angular 7 CDK helps to drag and drop the elements from the list. We will understand the working of Drag and Drop Module with the help of an example. The feature is added to cdk. We need to first download the dependency as shown below β
npm install @angular/cdk --save
Once the above step is done. Let us import the drag and drop module in app.module.ts as shown below β
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
import { MyserviceService } from './myservice.service';
import { HttpClientModule } from '@angular/common/http';
import { ScrollDispatchModule } from '@angular/cdk/scrolling';
import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective,
RoutingComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ScrollDispatchModule,
DragDropModule
],
providers: [MyserviceService],
bootstrap: [AppComponent]
})
export class AppModule { }
The DragDropModule is imported from '@angular/cdk/drag-drop' and the module is added to import array as shown above.
We will use details from the api, (http://jsonplaceholder.typicode.com/users) to be displayed on the screen. We have service which will fetch the data from the api as shown below β
myservice.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MyserviceService {
private finaldata = [];
private apiurl = "http://jsonplaceholder.typicode.com/users";
constructor(private http: HttpClient) { }
getData() {
return this.http.get(this.apiurl);
}
}
Once done call the service inside app.component.ts as shown below β
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
public personaldetails = [];
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.myservice.getData().subscribe((data) => {
this.personaldetails = Array.from(Object.keys(data), k=>data[k]);
console.log(this.personaldetails);
});
}
}
We have the required data available in personaldetails variable. Now let us use the same to display to the user as shown below β
<h3>Angular 7 - Drag and Drop Module</h3>
<div>
<div *ngFor="let item of personaldetails; let i = index" class="divlayoutβ>
{{item.name}}
</div >
</div>
We have added class = βdivlayoutβ and the details of the class are in app.component.css.
.divlayout{
width: 40%;
background-color: #ccc;
margin-bottom: 5px;
padding: 10px 10px;
border: 3px solid #73AD21;
}
Following screen will be displayed in the browser β
It will not drag and drop anything, we need to add the dragdrop cdk properties in app.component.html as shown below β
<h3>Angular 7 - Drag and Drop Module</h3>
<div cdkDropList
#personList = "cdkDropList"
[cdkDropListData] = "personaldetails"
[cdkDropListConnectedTo] = "[userlist]"
class = "example-list"
(cdkDropListDropped) = "onDrop($event)" >
<div *ngFor = "let item of personaldetails;
let i = index" class = "divlayout" cdkDrag>
{{item.name}}
</div >
</div&t;
The highlighted ones are all the properties required to perform drag and drop. When you check in the browser, it allows you to drag the item. It will not drop it in the list and will remain as it is when you leave the mouse pointer.
Here it allows to drag the item from the list but once you leave the mouse pointer it will go and settle in the same place. To add the drop feature, we need to add the event onDrop in app.component.ts as shown below β
First we have to import the dragdrap cdk modules as shown below β
import {CdkDragDrop, moveItemInArray, transferArrayItem}
from '@angular/cdk/drag-drop';
Here is the full code in app.component.ts β
import { Component } from '@angular/core';
import { MyserviceService } from './myservice.service';
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7 Project!';
public personaldetails = [];
constructor(private myservice: MyserviceService) {}
ngOnInit() {
this.myservice.getData().subscribe((data) => {
this.personaldetails = Array.from(Object.keys(data),
k=>data[k]);
console.log(this.personaldetails);
});
}
onDrop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data,
event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);
}
}
}
The function onDrop takes care of dropping the item dragged in the position required.
It makes use of the moveItemInArray and transferArrayItem we have imported from cdk dragdrop module.
Now let us see the demo again in the browser β
Now it allows you to drag and drop the item in the position required as shown above. The feature works very smoothly without any flicker issues and can be used in your application wherever the need arises.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2336,
"s": 2061,
"text": "The new Drag and Drop feature added to Angular 7 CDK helps to drag and drop the elements from the list. We will understand the working of Drag and Drop Module with the help of an example. The feature is added to cdk. We need to first download the dependency as shown below β"
},
{
"code": null,
"e": 2369,
"s": 2336,
"text": "npm install @angular/cdk --save\n"
},
{
"code": null,
"e": 2471,
"s": 2369,
"text": "Once the above step is done. Let us import the drag and drop module in app.module.ts as shown below β"
},
{
"code": null,
"e": 3471,
"s": 2471,
"text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule , RoutingComponent} from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\nimport { SqrtPipe } from './app.sqrt';\nimport { MyserviceService } from './myservice.service';\nimport { HttpClientModule } from '@angular/common/http';\nimport { ScrollDispatchModule } from '@angular/cdk/scrolling';\nimport { DragDropModule } from '@angular/cdk/drag-drop';\n\n@NgModule({\n declarations: [\n SqrtPipe,\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective,\n RoutingComponent\n ],\n imports: [\n BrowserModule,\n AppRoutingModule,\n HttpClientModule,\n ScrollDispatchModule,\n DragDropModule\n ],\n providers: [MyserviceService],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }"
},
{
"code": null,
"e": 3588,
"s": 3471,
"text": "The DragDropModule is imported from '@angular/cdk/drag-drop' and the module is added to import array as shown above."
},
{
"code": null,
"e": 3770,
"s": 3588,
"text": "We will use details from the api, (http://jsonplaceholder.typicode.com/users) to be displayed on the screen. We have service which will fetch the data from the api as shown below β"
},
{
"code": null,
"e": 3791,
"s": 3770,
"text": "myservice.service.ts"
},
{
"code": null,
"e": 4158,
"s": 3791,
"text": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class MyserviceService {\n private finaldata = [];\n private apiurl = \"http://jsonplaceholder.typicode.com/users\";\n constructor(private http: HttpClient) { }\n getData() {\n return this.http.get(this.apiurl);\n }\n}"
},
{
"code": null,
"e": 4226,
"s": 4158,
"text": "Once done call the service inside app.component.ts as shown below β"
},
{
"code": null,
"e": 4798,
"s": 4226,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7 Project!';\n public personaldetails = [];\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.myservice.getData().subscribe((data) => {\n this.personaldetails = Array.from(Object.keys(data), k=>data[k]);\n console.log(this.personaldetails);\n });\n }\n}"
},
{
"code": null,
"e": 4927,
"s": 4798,
"text": "We have the required data available in personaldetails variable. Now let us use the same to display to the user as shown below β"
},
{
"code": null,
"e": 5092,
"s": 4927,
"text": "<h3>Angular 7 - Drag and Drop Module</h3>\n<div>\n <div *ngFor=\"let item of personaldetails; let i = index\" class=\"divlayoutβ>\n {{item.name}}\n </div >\n</div>"
},
{
"code": null,
"e": 5181,
"s": 5092,
"text": "We have added class = βdivlayoutβ and the details of the class are in app.component.css."
},
{
"code": null,
"e": 5314,
"s": 5181,
"text": ".divlayout{\n width: 40%;\n background-color: #ccc;\n margin-bottom: 5px;\n padding: 10px 10px;\n border: 3px solid #73AD21;\n}\n"
},
{
"code": null,
"e": 5366,
"s": 5314,
"text": "Following screen will be displayed in the browser β"
},
{
"code": null,
"e": 5484,
"s": 5366,
"text": "It will not drag and drop anything, we need to add the dragdrop cdk properties in app.component.html as shown below β"
},
{
"code": null,
"e": 5871,
"s": 5484,
"text": "<h3>Angular 7 - Drag and Drop Module</h3>\n<div cdkDropList\n #personList = \"cdkDropList\"\n [cdkDropListData] = \"personaldetails\"\n [cdkDropListConnectedTo] = \"[userlist]\"\n class = \"example-list\"\n (cdkDropListDropped) = \"onDrop($event)\" >\n \n <div *ngFor = \"let item of personaldetails; \n let i = index\" class = \"divlayout\" cdkDrag>\n {{item.name}}\n </div >\n</div&t;"
},
{
"code": null,
"e": 6104,
"s": 5871,
"text": "The highlighted ones are all the properties required to perform drag and drop. When you check in the browser, it allows you to drag the item. It will not drop it in the list and will remain as it is when you leave the mouse pointer."
},
{
"code": null,
"e": 6322,
"s": 6104,
"text": "Here it allows to drag the item from the list but once you leave the mouse pointer it will go and settle in the same place. To add the drop feature, we need to add the event onDrop in app.component.ts as shown below β"
},
{
"code": null,
"e": 6388,
"s": 6322,
"text": "First we have to import the dragdrap cdk modules as shown below β"
},
{
"code": null,
"e": 6478,
"s": 6388,
"text": "import {CdkDragDrop, moveItemInArray, transferArrayItem} \nfrom '@angular/cdk/drag-drop';\n"
},
{
"code": null,
"e": 6522,
"s": 6478,
"text": "Here is the full code in app.component.ts β"
},
{
"code": null,
"e": 7569,
"s": 6522,
"text": "import { Component } from '@angular/core';\nimport { MyserviceService } from './myservice.service';\nimport {CdkDragDrop, moveItemInArray, transferArrayItem} from '@angular/cdk/drag-drop';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7 Project!';\n public personaldetails = [];\n constructor(private myservice: MyserviceService) {}\n ngOnInit() {\n this.myservice.getData().subscribe((data) => {\n this.personaldetails = Array.from(Object.keys(data), \n k=>data[k]);\n console.log(this.personaldetails);\n });\n }\n onDrop(event: CdkDragDrop<string[]>) {\n if (event.previousContainer === event.container) {\n moveItemInArray(event.container.data, \n event.previousIndex, event.currentIndex);\n } else {\n transferArrayItem(event.previousContainer.data,\n event.container.data,\n event.previousIndex,\n event.currentIndex);\n }\n }\n}"
},
{
"code": null,
"e": 7655,
"s": 7569,
"text": "The function onDrop takes care of dropping the item dragged in the position required."
},
{
"code": null,
"e": 7756,
"s": 7655,
"text": "It makes use of the moveItemInArray and transferArrayItem we have imported from cdk dragdrop module."
},
{
"code": null,
"e": 7803,
"s": 7756,
"text": "Now let us see the demo again in the browser β"
},
{
"code": null,
"e": 8009,
"s": 7803,
"text": "Now it allows you to drag and drop the item in the position required as shown above. The feature works very smoothly without any flicker issues and can be used in your application wherever the need arises."
},
{
"code": null,
"e": 8044,
"s": 8009,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8058,
"s": 8044,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8093,
"s": 8058,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8107,
"s": 8093,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8142,
"s": 8107,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8162,
"s": 8142,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 8197,
"s": 8162,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8214,
"s": 8197,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8247,
"s": 8214,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8259,
"s": 8247,
"text": " Senol Atac"
},
{
"code": null,
"e": 8294,
"s": 8259,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8306,
"s": 8294,
"text": " Senol Atac"
},
{
"code": null,
"e": 8313,
"s": 8306,
"text": " Print"
},
{
"code": null,
"e": 8324,
"s": 8313,
"text": " Add Notes"
}
] |
hex() function in Python - GeeksforGeeks
|
27 Oct, 2021
hex() function is one of the built-in functions in Python3, which is used to convert an integer number into itβs corresponding hexadecimal form.
Syntax :
hex(x)
Parameters :
x - an integer number (int object)
Returns : Returns hexadecimal string.
Errors and Exceptions :
TypeError : Returns TypeError when anything other than
integer type constants are passed as parameters.
Code #1 : Illustrates use of hex() function.
Python3
# Python3 program to illustrate# hex() function print("The hexadecimal form of 23 is " + hex(23)) print("The hexadecimal form of the " "ascii value is 'a' is " + hex(ord('a'))) print("The hexadecimal form of 3.9 is " + float.hex(3.9))
Output :
The hexadecimal form of 23 is 0x17
The hexadecimal form of the ascii value os 'a' is 0x61
The hexadecimal form of 3.9 is 0x1.f333333333333p+1
Code #2: Demonstrate TypeError when floating point values are passed as parameter.
Python3
# hex() accepts only integer values as parametersprint("The hexadecimal form of 11.1 is " + hex(11.1)) '''# The hexadecimal conversion of floating # point integers can be done using the# function float.hex()print("The hexadecimal form of 11.1 is " + float.hex(11.1))# Output :# The hexadecimal form of 11.1 is 0x1.6333333333333p+3 # Similarly, float.hex() throws a TypeError# when integer values are passed in it.'''
Output :
Traceback (most recent call last):
File "/home/7e1ac7e34362fd690cdb72cf294502e1.py", line 2, in
print("The hexadecimal form of 11.1 is "+hex(11.1))
TypeError: 'float' object cannot be interpreted as an integer
Applications : hex() is used in all the standard conversions. For example conversion of hexadecimal to decimal, hexadecimal to octal, hexadecimal to binary.
Code #3 :
Python3
# TypeConversion from decimal with base 10# to hexadecimal form with base 16 # Taking input from user# an integer with base 10number = int(input("Enter a number with base 10\n")) # The choices present to the userprint("a. Decimal to Hexadecimal ")print("b. Decimal to Octal")print("c. Decimal to Binary") # taking user inputprint("Enter your choice :- ")choice = input() # Running a variable choice# Hexadecimal form if choice# is set to 'a'if choice is 'a': # lstrip helps remove "0x" from the left # rstrip helps remove "L" from the right, # L represents a long number print("Hexadecimal form of " + str(number) + " is " + hex(number).lstrip("0x").rstrip("L")) if choice is 'b': # Octal representation is done # by adding a prefix "0o" print("Octal form of " + str(number) + " is " + oct(number).lstrip("0o").rstrip("L")) if choice is 'c': # Binary representation is done by # the addition of prefix "0b" print("Binary form of " + str(number) + " is "+bin(number).lstrip("0b").rstrip("L"))
Output :
input variant a)
Enter a number with base 10
123
a. Decimal to Hexadecimal
b. Decimal to Octal
c. Decimal to Binary
Enter your choice:-
a
Hexadecimal form of 123 is 7b
input variant b)
Enter a number with base 10
123456789
a. Decimal to Hexadecimal
b. Decimal to Octal
c. Decimal to Binary
Enter your choice:-
a
Hexadecimal form of 123456789 is 75bcd15
nidhi_biet
alexanderstohr
varshagumber28
python-basics
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
|
[
{
"code": null,
"e": 24652,
"s": 24624,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 24797,
"s": 24652,
"text": "hex() function is one of the built-in functions in Python3, which is used to convert an integer number into itβs corresponding hexadecimal form."
},
{
"code": null,
"e": 24807,
"s": 24797,
"text": "Syntax : "
},
{
"code": null,
"e": 24903,
"s": 24807,
"text": "hex(x) \nParameters : \nx - an integer number (int object)\nReturns : Returns hexadecimal string."
},
{
"code": null,
"e": 24928,
"s": 24903,
"text": "Errors and Exceptions : "
},
{
"code": null,
"e": 25046,
"s": 24928,
"text": "TypeError : Returns TypeError when anything other than\n integer type constants are passed as parameters."
},
{
"code": null,
"e": 25094,
"s": 25046,
"text": " Code #1 : Illustrates use of hex() function. "
},
{
"code": null,
"e": 25102,
"s": 25094,
"text": "Python3"
},
{
"code": "# Python3 program to illustrate# hex() function print(\"The hexadecimal form of 23 is \" + hex(23)) print(\"The hexadecimal form of the \" \"ascii value is 'a' is \" + hex(ord('a'))) print(\"The hexadecimal form of 3.9 is \" + float.hex(3.9))",
"e": 25426,
"s": 25102,
"text": null
},
{
"code": null,
"e": 25436,
"s": 25426,
"text": "Output : "
},
{
"code": null,
"e": 25578,
"s": 25436,
"text": "The hexadecimal form of 23 is 0x17\nThe hexadecimal form of the ascii value os 'a' is 0x61\nThe hexadecimal form of 3.9 is 0x1.f333333333333p+1"
},
{
"code": null,
"e": 25662,
"s": 25578,
"text": "Code #2: Demonstrate TypeError when floating point values are passed as parameter. "
},
{
"code": null,
"e": 25670,
"s": 25662,
"text": "Python3"
},
{
"code": "# hex() accepts only integer values as parametersprint(\"The hexadecimal form of 11.1 is \" + hex(11.1)) '''# The hexadecimal conversion of floating # point integers can be done using the# function float.hex()print(\"The hexadecimal form of 11.1 is \" + float.hex(11.1))# Output :# The hexadecimal form of 11.1 is 0x1.6333333333333p+3 # Similarly, float.hex() throws a TypeError# when integer values are passed in it.'''",
"e": 26133,
"s": 25670,
"text": null
},
{
"code": null,
"e": 26143,
"s": 26133,
"text": "Output : "
},
{
"code": null,
"e": 26360,
"s": 26143,
"text": "Traceback (most recent call last):\n File \"/home/7e1ac7e34362fd690cdb72cf294502e1.py\", line 2, in \n print(\"The hexadecimal form of 11.1 is \"+hex(11.1))\nTypeError: 'float' object cannot be interpreted as an integer"
},
{
"code": null,
"e": 26520,
"s": 26360,
"text": " Applications : hex() is used in all the standard conversions. For example conversion of hexadecimal to decimal, hexadecimal to octal, hexadecimal to binary. "
},
{
"code": null,
"e": 26531,
"s": 26520,
"text": "Code #3 : "
},
{
"code": null,
"e": 26539,
"s": 26531,
"text": "Python3"
},
{
"code": "# TypeConversion from decimal with base 10# to hexadecimal form with base 16 # Taking input from user# an integer with base 10number = int(input(\"Enter a number with base 10\\n\")) # The choices present to the userprint(\"a. Decimal to Hexadecimal \")print(\"b. Decimal to Octal\")print(\"c. Decimal to Binary\") # taking user inputprint(\"Enter your choice :- \")choice = input() # Running a variable choice# Hexadecimal form if choice# is set to 'a'if choice is 'a': # lstrip helps remove \"0x\" from the left # rstrip helps remove \"L\" from the right, # L represents a long number print(\"Hexadecimal form of \" + str(number) + \" is \" + hex(number).lstrip(\"0x\").rstrip(\"L\")) if choice is 'b': # Octal representation is done # by adding a prefix \"0o\" print(\"Octal form of \" + str(number) + \" is \" + oct(number).lstrip(\"0o\").rstrip(\"L\")) if choice is 'c': # Binary representation is done by # the addition of prefix \"0b\" print(\"Binary form of \" + str(number) + \" is \"+bin(number).lstrip(\"0b\").rstrip(\"L\"))",
"e": 27610,
"s": 26539,
"text": null
},
{
"code": null,
"e": 27620,
"s": 27610,
"text": "Output : "
},
{
"code": null,
"e": 27637,
"s": 27620,
"text": "input variant a)"
},
{
"code": null,
"e": 27790,
"s": 27637,
"text": "Enter a number with base 10\n123\na. Decimal to Hexadecimal \nb. Decimal to Octal\nc. Decimal to Binary\nEnter your choice:- \na\nHexadecimal form of 123 is 7b"
},
{
"code": null,
"e": 27807,
"s": 27790,
"text": "input variant b)"
},
{
"code": null,
"e": 27977,
"s": 27807,
"text": "Enter a number with base 10\n123456789\na. Decimal to Hexadecimal \nb. Decimal to Octal\nc. Decimal to Binary\nEnter your choice:- \na\nHexadecimal form of 123456789 is 75bcd15"
},
{
"code": null,
"e": 27988,
"s": 27977,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28003,
"s": 27988,
"text": "alexanderstohr"
},
{
"code": null,
"e": 28018,
"s": 28003,
"text": "varshagumber28"
},
{
"code": null,
"e": 28032,
"s": 28018,
"text": "python-basics"
},
{
"code": null,
"e": 28058,
"s": 28032,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 28065,
"s": 28058,
"text": "Python"
},
{
"code": null,
"e": 28163,
"s": 28065,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28172,
"s": 28163,
"text": "Comments"
},
{
"code": null,
"e": 28185,
"s": 28172,
"text": "Old Comments"
},
{
"code": null,
"e": 28203,
"s": 28185,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28235,
"s": 28203,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28257,
"s": 28235,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28299,
"s": 28257,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28325,
"s": 28299,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28362,
"s": 28325,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28406,
"s": 28362,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28435,
"s": 28406,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28491,
"s": 28435,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Create a large button with Bootstrap
|
To create a large button, use the .btn-lg class in Bootstrap.
You can try to run the following code to implement the .btn-lg class β
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<p>The following are FMCG companies:</p>
<div class = "btn-default">
<button type = "button" class="btn btn-primary">ITC Limited</button>
<button type = "button" class="btn btn-sm">Nestle</button>
<button type = "button" class="btn btn-lg">Britannia Industries Limited</button>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "To create a large button, use the .btn-lg class in Bootstrap."
},
{
"code": null,
"e": 1195,
"s": 1124,
"text": "You can try to run the following code to implement the .btn-lg class β"
},
{
"code": null,
"e": 1205,
"s": 1195,
"text": "Live Demo"
},
{
"code": null,
"e": 1955,
"s": 1205,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>The following are FMCG companies:</p>\n <div class = \"btn-default\">\n <button type = \"button\" class=\"btn btn-primary\">ITC Limited</button>\n <button type = \"button\" class=\"btn btn-sm\">Nestle</button>\n <button type = \"button\" class=\"btn btn-lg\">Britannia Industries Limited</button>\n </div>\n </body>\n</html>"
}
] |
SVG - Polyline
|
<polyline> element is used to draw a connected straight lines.
Following is the syntax declaration of <polyline> element. We've shown main attributes only.
<polyline
points="list of points" >
</polyline>
<html>
<title>SVG Polyline</title>
<body>
<h1>Sample SVG Polyline Image</h1>
<svg width="800" height="800">
<g>
<text x="0" y="15" fill="black" >Polyline #1: Without opacity.</text>
<polyline points="150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5"
stroke="black" stroke-width="3" fill="none"></polyline>
</g>
</svg>
</body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
<html>
<title>SVG Polyline</title>
<body>
<h1>Sample SVG Polyline Image</h1>
<svg width="800" height="800">
<g>
<text x="0" y="15" fill="black" >Polyline #2: With opacity </text>
<polyline points="150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5"
style="fill:none;stroke-width:3;
stroke:rgb(0,0,0);stroke-opacity:0.5;"></polyline>
</g>
</svg>
</body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2428,
"s": 2364,
"text": "<polyline> element is used to draw a connected straight lines."
},
{
"code": null,
"e": 2521,
"s": 2428,
"text": "Following is the syntax declaration of <polyline> element. We've shown main attributes only."
},
{
"code": null,
"e": 2574,
"s": 2521,
"text": "<polyline\n points=\"list of points\" > \n</polyline>"
},
{
"code": null,
"e": 3024,
"s": 2574,
"text": "<html>\n <title>SVG Polyline</title>\n <body>\n \n <h1>Sample SVG Polyline Image</h1>\n \n <svg width=\"800\" height=\"800\">\n <g>\n <text x=\"0\" y=\"15\" fill=\"black\" >Polyline #1: Without opacity.</text>\n \n <polyline points=\"150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5\"\n stroke=\"black\" stroke-width=\"3\" fill=\"none\"></polyline>\n </g>\n </svg>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3211,
"s": 3024,
"text": "Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering."
},
{
"code": null,
"e": 3698,
"s": 3211,
"text": "<html>\n <title>SVG Polyline</title>\n <body>\n \n <h1>Sample SVG Polyline Image</h1>\n \n <svg width=\"800\" height=\"800\">\n <g>\n <text x=\"0\" y=\"15\" fill=\"black\" >Polyline #2: With opacity </text>\n \n <polyline points=\"150,75 258,137.5 258,262.5 150,325 42,262.6 42,137.5\"\n style=\"fill:none;stroke-width:3;\n stroke:rgb(0,0,0);stroke-opacity:0.5;\"></polyline>\n </g>\n </svg>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3884,
"s": 3698,
"text": "Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering."
},
{
"code": null,
"e": 3919,
"s": 3884,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3950,
"s": 3919,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3957,
"s": 3950,
"text": " Print"
},
{
"code": null,
"e": 3968,
"s": 3957,
"text": " Add Notes"
}
] |
MySQL - LIKE Clause
|
We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records.
A WHERE clause with the βequal toβ sign (=) works fine where we want to do an exact match. Like if "tutorial_author = 'Sanjay'". But there may be a requirement where we want to filter out all the results where tutorial_author name should contain "jay". This can be handled using SQL LIKE Clause along with the WHERE clause.
If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause.
The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table.
SELECT field1, field2,...fieldN table_name1, table_name2...
WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'
You can specify any condition using the WHERE clause.
You can specify any condition using the WHERE clause.
You can use the LIKE clause along with the WHERE clause.
You can use the LIKE clause along with the WHERE clause.
You can use the LIKE clause in place of the equals to sign.
You can use the LIKE clause in place of the equals to sign.
When LIKE is used along with % sign then it will work like a meta character search.
When LIKE is used along with % sign then it will work like a meta character search.
You can specify more than one condition using AND or OR operators.
You can specify more than one condition using AND or OR operators.
A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.
A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.
This will use the SQL SELECT command with the WHERE...LIKE clause to fetch the selected data from the MySQL table β tutorials_tbl.
The following example will return all the records from the tutorials_tbl table for which the author name ends with jay β
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl
-> WHERE tutorial_author LIKE '%jay';
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
1 rows in set (0.01 sec)
mysql>
PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using Like clause. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)
$sql
Required - SQL query to select records in a MySQL table using Like Clause.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to select a record using like clause in a table β
Copy and paste the following example as mysql_example.php β
<html>
<head>
<title>Using Like Clause</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl where tutorial_author like "Mah%"';
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
$row["tutorial_id"],
$row["tutorial_title"],
$row["tutorial_author"],
$row["submission_date"]);
}
} else {
printf('No record found.<br />');
}
mysqli_free_result($result);
$mysqli->close();
?>
</body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script.
Connected successfully.
Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2501,
"s": 2333,
"text": "We have seen the SQL SELECT command to fetch data from the MySQL table. We can also use a conditional clause called as the WHERE clause to select the required records."
},
{
"code": null,
"e": 2825,
"s": 2501,
"text": "A WHERE clause with the βequal toβ sign (=) works fine where we want to do an exact match. Like if \"tutorial_author = 'Sanjay'\". But there may be a requirement where we want to filter out all the results where tutorial_author name should contain \"jay\". This can be handled using SQL LIKE Clause along with the WHERE clause."
},
{
"code": null,
"e": 3112,
"s": 2825,
"text": "If the SQL LIKE clause is used along with the % character, then it will work like a meta character (*) as in UNIX, while listing out all the files or directories at the command prompt. Without a % character, the LIKE clause is very same as the equal to sign along with the WHERE clause."
},
{
"code": null,
"e": 3245,
"s": 3112,
"text": "The following code block has a generic SQL syntax of the SELECT command along with the LIKE clause to fetch data from a MySQL table."
},
{
"code": null,
"e": 3367,
"s": 3245,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\nWHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'\n"
},
{
"code": null,
"e": 3421,
"s": 3367,
"text": "You can specify any condition using the WHERE clause."
},
{
"code": null,
"e": 3475,
"s": 3421,
"text": "You can specify any condition using the WHERE clause."
},
{
"code": null,
"e": 3532,
"s": 3475,
"text": "You can use the LIKE clause along with the WHERE clause."
},
{
"code": null,
"e": 3589,
"s": 3532,
"text": "You can use the LIKE clause along with the WHERE clause."
},
{
"code": null,
"e": 3649,
"s": 3589,
"text": "You can use the LIKE clause in place of the equals to sign."
},
{
"code": null,
"e": 3709,
"s": 3649,
"text": "You can use the LIKE clause in place of the equals to sign."
},
{
"code": null,
"e": 3793,
"s": 3709,
"text": "When LIKE is used along with % sign then it will work like a meta character search."
},
{
"code": null,
"e": 3877,
"s": 3793,
"text": "When LIKE is used along with % sign then it will work like a meta character search."
},
{
"code": null,
"e": 3944,
"s": 3877,
"text": "You can specify more than one condition using AND or OR operators."
},
{
"code": null,
"e": 4011,
"s": 3944,
"text": "You can specify more than one condition using AND or OR operators."
},
{
"code": null,
"e": 4114,
"s": 4011,
"text": "A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition."
},
{
"code": null,
"e": 4217,
"s": 4114,
"text": "A WHERE...LIKE clause can be used along with DELETE or UPDATE SQL command also to specify a condition."
},
{
"code": null,
"e": 4348,
"s": 4217,
"text": "This will use the SQL SELECT command with the WHERE...LIKE clause to fetch the selected data from the MySQL table β tutorials_tbl."
},
{
"code": null,
"e": 4469,
"s": 4348,
"text": "The following example will return all the records from the tutorials_tbl table for which the author name ends with jay β"
},
{
"code": null,
"e": 5027,
"s": 4469,
"text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl \n -> WHERE tutorial_author LIKE '%jay';\n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 3 | JAVA Tutorial | Sanjay | 2007-05-21 | \n+-------------+----------------+-----------------+-----------------+\n1 rows in set (0.01 sec)\n\nmysql>"
},
{
"code": null,
"e": 5215,
"s": 5027,
"text": "PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using Like clause. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 5249,
"s": 5215,
"text": "$mysqli->query($sql,$resultmode)\n"
},
{
"code": null,
"e": 5254,
"s": 5249,
"text": "$sql"
},
{
"code": null,
"e": 5329,
"s": 5254,
"text": "Required - SQL query to select records in a MySQL table using Like Clause."
},
{
"code": null,
"e": 5341,
"s": 5329,
"text": "$resultmode"
},
{
"code": null,
"e": 5489,
"s": 5341,
"text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used."
},
{
"code": null,
"e": 5565,
"s": 5489,
"text": "Try the following example to select a record using like clause in a table β"
},
{
"code": null,
"e": 5625,
"s": 5565,
"text": "Copy and paste the following example as mysql_example.php β"
},
{
"code": null,
"e": 6849,
"s": 5625,
"text": "<html>\n <head>\n <title>Using Like Clause</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date \n FROM tutorials_tbl where tutorial_author like \"Mah%\"';\n\t\t \n $result = $mysqli->query($sql);\n \n if ($result->num_rows > 0) {\n while($row = $result->fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli->close();\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 7014,
"s": 6849,
"text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script."
},
{
"code": null,
"e": 7207,
"s": 7014,
"text": "Connected successfully.\nId: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021\nId: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021\nId: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021\n"
},
{
"code": null,
"e": 7240,
"s": 7207,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7268,
"s": 7240,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7303,
"s": 7268,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7320,
"s": 7303,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7354,
"s": 7320,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7389,
"s": 7354,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 7423,
"s": 7389,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7451,
"s": 7423,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 7484,
"s": 7451,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7504,
"s": 7484,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 7537,
"s": 7504,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7555,
"s": 7537,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 7562,
"s": 7555,
"text": " Print"
},
{
"code": null,
"e": 7573,
"s": 7562,
"text": " Add Notes"
}
] |
K'th Non-repeating Character - GeeksforGeeks
|
18 Nov, 2021
Given a string and a number k, find the kβth non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples:
Input : str = geeksforgeeks, k = 3
Output : r
First non-repeating character is f,
second is o and third is r.
Input : str = geeksforgeeks, k = 2
Output : o
Input : str = geeksforgeeks, k = 4
Output : Less than k non-repeating
characters in input.
This problem is mainly an extension of First non-repeating character problem.Method 1 (Simple : O(n2) A Simple Solution is to run two loops. Start traversing from left side. For every character, check if it repeats or not. If the character doesnβt repeat, increment count of non-repeating characters. When the count becomes k, return the character.Method 2 (O(n) but requires two traversals)
Create an empty hash.Scan input string from left to right and insert values and their counts in the hash.Scan input string from left to right and keep count of characters with counts more than 1. When count becomes k, return the character.
Create an empty hash.
Scan input string from left to right and insert values and their counts in the hash.
Scan input string from left to right and keep count of characters with counts more than 1. When count becomes k, return the character.
Method 3 (O(n) and requires one traversal) The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored using 8 bits). The two arrays are:
count[x] : Stores count of character 'x' in str.
If x is not present, then it stores 0.
index[x] : Stores indexes of non-repeating characters
in str. If a character 'x' is not present
or x is repeating, then it stores a value
that cannot be a valid index in str[]. For
example, length of string.
Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = nNow index[] has indexes of all non-repeating characters. Sort index[] in increasing order so that we get kβth smallest element at index[k]. Note that this step takes O(1) time because there are only 256 elements in index[].
Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.
Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = n
Increment count[x].
If count[x] is 1, then store index of x in index[x], i.e., index[x] = i
If count[x] is 2, then remove x from index[], i.e., index[x] = n
Now index[] has indexes of all non-repeating characters. Sort index[] in increasing order so that we get kβth smallest element at index[k]. Note that this step takes O(1) time because there are only 256 elements in index[].
Below is implementation of above idea.
C++
Java
Python 3
C#
Javascript
// C++ program to find k'th non-repeating character// in a string#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 256; // Returns index of k'th non-repeating character in// given string str[]int kthNonRepeating(string str, int k){ int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int count[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int index[MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str[i]; ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only sort(index, index+MAX_CHAR); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1;} // Driver codeint main(){ string str = "geeksforgeeks"; int k = 3; int res = kthNonRepeating(str, k); (res == -1)? cout << "There are less than k non-" "repeating characters" : cout << "k'th non-repeating character" " is "<< str[res]; return 0;}
// Java program to find k'th non-repeating character// in a string import java.util.Arrays; class GFG{ public static int MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[] static int kthNonRepeating(String str, int k) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int[] count = new int[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int[] index = new int[MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str.charAt(i); ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only Arrays.sort(index); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1; } // driver program public static void main (String[] args) { String str = "geeksforgeeks"; int k = 3; int res = kthNonRepeating(str, k); System.out.println(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + str.charAt(res)); }} // Contributed by Pramod Kumar
# Python 3 program to find k'th# non-repeating character in a stringMAX_CHAR = 256 # Returns index of k'th non-repeating# character in given string str[]def kthNonRepeating(str, k): n = len(str) # count[x] is going to store count of # character 'x' in str. If x is not # present, then it is going to store 0. count = [0] * MAX_CHAR # index[x] is going to store index of # character 'x' in str. If x is not # present or x is repeating, then it # is going to store a value (for example, # length of string) that cannot be a valid # index in str[] index = [0] * MAX_CHAR # Initialize counts of all characters # and indexes of non-repeating characters. for i in range( MAX_CHAR): count[i] = 0 index[i] = n # A value more than any # index in str[] # Traverse the input string for i in range(n): # Find current character and # increment its count x = str[i] count[ord(x)] += 1 # If this is first occurrence, then # set value in index as index of it. if (count[ord(x)] == 1): index[ord(x)] = i # If character repeats, then remove # it from index[] if (count[ord(x)] == 2): index[ord(x)] = n # Sort index[] in increasing order. This step # takes O(1) time as size of index is 256 only index.sort() # After sorting, if index[k-1] is value, # then return it, else return -1. return index[k - 1] if (index[k - 1] != n) else -1 # Driver codeif __name__ == "__main__": str = "geeksforgeeks" k = 3 res = kthNonRepeating(str, k) if(res == -1): print("There are less than k", "non-repeating characters") else: print("k'th non-repeating character is", str[res]) # This code is contributed# by ChitraNayal
// C# program to find k'th non-repeating// character in a stringusing System; class GFG { public static int MAX_CHAR = 256; // Returns index of k'th non-repeating // character in given string str[] static int kthNonRepeating(String str, int k) { int n = str.Length; // count[x] is going to store count of // character 'x' in str. If x is not // present, then it is going to store 0. int []count = new int[MAX_CHAR]; // index[x] is going to store index of // character 'x' in str. If x is not // present or x is repeating, then it // is going to store a value (for // example, length of string) that // cannot be a valid index in str[] int []index = new int[MAX_CHAR]; // Initialize counts of all characters // and indexes of non-repeating // characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; // A value more than any index // in str[] index[i] = n; } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and // increment its count char x = str[i]; ++count[x]; // If this is first occurrence, // then set value in index as // index of it. if (count[x] == 1) index[x] = i; // If character repeats, then // remove it from index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. // This step takes O(1) time as size // of index is 256 only Array.Sort(index); // After sorting, if index[k-1] is // value, then return it, else // return -1. return (index[k-1] != n) ? index[k-1] : -1; } // driver program public static void Main () { String str = "geeksforgeeks"; int k = 3; int res = kthNonRepeating(str, k); Console.Write(res == -1 ? "There are less" + " than k non-repeating characters" : "k'th non-repeating character is " + str[res]); }} // This code is contributed by nitin mittal.
<script>// Javascript program to find k'th non-repeating character// in a string let MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[]function kthNonRepeating(str,k){ let n = str.length; // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. let count = new Array(MAX_CHAR); // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] let index = new Array(MAX_CHAR); // Initialize counts of all characters and indexes // of non-repeating characters. for (let i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (let i = 0; i < n; i++) { // Find current character and increment its // count let x = str[i]; ++count[x.charCodeAt(0)]; // If this is first occurrence, then set value // in index as index of it. if (count[x.charCodeAt(0)] == 1) index[x.charCodeAt(0)] = i; // If character repeats, then remove it from // index[] if (count[x.charCodeAt(0)] == 2) index[x.charCodeAt(0)] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only (index).sort(function(a,b){return a-b;}); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1;} // driver programlet str = "geeksforgeeks";let k = 3;let res = kthNonRepeating(str, k);document.write(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + str[res]); // This code is contributed by ab2127</script>
k'th non-repeating character is r
Space Optimized Solution : This can be space optimized and can be solved using single index array only. Below is the space optimized solution:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;#define MAX_CHAR 256int kthNonRepeating(string input, int k){ int inputLength = input.length(); /* * indexArr will store index of non-repeating * characters, inputLength for characters not in input * and inputLength+1 for repeated characters. */ int indexArr[MAX_CHAR]; // initialize all values in indexArr as inputLength. for (int i = 0; i < MAX_CHAR; i++) { indexArr[i] = inputLength; } for (int i = 0; i < inputLength; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } sort(indexArr, indexArr + MAX_CHAR); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1;} int main(){ string input = "geeksforgeeks"; int k = 3; int res = kthNonRepeating(input, k); if (res == -1) cout << "There are less than k non-repeating " "characters"; else cout << "k'th non-repeating character is " << input[res]; return 0;} // This code is contributed by gauravrajput1
import java.util.*; public class GFG { public static int MAX_CHAR = 256; public static void main (String[] args) { final String input = "geeksforgeeks"; int k = 3; int res = kthNonRepeating(input, k); System.out.println(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + input.charAt(res)); } public static int kthNonRepeating(final String input, final int k) { final int inputLength = input.length(); /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ final int[] indexArr = new int[MAX_CHAR]; // initialize all values in indexArr as inputLength. Arrays.fill(indexArr, inputLength); for (int i = 0; i < inputLength ; i++) { final char c = input.charAt(i); if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } Arrays.sort(indexArr); return (indexArr[k-1] != inputLength) ? indexArr[k-1] : -1; }}// Contributed by AK
MAX_CHAR = 256 def kthNonRepeating(Input,k): inputLength = len(Input) # indexArr will store index of non-repeating characters, # inputLength for characters not in input and # inputLength+1 for repeated characters. # initialize all values in indexArr as inputLength. indexArr = [inputLength for i in range(MAX_CHAR)] for i in range(inputLength): c = Input[i] if (indexArr[ord(c)] == inputLength): indexArr[ord(c)] = i else: indexArr[ord(c)] = inputLength + 2 indexArr.sort() if(indexArr[k - 1] != inputLength): return indexArr[k - 1] else: return -1 Input = "geeksforgeeks"k = 3res = kthNonRepeating(Input, k)if(res == -1): print("There are less than k non-repeating characters")else: print("k'th non-repeating character is", Input[res]) # This code is contributed by rag2127
using System; public class GFG{ public static int MAX_CHAR = 256; static public void Main () { string input = "geeksforgeeks"; int k = 3; int res = kthNonRepeating(input, k); Console.WriteLine(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + input[res]); } public static int kthNonRepeating(string input, int k) { int inputLength = input.Length; /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ int[] indexArr = new int[MAX_CHAR]; // initialize all values in indexArr as inputLength. Array.Fill(indexArr, inputLength); for (int i = 0; i < inputLength ; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } Array.Sort(indexArr); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1; }} // This code is contributed by avanitrachhadiya2155
<script> let MAX_CHAR = 256; function kthNonRepeating(input, k){ let inputLength = input.length; /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ let indexArr = new Array(MAX_CHAR); // initialize all values in indexArr as inputLength. for(let i=0;i<MAX_CHAR;i++) { indexArr[i]=inputLength; } for (let i = 0; i < inputLength ; i++) { let c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } (indexArr).sort(function(a,b){return a-b;}); return (indexArr[k-1] != inputLength) ? indexArr[k-1] : -1;} let input = "geeksforgeeks";let k = 3;let res = kthNonRepeating(input, k);document.write(res == -1 ? "There are less than k non-repeating characters" : "k'th non-repeating character is " + input[res]); // This code is contributed by unknown2108</script>
k'th non-repeating character is r
This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
nitin mittal
ukasp
abhishekkumarnitrr
avanitrachhadiya2155
rag2127
ab2127
unknown2108
GauravRajput1
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
VigeneΜre Cipher
How to Append a Character to a String in C
Convert character array to string in C++
Reverse words in a given String in Python
Print all the duplicates in the input string
sprintf() in C
Print all subsequences of a string
|
[
{
"code": null,
"e": 24774,
"s": 24746,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 25027,
"s": 24774,
"text": "Given a string and a number k, find the kβth non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: "
},
{
"code": null,
"e": 25285,
"s": 25027,
"text": "Input : str = geeksforgeeks, k = 3\nOutput : r\nFirst non-repeating character is f,\nsecond is o and third is r.\n\nInput : str = geeksforgeeks, k = 2\nOutput : o\n\nInput : str = geeksforgeeks, k = 4\nOutput : Less than k non-repeating\n characters in input."
},
{
"code": null,
"e": 25681,
"s": 25287,
"text": "This problem is mainly an extension of First non-repeating character problem.Method 1 (Simple : O(n2) A Simple Solution is to run two loops. Start traversing from left side. For every character, check if it repeats or not. If the character doesnβt repeat, increment count of non-repeating characters. When the count becomes k, return the character.Method 2 (O(n) but requires two traversals) "
},
{
"code": null,
"e": 25921,
"s": 25681,
"text": "Create an empty hash.Scan input string from left to right and insert values and their counts in the hash.Scan input string from left to right and keep count of characters with counts more than 1. When count becomes k, return the character."
},
{
"code": null,
"e": 25943,
"s": 25921,
"text": "Create an empty hash."
},
{
"code": null,
"e": 26028,
"s": 25943,
"text": "Scan input string from left to right and insert values and their counts in the hash."
},
{
"code": null,
"e": 26163,
"s": 26028,
"text": "Scan input string from left to right and keep count of characters with counts more than 1. When count becomes k, return the character."
},
{
"code": null,
"e": 26332,
"s": 26163,
"text": "Method 3 (O(n) and requires one traversal) The idea is to use two auxiliary arrays of size 256 (Assuming that characters are stored using 8 bits). The two arrays are: "
},
{
"code": null,
"e": 26687,
"s": 26332,
"text": "count[x] : Stores count of character 'x' in str.\n If x is not present, then it stores 0.\n\nindex[x] : Stores indexes of non-repeating characters\n in str. If a character 'x' is not present\n or x is repeating, then it stores a value\n that cannot be a valid index in str[]. For \n example, length of string."
},
{
"code": null,
"e": 27243,
"s": 26689,
"text": "Initialize all values in count[] as 0 and all values in index[] as n where n is length of string.Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = nNow index[] has indexes of all non-repeating characters. Sort index[] in increasing order so that we get kβth smallest element at index[k]. Note that this step takes O(1) time because there are only 256 elements in index[]."
},
{
"code": null,
"e": 27341,
"s": 27243,
"text": "Initialize all values in count[] as 0 and all values in index[] as n where n is length of string."
},
{
"code": null,
"e": 27575,
"s": 27341,
"text": "Traverse the input string str and do following for every character c = str[i]. Increment count[x].If count[x] is 1, then store index of x in index[x], i.e., index[x] = iIf count[x] is 2, then remove x from index[], i.e., index[x] = n"
},
{
"code": null,
"e": 27595,
"s": 27575,
"text": "Increment count[x]."
},
{
"code": null,
"e": 27667,
"s": 27595,
"text": "If count[x] is 1, then store index of x in index[x], i.e., index[x] = i"
},
{
"code": null,
"e": 27732,
"s": 27667,
"text": "If count[x] is 2, then remove x from index[], i.e., index[x] = n"
},
{
"code": null,
"e": 27956,
"s": 27732,
"text": "Now index[] has indexes of all non-repeating characters. Sort index[] in increasing order so that we get kβth smallest element at index[k]. Note that this step takes O(1) time because there are only 256 elements in index[]."
},
{
"code": null,
"e": 27996,
"s": 27956,
"text": "Below is implementation of above idea. "
},
{
"code": null,
"e": 28000,
"s": 27996,
"text": "C++"
},
{
"code": null,
"e": 28005,
"s": 28000,
"text": "Java"
},
{
"code": null,
"e": 28014,
"s": 28005,
"text": "Python 3"
},
{
"code": null,
"e": 28017,
"s": 28014,
"text": "C#"
},
{
"code": null,
"e": 28028,
"s": 28017,
"text": "Javascript"
},
{
"code": "// C++ program to find k'th non-repeating character// in a string#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 256; // Returns index of k'th non-repeating character in// given string str[]int kthNonRepeating(string str, int k){ int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int count[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int index[MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str[i]; ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only sort(index, index+MAX_CHAR); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1;} // Driver codeint main(){ string str = \"geeksforgeeks\"; int k = 3; int res = kthNonRepeating(str, k); (res == -1)? cout << \"There are less than k non-\" \"repeating characters\" : cout << \"k'th non-repeating character\" \" is \"<< str[res]; return 0;}",
"e": 29985,
"s": 28028,
"text": null
},
{
"code": "// Java program to find k'th non-repeating character// in a string import java.util.Arrays; class GFG{ public static int MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[] static int kthNonRepeating(String str, int k) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int[] count = new int[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int[] index = new int[MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str.charAt(i); ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only Arrays.sort(index); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1; } // driver program public static void main (String[] args) { String str = \"geeksforgeeks\"; int k = 3; int res = kthNonRepeating(str, k); System.out.println(res == -1 ? \"There are less than k non-repeating characters\" : \"k'th non-repeating character is \" + str.charAt(res)); }} // Contributed by Pramod Kumar",
"e": 32245,
"s": 29985,
"text": null
},
{
"code": "# Python 3 program to find k'th# non-repeating character in a stringMAX_CHAR = 256 # Returns index of k'th non-repeating# character in given string str[]def kthNonRepeating(str, k): n = len(str) # count[x] is going to store count of # character 'x' in str. If x is not # present, then it is going to store 0. count = [0] * MAX_CHAR # index[x] is going to store index of # character 'x' in str. If x is not # present or x is repeating, then it # is going to store a value (for example, # length of string) that cannot be a valid # index in str[] index = [0] * MAX_CHAR # Initialize counts of all characters # and indexes of non-repeating characters. for i in range( MAX_CHAR): count[i] = 0 index[i] = n # A value more than any # index in str[] # Traverse the input string for i in range(n): # Find current character and # increment its count x = str[i] count[ord(x)] += 1 # If this is first occurrence, then # set value in index as index of it. if (count[ord(x)] == 1): index[ord(x)] = i # If character repeats, then remove # it from index[] if (count[ord(x)] == 2): index[ord(x)] = n # Sort index[] in increasing order. This step # takes O(1) time as size of index is 256 only index.sort() # After sorting, if index[k-1] is value, # then return it, else return -1. return index[k - 1] if (index[k - 1] != n) else -1 # Driver codeif __name__ == \"__main__\": str = \"geeksforgeeks\" k = 3 res = kthNonRepeating(str, k) if(res == -1): print(\"There are less than k\", \"non-repeating characters\") else: print(\"k'th non-repeating character is\", str[res]) # This code is contributed# by ChitraNayal",
"e": 34127,
"s": 32245,
"text": null
},
{
"code": "// C# program to find k'th non-repeating// character in a stringusing System; class GFG { public static int MAX_CHAR = 256; // Returns index of k'th non-repeating // character in given string str[] static int kthNonRepeating(String str, int k) { int n = str.Length; // count[x] is going to store count of // character 'x' in str. If x is not // present, then it is going to store 0. int []count = new int[MAX_CHAR]; // index[x] is going to store index of // character 'x' in str. If x is not // present or x is repeating, then it // is going to store a value (for // example, length of string) that // cannot be a valid index in str[] int []index = new int[MAX_CHAR]; // Initialize counts of all characters // and indexes of non-repeating // characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; // A value more than any index // in str[] index[i] = n; } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and // increment its count char x = str[i]; ++count[x]; // If this is first occurrence, // then set value in index as // index of it. if (count[x] == 1) index[x] = i; // If character repeats, then // remove it from index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. // This step takes O(1) time as size // of index is 256 only Array.Sort(index); // After sorting, if index[k-1] is // value, then return it, else // return -1. return (index[k-1] != n) ? index[k-1] : -1; } // driver program public static void Main () { String str = \"geeksforgeeks\"; int k = 3; int res = kthNonRepeating(str, k); Console.Write(res == -1 ? \"There are less\" + \" than k non-repeating characters\" : \"k'th non-repeating character is \" + str[res]); }} // This code is contributed by nitin mittal.",
"e": 36483,
"s": 34127,
"text": null
},
{
"code": "<script>// Javascript program to find k'th non-repeating character// in a string let MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[]function kthNonRepeating(str,k){ let n = str.length; // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. let count = new Array(MAX_CHAR); // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] let index = new Array(MAX_CHAR); // Initialize counts of all characters and indexes // of non-repeating characters. for (let i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (let i = 0; i < n; i++) { // Find current character and increment its // count let x = str[i]; ++count[x.charCodeAt(0)]; // If this is first occurrence, then set value // in index as index of it. if (count[x.charCodeAt(0)] == 1) index[x.charCodeAt(0)] = i; // If character repeats, then remove it from // index[] if (count[x.charCodeAt(0)] == 2) index[x.charCodeAt(0)] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only (index).sort(function(a,b){return a-b;}); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1;} // driver programlet str = \"geeksforgeeks\";let k = 3;let res = kthNonRepeating(str, k);document.write(res == -1 ? \"There are less than k non-repeating characters\" : \"k'th non-repeating character is \" + str[res]); // This code is contributed by ab2127</script>",
"e": 38655,
"s": 36483,
"text": null
},
{
"code": null,
"e": 38690,
"s": 38655,
"text": "k'th non-repeating character is r"
},
{
"code": null,
"e": 38836,
"s": 38692,
"text": "Space Optimized Solution : This can be space optimized and can be solved using single index array only. Below is the space optimized solution: "
},
{
"code": null,
"e": 38840,
"s": 38836,
"text": "C++"
},
{
"code": null,
"e": 38845,
"s": 38840,
"text": "Java"
},
{
"code": null,
"e": 38853,
"s": 38845,
"text": "Python3"
},
{
"code": null,
"e": 38856,
"s": 38853,
"text": "C#"
},
{
"code": null,
"e": 38867,
"s": 38856,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define MAX_CHAR 256int kthNonRepeating(string input, int k){ int inputLength = input.length(); /* * indexArr will store index of non-repeating * characters, inputLength for characters not in input * and inputLength+1 for repeated characters. */ int indexArr[MAX_CHAR]; // initialize all values in indexArr as inputLength. for (int i = 0; i < MAX_CHAR; i++) { indexArr[i] = inputLength; } for (int i = 0; i < inputLength; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } sort(indexArr, indexArr + MAX_CHAR); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1;} int main(){ string input = \"geeksforgeeks\"; int k = 3; int res = kthNonRepeating(input, k); if (res == -1) cout << \"There are less than k non-repeating \" \"characters\"; else cout << \"k'th non-repeating character is \" << input[res]; return 0;} // This code is contributed by gauravrajput1",
"e": 40035,
"s": 38867,
"text": null
},
{
"code": "import java.util.*; public class GFG { public static int MAX_CHAR = 256; public static void main (String[] args) { final String input = \"geeksforgeeks\"; int k = 3; int res = kthNonRepeating(input, k); System.out.println(res == -1 ? \"There are less than k non-repeating characters\" : \"k'th non-repeating character is \" + input.charAt(res)); } public static int kthNonRepeating(final String input, final int k) { final int inputLength = input.length(); /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ final int[] indexArr = new int[MAX_CHAR]; // initialize all values in indexArr as inputLength. Arrays.fill(indexArr, inputLength); for (int i = 0; i < inputLength ; i++) { final char c = input.charAt(i); if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } Arrays.sort(indexArr); return (indexArr[k-1] != inputLength) ? indexArr[k-1] : -1; }}// Contributed by AK",
"e": 41329,
"s": 40035,
"text": null
},
{
"code": "MAX_CHAR = 256 def kthNonRepeating(Input,k): inputLength = len(Input) # indexArr will store index of non-repeating characters, # inputLength for characters not in input and # inputLength+1 for repeated characters. # initialize all values in indexArr as inputLength. indexArr = [inputLength for i in range(MAX_CHAR)] for i in range(inputLength): c = Input[i] if (indexArr[ord(c)] == inputLength): indexArr[ord(c)] = i else: indexArr[ord(c)] = inputLength + 2 indexArr.sort() if(indexArr[k - 1] != inputLength): return indexArr[k - 1] else: return -1 Input = \"geeksforgeeks\"k = 3res = kthNonRepeating(Input, k)if(res == -1): print(\"There are less than k non-repeating characters\")else: print(\"k'th non-repeating character is\", Input[res]) # This code is contributed by rag2127",
"e": 42216,
"s": 41329,
"text": null
},
{
"code": "using System; public class GFG{ public static int MAX_CHAR = 256; static public void Main () { string input = \"geeksforgeeks\"; int k = 3; int res = kthNonRepeating(input, k); Console.WriteLine(res == -1 ? \"There are less than k non-repeating characters\" : \"k'th non-repeating character is \" + input[res]); } public static int kthNonRepeating(string input, int k) { int inputLength = input.Length; /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ int[] indexArr = new int[MAX_CHAR]; // initialize all values in indexArr as inputLength. Array.Fill(indexArr, inputLength); for (int i = 0; i < inputLength ; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } Array.Sort(indexArr); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1; }} // This code is contributed by avanitrachhadiya2155",
"e": 43475,
"s": 42216,
"text": null
},
{
"code": "<script> let MAX_CHAR = 256; function kthNonRepeating(input, k){ let inputLength = input.length; /* * indexArr will store index of non-repeating characters, * inputLength for characters not in input and * inputLength+1 for repeated characters. */ let indexArr = new Array(MAX_CHAR); // initialize all values in indexArr as inputLength. for(let i=0;i<MAX_CHAR;i++) { indexArr[i]=inputLength; } for (let i = 0; i < inputLength ; i++) { let c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } (indexArr).sort(function(a,b){return a-b;}); return (indexArr[k-1] != inputLength) ? indexArr[k-1] : -1;} let input = \"geeksforgeeks\";let k = 3;let res = kthNonRepeating(input, k);document.write(res == -1 ? \"There are less than k non-repeating characters\" : \"k'th non-repeating character is \" + input[res]); // This code is contributed by unknown2108</script>",
"e": 44632,
"s": 43475,
"text": null
},
{
"code": null,
"e": 44667,
"s": 44632,
"text": "k'th non-repeating character is r"
},
{
"code": null,
"e": 45060,
"s": 44669,
"text": "This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 45073,
"s": 45060,
"text": "nitin mittal"
},
{
"code": null,
"e": 45079,
"s": 45073,
"text": "ukasp"
},
{
"code": null,
"e": 45098,
"s": 45079,
"text": "abhishekkumarnitrr"
},
{
"code": null,
"e": 45119,
"s": 45098,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 45127,
"s": 45119,
"text": "rag2127"
},
{
"code": null,
"e": 45134,
"s": 45127,
"text": "ab2127"
},
{
"code": null,
"e": 45146,
"s": 45134,
"text": "unknown2108"
},
{
"code": null,
"e": 45160,
"s": 45146,
"text": "GauravRajput1"
},
{
"code": null,
"e": 45168,
"s": 45160,
"text": "Strings"
},
{
"code": null,
"e": 45176,
"s": 45168,
"text": "Strings"
},
{
"code": null,
"e": 45274,
"s": 45176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45283,
"s": 45274,
"text": "Comments"
},
{
"code": null,
"e": 45296,
"s": 45283,
"text": "Old Comments"
},
{
"code": null,
"e": 45341,
"s": 45296,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 45353,
"s": 45341,
"text": "Hill Cipher"
},
{
"code": null,
"e": 45391,
"s": 45353,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 45408,
"s": 45391,
"text": "VigeneΜre Cipher"
},
{
"code": null,
"e": 45451,
"s": 45408,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 45492,
"s": 45451,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 45534,
"s": 45492,
"text": "Reverse words in a given String in Python"
},
{
"code": null,
"e": 45579,
"s": 45534,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 45594,
"s": 45579,
"text": "sprintf() in C"
}
] |
Running Jupyter Notebooks on Remote Servers | by Tobias Skovgaard Jepsen | Towards Data Science
|
Jupyter Notebook is a staple tool in many data scientistsβ toolkit. As a tool, Jupyter Notebook can enhance productivity by making it easier to perform data analysis, model prototyping, and experiments in an interactive way, thus shortening the feedback loop from coding and seeing results.
In many cases, running a Jupyter notebook on a laptop or work station is sufficient. However, if youβre working with large datasets, doing computationally expensive data processing, or learning complex models you probably need something more powerful than a laptop extra power. Maybe youβre running graph convolutional networks on large graphs or doing machine translation with recurrent neural networks on large text corpora and need some more CPU cores, RAM, or a couple of GPUs. Luckily, you may be in the situation where you have these resources available on a remote server!
If your remote server has a Graphical User Interface (GUI), you are in luck. You can use remote desktop software to access the remote server and otherwise use Jupyter Notebook as your normally would on your laptop.
However, many servers do not have a GUI. If you are in this situation, you can set up your experiment by writing a Python script on your laptop, run it on a small subset of your data to verify that it can run, copy it to a remote server, and execute it from the command line. You could even set up the experiment in a notebook and export the notebook to a script using jupyter nbconvert --to script your_notebook.ipynb. Although this workflow certainly allows you to run your code on the remote server, you can no longer use Jupyter Notebook to, e.g., experiment with your models and visualize your results interactively. What a shame!
In this post I will show you how to run a Jupyter notebook on a remote server and how to access it on your laptop. I will also show how to setup two bash commands to make the whole process easier.
We will use the Secure Shell Protocol (SSH) to start the Jupyter Notebook server on the remote server. SSH allows us to send commands to the remote server. The basic syntax is as follows:
ssh username:password@remote_server_ip command
The exact command you should send depends a little on your context. In my case, I share a remote server with other people have therefore not installed Jupyter in the shared environment. The first step for me is therefore to go to my project folder, activate the virtual environment, and start the notebook server. In particular, I would like to execute the following threebash commands on the remote server:
cd project_folder. virtual_environment/bin/activatejupyter notebook --no-browser --port=8889
I execute the jupyter notebook command with the --no-browser flag to start the Jupyter notebook with launching a browser since the remote server cannot display a browser if it doesnβt have a GUI. I also change the port from the default port 8888 to port 8889 using the --port=8889 flag. This is a personal preference; having local and remote notebooks on different ports to make it easier to see where my code is running.
To execute commands on the remote server, we run the combined command
nohup ssh -f username:password@remote_server_ip "cd project_folder; . virtual_environment/bin/activate; jupyter notebook --no-browser --port=8889"
Note that I have one-lined the three commands and separated them using ; instead of line breaks. Executing this command will start the Jupyter Notebook server on port 8889 and let it run in the background. Finally, I have added the -f flag to the ssh command to push the process to the background and prepended the nohup command to silence all output from the process so you can continue using the terminal window. You can read more about thenohup command here.
You can now access the notebook typing in the url
remote_server_ip:8889
This command requires you to memorise the IP address or to bookmark the web page. However, we can make it just as easy to access the remote notebook as if it were a local notebook by using port forwarding:
nohup ssh -N -f -L localhost:8889:localhost:8889 username:password@remote_server_ip
The -N flag tells ssh that no remote commands will be executed. At this point we do not need to execute any remote commands. The -f flag pushes the ssh process to the background as mentioned previously. Finally, the -L flag specifies the port forwarding configuration using the syntax local_server:local_port:remote_server:remote_port. The configuration specifies that all requests sent to port 8889 on the local machine, e.g., your laptop, to port 8889 on the remote machine at username:password@remote_server_ip. As before, the nohup command has been prepended to silence the output.
The effect the above command is that you can now access the remote Jupyter Notebook server in your browser at
localhost:8889
as if you ran the notebook locally.
In principle, you can let the notebook server run indefinitely on the remote server (barring restarts or crashes), but you may need to stop the server, for instance to upgrade your version of jupyter. If you need to stop it there are two ways to do so: through the browser or through the command line.
In the recent versions of the Jupyter Notebook, you can find a Quit button at the top right of the browser window as indicated by the arrow in the image below. If you press it, you will have to relaunch the server again using the start-up command we saw previously.
If you are unable to upgrade to a newer version of Jupyter that has the Quit button or simply prefer working through a terminal, you can also stop the server from the command line. Jupyter has a shell command to stop notebooks:
jupyter notebook stop 8889
where 8889 is the port number. You can execute it on the remote server using the command
ssh username:password@remote_server_ip "jupyter notebook stop 8889"
Unfortunately, this command is currently bugged, but I have included it here in the hopes that it will work in the future. However, as a work-around you can instead kill the jupyter process instead using the command:
ssh username:password@remote_server_ip "pkill -u username jupyter"
where the -u username indicates that only jupyter processes started by username should be killed. The drawback of doing this is that you will shutdown all of your notebook servers if you have more than one running at a time. Finally, you can of course manage the servers manually by logging on to the remote server, starting the notebook server, and keeping the terminal window open. This allows you to shutdown the notebook server using the usual CTRL+C keyboard command.
Remembering all these commands can be quite cumbersome. Thankfully, we can make life easier by creating bash aliases for each of the commands. Add the following lines to your ~/.bashrc file:
Load the commands by typing source .bashrc in your terminal. You can now use the commands remote_notebook_start and remote_notebook_stop in your terminal to respectively start the remote notebook server (and setup port forwarding) and shut it down.
In this post I have shown you how to start, access, and stop Jupyter notebooks on remote servers using bash commands and shown how to create bash aliases to make it easy to do so.
I hope that these commands can improve your data science productivity by nearly seamlessly allowing you to reap the benefits of both Jupyter notebook and any computing resources you have available on remote servers.
Liked what you read? Consider following me on Twitter where I share papers, videos, and articles related to the practice, theory, and ethics of data science and machine learning that I find interesting, in addition to my own posts.
For professional inquiries, please contact me on LinkedIn or by direct message on Twitter.
|
[
{
"code": null,
"e": 462,
"s": 171,
"text": "Jupyter Notebook is a staple tool in many data scientistsβ toolkit. As a tool, Jupyter Notebook can enhance productivity by making it easier to perform data analysis, model prototyping, and experiments in an interactive way, thus shortening the feedback loop from coding and seeing results."
},
{
"code": null,
"e": 1042,
"s": 462,
"text": "In many cases, running a Jupyter notebook on a laptop or work station is sufficient. However, if youβre working with large datasets, doing computationally expensive data processing, or learning complex models you probably need something more powerful than a laptop extra power. Maybe youβre running graph convolutional networks on large graphs or doing machine translation with recurrent neural networks on large text corpora and need some more CPU cores, RAM, or a couple of GPUs. Luckily, you may be in the situation where you have these resources available on a remote server!"
},
{
"code": null,
"e": 1257,
"s": 1042,
"text": "If your remote server has a Graphical User Interface (GUI), you are in luck. You can use remote desktop software to access the remote server and otherwise use Jupyter Notebook as your normally would on your laptop."
},
{
"code": null,
"e": 1893,
"s": 1257,
"text": "However, many servers do not have a GUI. If you are in this situation, you can set up your experiment by writing a Python script on your laptop, run it on a small subset of your data to verify that it can run, copy it to a remote server, and execute it from the command line. You could even set up the experiment in a notebook and export the notebook to a script using jupyter nbconvert --to script your_notebook.ipynb. Although this workflow certainly allows you to run your code on the remote server, you can no longer use Jupyter Notebook to, e.g., experiment with your models and visualize your results interactively. What a shame!"
},
{
"code": null,
"e": 2090,
"s": 1893,
"text": "In this post I will show you how to run a Jupyter notebook on a remote server and how to access it on your laptop. I will also show how to setup two bash commands to make the whole process easier."
},
{
"code": null,
"e": 2278,
"s": 2090,
"text": "We will use the Secure Shell Protocol (SSH) to start the Jupyter Notebook server on the remote server. SSH allows us to send commands to the remote server. The basic syntax is as follows:"
},
{
"code": null,
"e": 2325,
"s": 2278,
"text": "ssh username:password@remote_server_ip command"
},
{
"code": null,
"e": 2733,
"s": 2325,
"text": "The exact command you should send depends a little on your context. In my case, I share a remote server with other people have therefore not installed Jupyter in the shared environment. The first step for me is therefore to go to my project folder, activate the virtual environment, and start the notebook server. In particular, I would like to execute the following threebash commands on the remote server:"
},
{
"code": null,
"e": 2826,
"s": 2733,
"text": "cd project_folder. virtual_environment/bin/activatejupyter notebook --no-browser --port=8889"
},
{
"code": null,
"e": 3248,
"s": 2826,
"text": "I execute the jupyter notebook command with the --no-browser flag to start the Jupyter notebook with launching a browser since the remote server cannot display a browser if it doesnβt have a GUI. I also change the port from the default port 8888 to port 8889 using the --port=8889 flag. This is a personal preference; having local and remote notebooks on different ports to make it easier to see where my code is running."
},
{
"code": null,
"e": 3318,
"s": 3248,
"text": "To execute commands on the remote server, we run the combined command"
},
{
"code": null,
"e": 3465,
"s": 3318,
"text": "nohup ssh -f username:password@remote_server_ip \"cd project_folder; . virtual_environment/bin/activate; jupyter notebook --no-browser --port=8889\""
},
{
"code": null,
"e": 3927,
"s": 3465,
"text": "Note that I have one-lined the three commands and separated them using ; instead of line breaks. Executing this command will start the Jupyter Notebook server on port 8889 and let it run in the background. Finally, I have added the -f flag to the ssh command to push the process to the background and prepended the nohup command to silence all output from the process so you can continue using the terminal window. You can read more about thenohup command here."
},
{
"code": null,
"e": 3977,
"s": 3927,
"text": "You can now access the notebook typing in the url"
},
{
"code": null,
"e": 3999,
"s": 3977,
"text": "remote_server_ip:8889"
},
{
"code": null,
"e": 4205,
"s": 3999,
"text": "This command requires you to memorise the IP address or to bookmark the web page. However, we can make it just as easy to access the remote notebook as if it were a local notebook by using port forwarding:"
},
{
"code": null,
"e": 4289,
"s": 4205,
"text": "nohup ssh -N -f -L localhost:8889:localhost:8889 username:password@remote_server_ip"
},
{
"code": null,
"e": 4875,
"s": 4289,
"text": "The -N flag tells ssh that no remote commands will be executed. At this point we do not need to execute any remote commands. The -f flag pushes the ssh process to the background as mentioned previously. Finally, the -L flag specifies the port forwarding configuration using the syntax local_server:local_port:remote_server:remote_port. The configuration specifies that all requests sent to port 8889 on the local machine, e.g., your laptop, to port 8889 on the remote machine at username:password@remote_server_ip. As before, the nohup command has been prepended to silence the output."
},
{
"code": null,
"e": 4985,
"s": 4875,
"text": "The effect the above command is that you can now access the remote Jupyter Notebook server in your browser at"
},
{
"code": null,
"e": 5000,
"s": 4985,
"text": "localhost:8889"
},
{
"code": null,
"e": 5036,
"s": 5000,
"text": "as if you ran the notebook locally."
},
{
"code": null,
"e": 5338,
"s": 5036,
"text": "In principle, you can let the notebook server run indefinitely on the remote server (barring restarts or crashes), but you may need to stop the server, for instance to upgrade your version of jupyter. If you need to stop it there are two ways to do so: through the browser or through the command line."
},
{
"code": null,
"e": 5604,
"s": 5338,
"text": "In the recent versions of the Jupyter Notebook, you can find a Quit button at the top right of the browser window as indicated by the arrow in the image below. If you press it, you will have to relaunch the server again using the start-up command we saw previously."
},
{
"code": null,
"e": 5832,
"s": 5604,
"text": "If you are unable to upgrade to a newer version of Jupyter that has the Quit button or simply prefer working through a terminal, you can also stop the server from the command line. Jupyter has a shell command to stop notebooks:"
},
{
"code": null,
"e": 5859,
"s": 5832,
"text": "jupyter notebook stop 8889"
},
{
"code": null,
"e": 5948,
"s": 5859,
"text": "where 8889 is the port number. You can execute it on the remote server using the command"
},
{
"code": null,
"e": 6016,
"s": 5948,
"text": "ssh username:password@remote_server_ip \"jupyter notebook stop 8889\""
},
{
"code": null,
"e": 6233,
"s": 6016,
"text": "Unfortunately, this command is currently bugged, but I have included it here in the hopes that it will work in the future. However, as a work-around you can instead kill the jupyter process instead using the command:"
},
{
"code": null,
"e": 6300,
"s": 6233,
"text": "ssh username:password@remote_server_ip \"pkill -u username jupyter\""
},
{
"code": null,
"e": 6773,
"s": 6300,
"text": "where the -u username indicates that only jupyter processes started by username should be killed. The drawback of doing this is that you will shutdown all of your notebook servers if you have more than one running at a time. Finally, you can of course manage the servers manually by logging on to the remote server, starting the notebook server, and keeping the terminal window open. This allows you to shutdown the notebook server using the usual CTRL+C keyboard command."
},
{
"code": null,
"e": 6964,
"s": 6773,
"text": "Remembering all these commands can be quite cumbersome. Thankfully, we can make life easier by creating bash aliases for each of the commands. Add the following lines to your ~/.bashrc file:"
},
{
"code": null,
"e": 7213,
"s": 6964,
"text": "Load the commands by typing source .bashrc in your terminal. You can now use the commands remote_notebook_start and remote_notebook_stop in your terminal to respectively start the remote notebook server (and setup port forwarding) and shut it down."
},
{
"code": null,
"e": 7393,
"s": 7213,
"text": "In this post I have shown you how to start, access, and stop Jupyter notebooks on remote servers using bash commands and shown how to create bash aliases to make it easy to do so."
},
{
"code": null,
"e": 7609,
"s": 7393,
"text": "I hope that these commands can improve your data science productivity by nearly seamlessly allowing you to reap the benefits of both Jupyter notebook and any computing resources you have available on remote servers."
},
{
"code": null,
"e": 7841,
"s": 7609,
"text": "Liked what you read? Consider following me on Twitter where I share papers, videos, and articles related to the practice, theory, and ethics of data science and machine learning that I find interesting, in addition to my own posts."
}
] |
C - Header Files & Preprocessor Directives - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about C Header Files & Preprocessor Directives.
Humans and computers communicate using input/output devices.
Programming languages facilitate such communication through I/O operations like reading input from the keyboard, displaying output on screens, writing to files, printers, etc.
C language provides many functions to perform, read, and write operations for the I/O devices. These functions are made available in files (usually written with .h extension) referred to, as header files.
Standard I/O library functions are available in a file named stdio.h (standard input output header file).
C language provides a collection of such header files which form the C standard library. These files are usually available in operating systems like Linux by default.
Programmers can also create their own header files which are usually referred to as user-defined header files.
As mentioned earlier, there is a file called stdio.h among the header files present in C standard library, which contains the most commonly used functions to print data to console and to read (also called scan) data.
In order to use the functions available in the header file stdio.h, the following line has to be used in a program:
#include <stdio.h>
It makes the contents of the header file available to the compiler and the linker during the execution of programs.
Now letβs understand some preprocessor directives,
The header files are included in a program using the #include directive.
The header files can be included using #include in two ways as follows:
#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.
#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.
#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.
#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.
#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.
#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.
#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.
#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.
Given below is the most commonly included header file which contains the standard input/output functions like, printf(), scanf(), etc.
#include <stdio.h>
Here, the symbol # is called the preprocessor directive, include is called the command, and stdio.h is the header file.
Note: Some compilers automatically include stdio.h. While using compilers that do not automatically include stdio.h, programmers have to explicitly write the include statement in their programs to avoid compilation errors.
In programming terminology, a macro is a pattern or a rule which specifies how a certain sequence of text should be replaced.
C allows us to define two types of macros using the preprocessor directive #define as shown below:
#define PI 3.14
#define MIN(a, b) ((a) < (b)? (a) : (b))
#define PI 3.14
#define MIN(a, b) ((a) < (b)? (a) : (b))
The first type of substitution has been discussed while learning about symbolic constant.
The second type can be used to define a rule or a function that works on given arguments.
Given below is the general syntax for declaring macros using #define:
#define macro_name replacement_text
#define macro_name(arg_1, arg_2... arg_n) function_expression
Consider the following example that swaps the values of two variables using #define macro.
#include
#define SWAP(a, b, c){c t; t=a; a=b; b=t;}
int main()
{
int x=10, y=20;
SWAP(x, y, int);
printf("%d %d\n", x, y);
return 0;
}
Output:
20 10
Here, SWAP(a, b, tempo) is the name of the macro with three arguments that are replaced with the macro body: (tempo = a, a = b, b = temp0).
C provides a special concatenation operator ## which can be used in a #define directive as shown below:
#define CONCAT(X, Y) X##Y
The ## operator concatenates the values in X and Y forming a single sequence.
For example, CONCAT (20, 21) will result in 2021.
In C, a programmer can instruct the preprocessor whether or not to include a certain section of the code. This is accomplished using conditional directives.
These are similar to if statements in syntax and usage. However, unlike if statements that are executed during runtime, the conditional directives are executed before compilation by the preprocessor.
These directives are used whenever there is a need to compile a portion of the program conditionally. It is also known as conditional compilation.
The most common conditional directive #ifdef (spelled as if-defined) verifies if a given identifier is defined or not.
The syntax for its usage is :
#ifdef identifier or #if defined (identifier)
The source code following #ifdef will be compiled only if the given identifier is defined either in the code or if it is provided as a compilation option as -Didentifier_name.
The opposite of #ifdef is #ifndef, which is written as
#ifndef identifier or #if !defined (identifier)
Consider the following example:
#if defined (MAX)
#define MIN 30
#else
#define MAX 100
#define MIN 200
#endif
Here, MIN 30 will be defined only if the constant MAX is defined earlier than MIN 30. Else, both MAX and MIN will be defined with values 100 and 200 respectively.
Similar to the if-else-if construct, we have a #if-#elif which is used in creating a chain of #if-else statements that can be used to conditionally compile a portion of code.
The general syntax for #if, #elif, #else, #endif is given below:
#if expression1
statement_block1;
#elif expression2
statement_block2;
#elif expression3
statement_block3;
#else
statement_block4;
#endif
The #undef directive βundefinesβ a symbolic constant or a macro identifier that has been defined earlier; i.e., it negates the effects of a #define directive that may have appeared earlier in the program.
The #undef directive is used to remove values defined by #define directives so that they can be redefined with new values.
The format of #undef is
#undef symbolic_name
Given below is an example for #undef:
#include <stdio.h>
#define TEMP 20
int main() {
printf("%d\n", TEMP);
#ifdef TEMP
#undef TEMP
#define TEMP 99
#else
#define TEMP 999
#endif
printf("%d\n", TEMP);
return 0;
}
Output:
20
99
Here, the code first prints 20 and then prints99.
Wiki β C standard Library
Wiki β Header Files
Wiki β include directive
Wiki β Special macros and directives
Happy Learning
Understanding the structure of a C Program
How add files to S3 Bucket using Shell Script
AngularJs Directive Example Tutorials
How to Copy Local Files to AWS EC2 instance Manually ?
Rules to define Python Identifiers
C β Derived and User Defined Data Types
Java 8 walk How to Read all files in a folder
Pandas read_excel β Read Excel files in Pandas
Variables & Keywords in C Language
Java How to create Jar File ?
How to add dynamic files to JTree
C β Integer Data Types β int, short int, long int and char
Step by Step Tutorials AngularJs Example
php readfile Example Tutorials
Step by Step β How to push the project into GIT Repository
Understanding the structure of a C Program
How add files to S3 Bucket using Shell Script
AngularJs Directive Example Tutorials
How to Copy Local Files to AWS EC2 instance Manually ?
Rules to define Python Identifiers
C β Derived and User Defined Data Types
Java 8 walk How to Read all files in a folder
Pandas read_excel β Read Excel files in Pandas
Variables & Keywords in C Language
Java How to create Jar File ?
How to add dynamic files to JTree
C β Integer Data Types β int, short int, long int and char
Step by Step Tutorials AngularJs Example
php readfile Example Tutorials
Step by Step β How to push the project into GIT Repository
Ξ
C β Introduction
C β Features
C β Variables & Keywords
C β Program Structure
C β Comment Lines & Tokens
C β Number System
C β Local and Global Variables
C β Scope & Lifetime of Variables
C β Data Types
C β Integer Data Types
C β Floating Data Types
C β Derived, Defined Data Types
C β Type Conversions
C β Arithmetic Operators
C β Bitwise Operators
C β Logical Operators
C β Comma and sizeof Operators
C β Operator Precedence and Associativity
C β Relational Operators
C Flow Control β if, if-else, nested if-else, if-else-if
C β Switch Case
C Iterative β for, while, dowhile loops
C Unconditional β break, continue, goto statements
C β Expressions and Statements
C β Header Files & Preprocessor Directives
C β One Dimensional Arrays
C β Multi Dimensional Arrays
C β Pointers Basics
C β Pointers with Arrays
C β Functions
C β How to Pass Arrays to Functions
C β Categories of Functions
C β User defined Functions
C β Formal and Actual Arguments
C β Recursion functions
C β Structures Part -1
C β Structures Part -2
C β Unions
C β File Handling
C β File Operations
C β Dynamic Memory Allocation
C Program β Fibonacci Series
C Program β Prime or Not
C Program β Factorial of Number
C Program β Even or Odd
C Program β Sum of digits till Single Digit
C Program β Sum of digits
C Program β Reverse of a number
C Program β Armstrong Numbers
C Program β Print prime Numbers
C Program β GCD of two Numbers
C Program β Number Palindrome or Not
C Program β Find Largest and Smallest number in an Array
C Program β Add elements of an Array
C Program β Addition of Matrices
C Program β Multiplication of Matrices
C Program β Reverse of an Array
C Program β Bubble Sort
C Program β Add and Sub without using + β
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 486,
"s": 398,
"text": "In this tutorial, we are going to learn about C Header Files & Preprocessor Directives."
},
{
"code": null,
"e": 547,
"s": 486,
"text": "Humans and computers communicate using input/output devices."
},
{
"code": null,
"e": 723,
"s": 547,
"text": "Programming languages facilitate such communication through I/O operations like reading input from the keyboard, displaying output on screens, writing to files, printers, etc."
},
{
"code": null,
"e": 928,
"s": 723,
"text": "C language provides many functions to perform, read, and write operations for the I/O devices. These functions are made available in files (usually written with .h extension) referred to, as header files."
},
{
"code": null,
"e": 1034,
"s": 928,
"text": "Standard I/O library functions are available in a file named stdio.h (standard input output header file)."
},
{
"code": null,
"e": 1201,
"s": 1034,
"text": "C language provides a collection of such header files which form the C standard library. These files are usually available in operating systems like Linux by default."
},
{
"code": null,
"e": 1312,
"s": 1201,
"text": "Programmers can also create their own header files which are usually referred to as user-defined header files."
},
{
"code": null,
"e": 1529,
"s": 1312,
"text": "As mentioned earlier, there is a file called stdio.h among the header files present in C standard library, which contains the most commonly used functions to print data to console and to read (also called scan) data."
},
{
"code": null,
"e": 1645,
"s": 1529,
"text": "In order to use the functions available in the header file stdio.h, the following line has to be used in a program:"
},
{
"code": null,
"e": 1664,
"s": 1645,
"text": "#include <stdio.h>"
},
{
"code": null,
"e": 1780,
"s": 1664,
"text": "It makes the contents of the header file available to the compiler and the linker during the execution of programs."
},
{
"code": null,
"e": 1831,
"s": 1780,
"text": "Now letβs understand some preprocessor directives,"
},
{
"code": null,
"e": 1904,
"s": 1831,
"text": "The header files are included in a program using the #include directive."
},
{
"code": null,
"e": 1976,
"s": 1904,
"text": "The header files can be included using #include in two ways as follows:"
},
{
"code": null,
"e": 2374,
"s": 1976,
"text": "\n\n\n#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.\n#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.\n\n\n"
},
{
"code": null,
"e": 2770,
"s": 2374,
"text": "\n\n#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.\n#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.\n\n"
},
{
"code": null,
"e": 3164,
"s": 2770,
"text": "\n#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories.\n#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths.\n"
},
{
"code": null,
"e": 3370,
"s": 3164,
"text": "#include <header_file_name.h>: This variant is used to include system header files made available in C standard library. The compiler searches for the named file in the standard list of system directories."
},
{
"code": null,
"e": 3556,
"s": 3370,
"text": "#include βheader_file_name.hβ: This variant is commonly used to include user-defined header files. The compiler searches for the named files only in the local or project-specific paths."
},
{
"code": null,
"e": 3691,
"s": 3556,
"text": "Given below is the most commonly included header file which contains the standard input/output functions like, printf(), scanf(), etc."
},
{
"code": null,
"e": 3711,
"s": 3691,
"text": "#include <stdio.h>\n"
},
{
"code": null,
"e": 3831,
"s": 3711,
"text": "Here, the symbol # is called the preprocessor directive, include is called the command, and stdio.h is the header file."
},
{
"code": null,
"e": 4054,
"s": 3831,
"text": "Note: Some compilers automatically include stdio.h. While using compilers that do not automatically include stdio.h, programmers have to explicitly write the include statement in their programs to avoid compilation errors."
},
{
"code": null,
"e": 4180,
"s": 4054,
"text": "In programming terminology, a macro is a pattern or a rule which specifies how a certain sequence of text should be replaced."
},
{
"code": null,
"e": 4279,
"s": 4180,
"text": "C allows us to define two types of macros using the preprocessor directive #define as shown below:"
},
{
"code": null,
"e": 4338,
"s": 4279,
"text": "\n#define PI 3.14\n#define MIN(a, b) ((a) < (b)? (a) : (b))\n"
},
{
"code": null,
"e": 4354,
"s": 4338,
"text": "#define PI 3.14"
},
{
"code": null,
"e": 4395,
"s": 4354,
"text": "#define MIN(a, b) ((a) < (b)? (a) : (b))"
},
{
"code": null,
"e": 4485,
"s": 4395,
"text": "The first type of substitution has been discussed while learning about symbolic constant."
},
{
"code": null,
"e": 4575,
"s": 4485,
"text": "The second type can be used to define a rule or a function that works on given arguments."
},
{
"code": null,
"e": 4645,
"s": 4575,
"text": "Given below is the general syntax for declaring macros using #define:"
},
{
"code": null,
"e": 4743,
"s": 4645,
"text": "#define macro_name replacement_text\n#define macro_name(arg_1, arg_2... arg_n) function_expression"
},
{
"code": null,
"e": 4834,
"s": 4743,
"text": "Consider the following example that swaps the values of two variables using #define macro."
},
{
"code": null,
"e": 4974,
"s": 4834,
"text": "#include\n#define SWAP(a, b, c){c t; t=a; a=b; b=t;}\nint main()\n{\n int x=10, y=20;\n SWAP(x, y, int);\n printf(\"%d %d\\n\", x, y);\n return 0;\n}\n"
},
{
"code": null,
"e": 4982,
"s": 4974,
"text": "Output:"
},
{
"code": null,
"e": 4988,
"s": 4982,
"text": "20 10"
},
{
"code": null,
"e": 5128,
"s": 4988,
"text": "Here, SWAP(a, b, tempo) is the name of the macro with three arguments that are replaced with the macro body: (tempo = a, a = b, b = temp0)."
},
{
"code": null,
"e": 5232,
"s": 5128,
"text": "C provides a special concatenation operator ## which can be used in a #define directive as shown below:"
},
{
"code": null,
"e": 5258,
"s": 5232,
"text": "#define CONCAT(X, Y) X##Y"
},
{
"code": null,
"e": 5336,
"s": 5258,
"text": "The ## operator concatenates the values in X and Y forming a single sequence."
},
{
"code": null,
"e": 5386,
"s": 5336,
"text": "For example, CONCAT (20, 21) will result in 2021."
},
{
"code": null,
"e": 5543,
"s": 5386,
"text": "In C, a programmer can instruct the preprocessor whether or not to include a certain section of the code. This is accomplished using conditional directives."
},
{
"code": null,
"e": 5743,
"s": 5543,
"text": "These are similar to if statements in syntax and usage. However, unlike if statements that are executed during runtime, the conditional directives are executed before compilation by the preprocessor."
},
{
"code": null,
"e": 5890,
"s": 5743,
"text": "These directives are used whenever there is a need to compile a portion of the program conditionally. It is also known as conditional compilation."
},
{
"code": null,
"e": 6039,
"s": 5890,
"text": "The most common conditional directive #ifdef (spelled as if-defined) verifies if a given identifier is defined or not.\nThe syntax for its usage is :"
},
{
"code": null,
"e": 6085,
"s": 6039,
"text": "#ifdef identifier or #if defined (identifier)"
},
{
"code": null,
"e": 6261,
"s": 6085,
"text": "The source code following #ifdef will be compiled only if the given identifier is defined either in the code or if it is provided as a compilation option as -Didentifier_name."
},
{
"code": null,
"e": 6316,
"s": 6261,
"text": "The opposite of #ifdef is #ifndef, which is written as"
},
{
"code": null,
"e": 6364,
"s": 6316,
"text": "#ifndef identifier or #if !defined (identifier)"
},
{
"code": null,
"e": 6396,
"s": 6364,
"text": "Consider the following example:"
},
{
"code": null,
"e": 6486,
"s": 6396,
"text": "#if defined (MAX)\n #define MIN 30\n#else\n #define MAX 100\n #define MIN 200\n#endif"
},
{
"code": null,
"e": 6649,
"s": 6486,
"text": "Here, MIN 30 will be defined only if the constant MAX is defined earlier than MIN 30. Else, both MAX and MIN will be defined with values 100 and 200 respectively."
},
{
"code": null,
"e": 6824,
"s": 6649,
"text": "Similar to the if-else-if construct, we have a #if-#elif which is used in creating a chain of #if-else statements that can be used to conditionally compile a portion of code."
},
{
"code": null,
"e": 6889,
"s": 6824,
"text": "The general syntax for #if, #elif, #else, #endif is given below:"
},
{
"code": null,
"e": 7042,
"s": 6889,
"text": "#if expression1\n statement_block1;\n#elif expression2\n statement_block2;\n#elif expression3\n statement_block3;\n#else\n statement_block4;\n#endif"
},
{
"code": null,
"e": 7247,
"s": 7042,
"text": "The #undef directive βundefinesβ a symbolic constant or a macro identifier that has been defined earlier; i.e., it negates the effects of a #define directive that may have appeared earlier in the program."
},
{
"code": null,
"e": 7370,
"s": 7247,
"text": "The #undef directive is used to remove values defined by #define directives so that they can be redefined with new values."
},
{
"code": null,
"e": 7394,
"s": 7370,
"text": "The format of #undef is"
},
{
"code": null,
"e": 7415,
"s": 7394,
"text": "#undef symbolic_name"
},
{
"code": null,
"e": 7453,
"s": 7415,
"text": "Given below is an example for #undef:"
},
{
"code": null,
"e": 7640,
"s": 7453,
"text": "#include <stdio.h>\n#define TEMP 20\nint main() {\n\tprintf(\"%d\\n\", TEMP);\n\t#ifdef TEMP\n\t\t#undef TEMP\n\t\t#define TEMP 99\n\t#else\n\t\t#define TEMP 999\n\t#endif\n\n\tprintf(\"%d\\n\", TEMP);\n\treturn 0;\n}"
},
{
"code": null,
"e": 7648,
"s": 7640,
"text": "Output:"
},
{
"code": null,
"e": 7654,
"s": 7648,
"text": "20\n99"
},
{
"code": null,
"e": 7704,
"s": 7654,
"text": "Here, the code first prints 20 and then prints99."
},
{
"code": null,
"e": 7730,
"s": 7704,
"text": "Wiki β C standard Library"
},
{
"code": null,
"e": 7750,
"s": 7730,
"text": "Wiki β Header Files"
},
{
"code": null,
"e": 7775,
"s": 7750,
"text": "Wiki β include directive"
},
{
"code": null,
"e": 7813,
"s": 7775,
"text": "Wiki β Special macros and directives "
},
{
"code": null,
"e": 7829,
"s": 7813,
"text": "Happy Learning "
},
{
"code": null,
"e": 8470,
"s": 7829,
"text": "\nUnderstanding the structure of a C Program\nHow add files to S3 Bucket using Shell Script\nAngularJs Directive Example Tutorials\nHow to Copy Local Files to AWS EC2 instance Manually ?\nRules to define Python Identifiers\nC β Derived and User Defined Data Types\nJava 8 walk How to Read all files in a folder\nPandas read_excel β Read Excel files in Pandas\nVariables & Keywords in C Language\nJava How to create Jar File ?\nHow to add dynamic files to JTree\nC β Integer Data Types β int, short int, long int and char\nStep by Step Tutorials AngularJs Example\nphp readfile Example Tutorials\nStep by Step β How to push the project into GIT Repository\n"
},
{
"code": null,
"e": 8513,
"s": 8470,
"text": "Understanding the structure of a C Program"
},
{
"code": null,
"e": 8559,
"s": 8513,
"text": "How add files to S3 Bucket using Shell Script"
},
{
"code": null,
"e": 8597,
"s": 8559,
"text": "AngularJs Directive Example Tutorials"
},
{
"code": null,
"e": 8652,
"s": 8597,
"text": "How to Copy Local Files to AWS EC2 instance Manually ?"
},
{
"code": null,
"e": 8687,
"s": 8652,
"text": "Rules to define Python Identifiers"
},
{
"code": null,
"e": 8727,
"s": 8687,
"text": "C β Derived and User Defined Data Types"
},
{
"code": null,
"e": 8773,
"s": 8727,
"text": "Java 8 walk How to Read all files in a folder"
},
{
"code": null,
"e": 8820,
"s": 8773,
"text": "Pandas read_excel β Read Excel files in Pandas"
},
{
"code": null,
"e": 8855,
"s": 8820,
"text": "Variables & Keywords in C Language"
},
{
"code": null,
"e": 8885,
"s": 8855,
"text": "Java How to create Jar File ?"
},
{
"code": null,
"e": 8919,
"s": 8885,
"text": "How to add dynamic files to JTree"
},
{
"code": null,
"e": 8978,
"s": 8919,
"text": "C β Integer Data Types β int, short int, long int and char"
},
{
"code": null,
"e": 9019,
"s": 8978,
"text": "Step by Step Tutorials AngularJs Example"
},
{
"code": null,
"e": 9050,
"s": 9019,
"text": "php readfile Example Tutorials"
},
{
"code": null,
"e": 9109,
"s": 9050,
"text": "Step by Step β How to push the project into GIT Repository"
},
{
"code": null,
"e": 9115,
"s": 9113,
"text": "Ξ"
},
{
"code": null,
"e": 9133,
"s": 9115,
"text": " C β Introduction"
},
{
"code": null,
"e": 9147,
"s": 9133,
"text": " C β Features"
},
{
"code": null,
"e": 9173,
"s": 9147,
"text": " C β Variables & Keywords"
},
{
"code": null,
"e": 9196,
"s": 9173,
"text": " C β Program Structure"
},
{
"code": null,
"e": 9225,
"s": 9196,
"text": " C β Comment Lines & Tokens"
},
{
"code": null,
"e": 9244,
"s": 9225,
"text": " C β Number System"
},
{
"code": null,
"e": 9276,
"s": 9244,
"text": " C β Local and Global Variables"
},
{
"code": null,
"e": 9311,
"s": 9276,
"text": " C β Scope & Lifetime of Variables"
},
{
"code": null,
"e": 9327,
"s": 9311,
"text": " C β Data Types"
},
{
"code": null,
"e": 9351,
"s": 9327,
"text": " C β Integer Data Types"
},
{
"code": null,
"e": 9376,
"s": 9351,
"text": " C β Floating Data Types"
},
{
"code": null,
"e": 9409,
"s": 9376,
"text": " C β Derived, Defined Data Types"
},
{
"code": null,
"e": 9431,
"s": 9409,
"text": " C β Type Conversions"
},
{
"code": null,
"e": 9457,
"s": 9431,
"text": " C β Arithmetic Operators"
},
{
"code": null,
"e": 9480,
"s": 9457,
"text": " C β Bitwise Operators"
},
{
"code": null,
"e": 9503,
"s": 9480,
"text": " C β Logical Operators"
},
{
"code": null,
"e": 9536,
"s": 9503,
"text": " C β Comma and sizeof Operators"
},
{
"code": null,
"e": 9579,
"s": 9536,
"text": " C β Operator Precedence and Associativity"
},
{
"code": null,
"e": 9605,
"s": 9579,
"text": " C β Relational Operators"
},
{
"code": null,
"e": 9663,
"s": 9605,
"text": " C Flow Control β if, if-else, nested if-else, if-else-if"
},
{
"code": null,
"e": 9680,
"s": 9663,
"text": " C β Switch Case"
},
{
"code": null,
"e": 9721,
"s": 9680,
"text": " C Iterative β for, while, dowhile loops"
},
{
"code": null,
"e": 9773,
"s": 9721,
"text": " C Unconditional β break, continue, goto statements"
},
{
"code": null,
"e": 9805,
"s": 9773,
"text": " C β Expressions and Statements"
},
{
"code": null,
"e": 9849,
"s": 9805,
"text": " C β Header Files & Preprocessor Directives"
},
{
"code": null,
"e": 9877,
"s": 9849,
"text": " C β One Dimensional Arrays"
},
{
"code": null,
"e": 9907,
"s": 9877,
"text": " C β Multi Dimensional Arrays"
},
{
"code": null,
"e": 9928,
"s": 9907,
"text": " C β Pointers Basics"
},
{
"code": null,
"e": 9954,
"s": 9928,
"text": " C β Pointers with Arrays"
},
{
"code": null,
"e": 9969,
"s": 9954,
"text": " C β Functions"
},
{
"code": null,
"e": 10006,
"s": 9969,
"text": " C β How to Pass Arrays to Functions"
},
{
"code": null,
"e": 10035,
"s": 10006,
"text": " C β Categories of Functions"
},
{
"code": null,
"e": 10063,
"s": 10035,
"text": " C β User defined Functions"
},
{
"code": null,
"e": 10096,
"s": 10063,
"text": " C β Formal and Actual Arguments"
},
{
"code": null,
"e": 10121,
"s": 10096,
"text": " C β Recursion functions"
},
{
"code": null,
"e": 10145,
"s": 10121,
"text": " C β Structures Part -1"
},
{
"code": null,
"e": 10169,
"s": 10145,
"text": " C β Structures Part -2"
},
{
"code": null,
"e": 10181,
"s": 10169,
"text": " C β Unions"
},
{
"code": null,
"e": 10200,
"s": 10181,
"text": " C β File Handling"
},
{
"code": null,
"e": 10221,
"s": 10200,
"text": " C β File Operations"
},
{
"code": null,
"e": 10252,
"s": 10221,
"text": " C β Dynamic Memory Allocation"
},
{
"code": null,
"e": 10282,
"s": 10252,
"text": " C Program β Fibonacci Series"
},
{
"code": null,
"e": 10308,
"s": 10282,
"text": " C Program β Prime or Not"
},
{
"code": null,
"e": 10341,
"s": 10308,
"text": " C Program β Factorial of Number"
},
{
"code": null,
"e": 10366,
"s": 10341,
"text": " C Program β Even or Odd"
},
{
"code": null,
"e": 10411,
"s": 10366,
"text": " C Program β Sum of digits till Single Digit"
},
{
"code": null,
"e": 10438,
"s": 10411,
"text": " C Program β Sum of digits"
},
{
"code": null,
"e": 10471,
"s": 10438,
"text": " C Program β Reverse of a number"
},
{
"code": null,
"e": 10502,
"s": 10471,
"text": " C Program β Armstrong Numbers"
},
{
"code": null,
"e": 10535,
"s": 10502,
"text": " C Program β Print prime Numbers"
},
{
"code": null,
"e": 10567,
"s": 10535,
"text": " C Program β GCD of two Numbers"
},
{
"code": null,
"e": 10605,
"s": 10567,
"text": " C Program β Number Palindrome or Not"
},
{
"code": null,
"e": 10663,
"s": 10605,
"text": " C Program β Find Largest and Smallest number in an Array"
},
{
"code": null,
"e": 10701,
"s": 10663,
"text": " C Program β Add elements of an Array"
},
{
"code": null,
"e": 10735,
"s": 10701,
"text": " C Program β Addition of Matrices"
},
{
"code": null,
"e": 10775,
"s": 10735,
"text": " C Program β Multiplication of Matrices"
},
{
"code": null,
"e": 10808,
"s": 10775,
"text": " C Program β Reverse of an Array"
},
{
"code": null,
"e": 10833,
"s": 10808,
"text": " C Program β Bubble Sort"
}
] |
All Pandas read_html() you should know for scraping data from HTML tables | by B. Chen | Towards Data Science
|
Web scraping is the process of collecting and parsing data from the web. The Python community has come up with some pretty powerful web scrapping tools. Among them, Pandas read_html() is a quick and convenient way for scraping data from HTML tables.
In this article, youβll learn Pandas read_html() to deal with the following common problems and should help you get started with web scraping.
Reading tables from a stringReading tables from a URLReading tables from a fileParsing date columns with parse_datesExplicitly typecast with convertersMultiIndex, header, and index columnMatching a table with matchFiltering tables with attrsWorking with missing values
Reading tables from a string
Reading tables from a URL
Reading tables from a file
Parsing date columns with parse_dates
Explicitly typecast with converters
MultiIndex, header, and index column
Matching a table with match
Filtering tables with attrs
Working with missing values
Please check out Notebook for the source code.
In the first example, we are going to read an HTML table from a string.
html_string = """<table> <thead> <tr> <th>date</th> <th>name</th> <th>year</th> <th>cost</th> <th>region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Jenny</td> <td>1998</td> <td>0.2</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> <td>1992</td> <td>-1.34</td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tomas</td> <td>1982</td> <td>1.00023</td> <td>South</td> </tr> </tbody></table>"""
To read tables from a string:
dfs = pd.read_html(html_string)
Now, the result we get is not a Pandas DataFrame but a Python list. If we use the type() function we can see that:
>>> type(dfs)list
If we want to get the table, we can use the index to access it:
dfs[0]
The result looks great. Letβs take a look at the data types with dfs[0].info(). By default, columns that are numerical are cast to numeric types, for example, the year and cost columns have been cast to int64 and float64 respectively.
>>> df[0].info()RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 3 non-null object 1 name 3 non-null object 2 year 3 non-null int64 3 cost 3 non-null float64 4 region 3 non-null object dtypes: float64(1), int64(1), object(3)memory usage: 248.0+ bytes
Pandas read_html() accepts a URL. Letβs see how this works with the help of an example.
URL = 'https://en.wikipedia.org/wiki/London'dfs = pd.read_html(URL)
Same as reading from a string, it returns a list of DataFrames. If we run len(dfs) we can see that 31 tables available from the given URL.
>>> print(f'Total tables: {len(dfs)}')31
And below is an example of dfs[6]
Pandas read_html() accepts a file. Letβs see how this works with the help of an example.
file_path = 'html_string.txt'with open(file_path, 'r') as f: dfs = pd.read_html(f.read())dfs[0]
Note: The following tutorials will be reading data from a string as the web page content is unlikely to be the same over time.
The date column gets read as an object data type. To read the date column correctly, we can use the argument parse_dates to specify a list of date columns.
>>> dfs = pd.read_html(html_string, parse_dates=['date'])>>> dfs[0].info()RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 3 non-null datetime64[ns] 1 name 3 non-null object 2 year 3 non-null int64 3 cost 3 non-null float64 4 region 3 non-null object dtypes: datetime64[ns](1), float64(1), int64(1), object(2)memory usage: 248.0+ bytes
By default, columns that are numerical are cast to numeric types, for example, the year and cost columns we have seen. But not all numerical text data are necessary to be numeric types, for example, an ID column that all values have leading zero.
ID = 0001
In addition, sometimes you may want to explicitly typecast to ensure dtype integrity. For these requirements, we can do explicitly typecast with the argument converters :
dfs = pd.read_html(html_string, converters={ 'ID': str, 'year': int, 'cost': float,})
By default, <th> or <td> elements located within a <thead> are used to form the column index, if multiple rows are contained within <thead> then a Multiindex is created.
Below is an example of an HTML table with multiple rows in <thead>.
html_string = """<table> <thead> <tr> <th colspan="5">Year 2020</th> </tr> <tr> <th>date</th> <th>name</th> <th>year</th> <th>cost</th> <th>region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Jenny</td> <td>1998</td> <td>1.2</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> <td>1992</td> <td>-1.34</td> <td>East</td> </tr> </tbody></table>"""
It creates MultiIndex because there are multiple rows in <thead>
dfs = pd.read_html(html_string)dfs[0]
Specify a header row:
dfs = pd.read_html(html_string, header=1)dfs[0]
Specify an index column:
dfs = pd.read_html(html_string, header=1, index_col=0)dfs[0]
The argument match takes a string or a regular expression. The value defaults to .+ (match any non-empty string) and will return all tables.
Letβs see how this works with the help of an example.
html_string = """<table id="report"> <caption>2020 report</caption> <thead> <tr> <th>date</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Jenny</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> </tr> </tbody></table><table> <caption>Average income</caption> <thead> <tr> <th>name</th> <th>income</th> </tr> </thead> <tbody> <tr> <td>Tom</td> <td>200</td> </tr> <tr> <td>James</td> <td>300</td> </tr> </tbody></table>"""
To read a table that contains the specific text:
# text in captiondfs = pd.read_html(html_string, match='2020 report')# text in table celldfs = pd.read_html(html_string, match='James')
The argument attrs takes a dictionary of any valid HTML tag attributes for filtering tables. For example,
dfs = pd.read_html(html_string, attrs={'id': 'report'})
id is a valid HTML tag attribute.
By default, all empty strings are treated as missing values and read as NaN .
Here is an example of an HTML table with some empty strings in the <td> cell.
html_string = """<table> <tr> <th>date</th> <th>name</th> <th>year</th> <th>cost</th> <th>region</th> </tr> <tr> <td>2020-01-01</td> <td>Jenny</td> <td>1998</td> <td>1.2</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> <td>1992</td> <td></td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tomas</td> <td>1982</td> <td></td> <td>South</td> </tr></table>"""
To read it with default settings
dfs = pd.read_html(html_string)dfs[0]
To keep these empty strings, we can set the argument keep_default_na to False
dfs = pd.read_html(html_string, keep_default_na=False)
Sometimes, you may have other character representations for missing values. If we know what kind of characters used as missing values in the table, we can handle them using na_values parameter:
dfs = pd.read_html(html_string, na_values=['?', '&'])
When the DataFrame is already created, we can use pandas replace() function to handle these values:
df_clean = dfs[0].replace({ "?": np.nan, "&": np.nan })
Pandas read_html() function is a quick and convenient way for scraping data from HTML tables.
I hope this article will help you to save time in scrapping data from HTML tables. I recommend you to check out the documentation for the read_html() API and to know about other things you can do.
Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning.
Using Pandas method chaining to improve code readability
How to do a Custom Sort on Pandas DataFrame
All the Pandas shift() you should know for data analysis
When to use Pandas transform() function
Pandas concat() tricks you should know
Difference between apply() and transform() in Pandas
All the Pandas merge() you should know
Working with datetime in Pandas DataFrame
Pandas read_csv() tricks you should know
4 tricks you should know to parse date columns with Pandas read_csv()
More tutorials can be found on my Github
|
[
{
"code": null,
"e": 422,
"s": 172,
"text": "Web scraping is the process of collecting and parsing data from the web. The Python community has come up with some pretty powerful web scrapping tools. Among them, Pandas read_html() is a quick and convenient way for scraping data from HTML tables."
},
{
"code": null,
"e": 565,
"s": 422,
"text": "In this article, youβll learn Pandas read_html() to deal with the following common problems and should help you get started with web scraping."
},
{
"code": null,
"e": 834,
"s": 565,
"text": "Reading tables from a stringReading tables from a URLReading tables from a fileParsing date columns with parse_datesExplicitly typecast with convertersMultiIndex, header, and index columnMatching a table with matchFiltering tables with attrsWorking with missing values"
},
{
"code": null,
"e": 863,
"s": 834,
"text": "Reading tables from a string"
},
{
"code": null,
"e": 889,
"s": 863,
"text": "Reading tables from a URL"
},
{
"code": null,
"e": 916,
"s": 889,
"text": "Reading tables from a file"
},
{
"code": null,
"e": 954,
"s": 916,
"text": "Parsing date columns with parse_dates"
},
{
"code": null,
"e": 990,
"s": 954,
"text": "Explicitly typecast with converters"
},
{
"code": null,
"e": 1027,
"s": 990,
"text": "MultiIndex, header, and index column"
},
{
"code": null,
"e": 1055,
"s": 1027,
"text": "Matching a table with match"
},
{
"code": null,
"e": 1083,
"s": 1055,
"text": "Filtering tables with attrs"
},
{
"code": null,
"e": 1111,
"s": 1083,
"text": "Working with missing values"
},
{
"code": null,
"e": 1158,
"s": 1111,
"text": "Please check out Notebook for the source code."
},
{
"code": null,
"e": 1230,
"s": 1158,
"text": "In the first example, we are going to read an HTML table from a string."
},
{
"code": null,
"e": 1780,
"s": 1230,
"text": "html_string = \"\"\"<table> <thead> <tr> <th>date</th> <th>name</th> <th>year</th> <th>cost</th> <th>region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Jenny</td> <td>1998</td> <td>0.2</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> <td>1992</td> <td>-1.34</td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tomas</td> <td>1982</td> <td>1.00023</td> <td>South</td> </tr> </tbody></table>\"\"\""
},
{
"code": null,
"e": 1810,
"s": 1780,
"text": "To read tables from a string:"
},
{
"code": null,
"e": 1842,
"s": 1810,
"text": "dfs = pd.read_html(html_string)"
},
{
"code": null,
"e": 1957,
"s": 1842,
"text": "Now, the result we get is not a Pandas DataFrame but a Python list. If we use the type() function we can see that:"
},
{
"code": null,
"e": 1975,
"s": 1957,
"text": ">>> type(dfs)list"
},
{
"code": null,
"e": 2039,
"s": 1975,
"text": "If we want to get the table, we can use the index to access it:"
},
{
"code": null,
"e": 2046,
"s": 2039,
"text": "dfs[0]"
},
{
"code": null,
"e": 2281,
"s": 2046,
"text": "The result looks great. Letβs take a look at the data types with dfs[0].info(). By default, columns that are numerical are cast to numeric types, for example, the year and cost columns have been cast to int64 and float64 respectively."
},
{
"code": null,
"e": 2675,
"s": 2281,
"text": ">>> df[0].info()RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 3 non-null object 1 name 3 non-null object 2 year 3 non-null int64 3 cost 3 non-null float64 4 region 3 non-null object dtypes: float64(1), int64(1), object(3)memory usage: 248.0+ bytes"
},
{
"code": null,
"e": 2763,
"s": 2675,
"text": "Pandas read_html() accepts a URL. Letβs see how this works with the help of an example."
},
{
"code": null,
"e": 2831,
"s": 2763,
"text": "URL = 'https://en.wikipedia.org/wiki/London'dfs = pd.read_html(URL)"
},
{
"code": null,
"e": 2970,
"s": 2831,
"text": "Same as reading from a string, it returns a list of DataFrames. If we run len(dfs) we can see that 31 tables available from the given URL."
},
{
"code": null,
"e": 3011,
"s": 2970,
"text": ">>> print(f'Total tables: {len(dfs)}')31"
},
{
"code": null,
"e": 3045,
"s": 3011,
"text": "And below is an example of dfs[6]"
},
{
"code": null,
"e": 3134,
"s": 3045,
"text": "Pandas read_html() accepts a file. Letβs see how this works with the help of an example."
},
{
"code": null,
"e": 3233,
"s": 3134,
"text": "file_path = 'html_string.txt'with open(file_path, 'r') as f: dfs = pd.read_html(f.read())dfs[0]"
},
{
"code": null,
"e": 3360,
"s": 3233,
"text": "Note: The following tutorials will be reading data from a string as the web page content is unlikely to be the same over time."
},
{
"code": null,
"e": 3516,
"s": 3360,
"text": "The date column gets read as an object data type. To read the date column correctly, we can use the argument parse_dates to specify a list of date columns."
},
{
"code": null,
"e": 4036,
"s": 3516,
"text": ">>> dfs = pd.read_html(html_string, parse_dates=['date'])>>> dfs[0].info()RangeIndex: 3 entries, 0 to 2Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 date 3 non-null datetime64[ns] 1 name 3 non-null object 2 year 3 non-null int64 3 cost 3 non-null float64 4 region 3 non-null object dtypes: datetime64[ns](1), float64(1), int64(1), object(2)memory usage: 248.0+ bytes"
},
{
"code": null,
"e": 4283,
"s": 4036,
"text": "By default, columns that are numerical are cast to numeric types, for example, the year and cost columns we have seen. But not all numerical text data are necessary to be numeric types, for example, an ID column that all values have leading zero."
},
{
"code": null,
"e": 4293,
"s": 4283,
"text": "ID = 0001"
},
{
"code": null,
"e": 4464,
"s": 4293,
"text": "In addition, sometimes you may want to explicitly typecast to ensure dtype integrity. For these requirements, we can do explicitly typecast with the argument converters :"
},
{
"code": null,
"e": 4559,
"s": 4464,
"text": "dfs = pd.read_html(html_string, converters={ 'ID': str, 'year': int, 'cost': float,})"
},
{
"code": null,
"e": 4729,
"s": 4559,
"text": "By default, <th> or <td> elements located within a <thead> are used to form the column index, if multiple rows are contained within <thead> then a Multiindex is created."
},
{
"code": null,
"e": 4797,
"s": 4729,
"text": "Below is an example of an HTML table with multiple rows in <thead>."
},
{
"code": null,
"e": 5277,
"s": 4797,
"text": "html_string = \"\"\"<table> <thead> <tr> <th colspan=\"5\">Year 2020</th> </tr> <tr> <th>date</th> <th>name</th> <th>year</th> <th>cost</th> <th>region</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Jenny</td> <td>1998</td> <td>1.2</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> <td>1992</td> <td>-1.34</td> <td>East</td> </tr> </tbody></table>\"\"\""
},
{
"code": null,
"e": 5342,
"s": 5277,
"text": "It creates MultiIndex because there are multiple rows in <thead>"
},
{
"code": null,
"e": 5380,
"s": 5342,
"text": "dfs = pd.read_html(html_string)dfs[0]"
},
{
"code": null,
"e": 5402,
"s": 5380,
"text": "Specify a header row:"
},
{
"code": null,
"e": 5450,
"s": 5402,
"text": "dfs = pd.read_html(html_string, header=1)dfs[0]"
},
{
"code": null,
"e": 5475,
"s": 5450,
"text": "Specify an index column:"
},
{
"code": null,
"e": 5536,
"s": 5475,
"text": "dfs = pd.read_html(html_string, header=1, index_col=0)dfs[0]"
},
{
"code": null,
"e": 5677,
"s": 5536,
"text": "The argument match takes a string or a regular expression. The value defaults to .+ (match any non-empty string) and will return all tables."
},
{
"code": null,
"e": 5731,
"s": 5677,
"text": "Letβs see how this works with the help of an example."
},
{
"code": null,
"e": 6281,
"s": 5731,
"text": "html_string = \"\"\"<table id=\"report\"> <caption>2020 report</caption> <thead> <tr> <th>date</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>2020-01-01</td> <td>Jenny</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> </tr> </tbody></table><table> <caption>Average income</caption> <thead> <tr> <th>name</th> <th>income</th> </tr> </thead> <tbody> <tr> <td>Tom</td> <td>200</td> </tr> <tr> <td>James</td> <td>300</td> </tr> </tbody></table>\"\"\""
},
{
"code": null,
"e": 6330,
"s": 6281,
"text": "To read a table that contains the specific text:"
},
{
"code": null,
"e": 6466,
"s": 6330,
"text": "# text in captiondfs = pd.read_html(html_string, match='2020 report')# text in table celldfs = pd.read_html(html_string, match='James')"
},
{
"code": null,
"e": 6572,
"s": 6466,
"text": "The argument attrs takes a dictionary of any valid HTML tag attributes for filtering tables. For example,"
},
{
"code": null,
"e": 6628,
"s": 6572,
"text": "dfs = pd.read_html(html_string, attrs={'id': 'report'})"
},
{
"code": null,
"e": 6662,
"s": 6628,
"text": "id is a valid HTML tag attribute."
},
{
"code": null,
"e": 6740,
"s": 6662,
"text": "By default, all empty strings are treated as missing values and read as NaN ."
},
{
"code": null,
"e": 6818,
"s": 6740,
"text": "Here is an example of an HTML table with some empty strings in the <td> cell."
},
{
"code": null,
"e": 7262,
"s": 6818,
"text": "html_string = \"\"\"<table> <tr> <th>date</th> <th>name</th> <th>year</th> <th>cost</th> <th>region</th> </tr> <tr> <td>2020-01-01</td> <td>Jenny</td> <td>1998</td> <td>1.2</td> <td>South</td> </tr> <tr> <td>2020-01-02</td> <td>Alice</td> <td>1992</td> <td></td> <td>East</td> </tr> <tr> <td>2020-01-03</td> <td>Tomas</td> <td>1982</td> <td></td> <td>South</td> </tr></table>\"\"\""
},
{
"code": null,
"e": 7295,
"s": 7262,
"text": "To read it with default settings"
},
{
"code": null,
"e": 7333,
"s": 7295,
"text": "dfs = pd.read_html(html_string)dfs[0]"
},
{
"code": null,
"e": 7411,
"s": 7333,
"text": "To keep these empty strings, we can set the argument keep_default_na to False"
},
{
"code": null,
"e": 7466,
"s": 7411,
"text": "dfs = pd.read_html(html_string, keep_default_na=False)"
},
{
"code": null,
"e": 7660,
"s": 7466,
"text": "Sometimes, you may have other character representations for missing values. If we know what kind of characters used as missing values in the table, we can handle them using na_values parameter:"
},
{
"code": null,
"e": 7714,
"s": 7660,
"text": "dfs = pd.read_html(html_string, na_values=['?', '&'])"
},
{
"code": null,
"e": 7814,
"s": 7714,
"text": "When the DataFrame is already created, we can use pandas replace() function to handle these values:"
},
{
"code": null,
"e": 7870,
"s": 7814,
"text": "df_clean = dfs[0].replace({ \"?\": np.nan, \"&\": np.nan })"
},
{
"code": null,
"e": 7964,
"s": 7870,
"text": "Pandas read_html() function is a quick and convenient way for scraping data from HTML tables."
},
{
"code": null,
"e": 8161,
"s": 7964,
"text": "I hope this article will help you to save time in scrapping data from HTML tables. I recommend you to check out the documentation for the read_html() API and to know about other things you can do."
},
{
"code": null,
"e": 8313,
"s": 8161,
"text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 8370,
"s": 8313,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 8414,
"s": 8370,
"text": "How to do a Custom Sort on Pandas DataFrame"
},
{
"code": null,
"e": 8471,
"s": 8414,
"text": "All the Pandas shift() you should know for data analysis"
},
{
"code": null,
"e": 8511,
"s": 8471,
"text": "When to use Pandas transform() function"
},
{
"code": null,
"e": 8550,
"s": 8511,
"text": "Pandas concat() tricks you should know"
},
{
"code": null,
"e": 8603,
"s": 8550,
"text": "Difference between apply() and transform() in Pandas"
},
{
"code": null,
"e": 8642,
"s": 8603,
"text": "All the Pandas merge() you should know"
},
{
"code": null,
"e": 8684,
"s": 8642,
"text": "Working with datetime in Pandas DataFrame"
},
{
"code": null,
"e": 8725,
"s": 8684,
"text": "Pandas read_csv() tricks you should know"
},
{
"code": null,
"e": 8795,
"s": 8725,
"text": "4 tricks you should know to parse date columns with Pandas read_csv()"
}
] |
Convolutions using Python?
|
Image recognition used to be done using much simpler methods such as linear regression and comparison of similarities. The results were obviously not very good, even the simple task of recognizing hand-written alphabets proved difficult. Convolution neural networks (CNNs) are supposed to be a step up from what we traditionally do by offering a computationally cheap method of loosely simulating the neural activities of a human brain when it perceives images.
Very similar to how we recognise different objects, computer algorithms need to go through millions of images before it is able to generalize the input and make judgement on image it has never seen before.
Computers see every image as 2D arrays of numbers, known as pixels. To identify objects in images, computer use special kind of Artificial Neural Network: a Convolutional Neural Network (CNN). CNN comes from, one of the most important operations in the network: convolution.
In convolutional neural network, each layers are organised into width, height and depth. Convolution which is the main part of CNNs, combine two functions to create a third function(merge two sets of information). It means consider an (image) convolution where we simply multiply two matrices element-wise followed by a sum.
A convolution is a three step procedure in image processing β
We take the input image.
We take the input image.
Kernel matrix that we are going to apply to the input image.
Kernel matrix that we are going to apply to the input image.
And the final image to store the output of the input image convolved with the kernel.
And the final image to store the output of the input image convolved with the kernel.
Below is small implementation of sobel filter using opencv which is an image processing filter for edge detection.
import cv2
import numpy as np
img = cv2.imread('beach.jpg')
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY).astype(float)
edge_x = cv2.Sobel(img,cv2.CV_64F,1,0,ksize = 3)
edge_y = cv2.Sobel(img,cv2.CV_64F,0,1,ksize = 3)
edge = np.sqrt(edge_x ** 2 + edge_y ** 2)
# image can be normalized to
# fit into 0..255 color space
cv2.imwrite('beach_convol.jpg', edge)
|
[
{
"code": null,
"e": 1524,
"s": 1062,
"text": "Image recognition used to be done using much simpler methods such as linear regression and comparison of similarities. The results were obviously not very good, even the simple task of recognizing hand-written alphabets proved difficult. Convolution neural networks (CNNs) are supposed to be a step up from what we traditionally do by offering a computationally cheap method of loosely simulating the neural activities of a human brain when it perceives images."
},
{
"code": null,
"e": 1730,
"s": 1524,
"text": "Very similar to how we recognise different objects, computer algorithms need to go through millions of images before it is able to generalize the input and make judgement on image it has never seen before."
},
{
"code": null,
"e": 2005,
"s": 1730,
"text": "Computers see every image as 2D arrays of numbers, known as pixels. To identify objects in images, computer use special kind of Artificial Neural Network: a Convolutional Neural Network (CNN). CNN comes from, one of the most important operations in the network: convolution."
},
{
"code": null,
"e": 2330,
"s": 2005,
"text": "In convolutional neural network, each layers are organised into width, height and depth. Convolution which is the main part of CNNs, combine two functions to create a third function(merge two sets of information). It means consider an (image) convolution where we simply multiply two matrices element-wise followed by a sum."
},
{
"code": null,
"e": 2392,
"s": 2330,
"text": "A convolution is a three step procedure in image processing β"
},
{
"code": null,
"e": 2417,
"s": 2392,
"text": "We take the input image."
},
{
"code": null,
"e": 2442,
"s": 2417,
"text": "We take the input image."
},
{
"code": null,
"e": 2503,
"s": 2442,
"text": "Kernel matrix that we are going to apply to the input image."
},
{
"code": null,
"e": 2564,
"s": 2503,
"text": "Kernel matrix that we are going to apply to the input image."
},
{
"code": null,
"e": 2650,
"s": 2564,
"text": "And the final image to store the output of the input image convolved with the kernel."
},
{
"code": null,
"e": 2736,
"s": 2650,
"text": "And the final image to store the output of the input image convolved with the kernel."
},
{
"code": null,
"e": 2851,
"s": 2736,
"text": "Below is small implementation of sobel filter using opencv which is an image processing filter for edge detection."
},
{
"code": null,
"e": 3208,
"s": 2851,
"text": "import cv2\nimport numpy as np\n\nimg = cv2.imread('beach.jpg')\nimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY).astype(float)\n\nedge_x = cv2.Sobel(img,cv2.CV_64F,1,0,ksize = 3)\nedge_y = cv2.Sobel(img,cv2.CV_64F,0,1,ksize = 3)\nedge = np.sqrt(edge_x ** 2 + edge_y ** 2)\n\n# image can be normalized to\n# fit into 0..255 color space\ncv2.imwrite('beach_convol.jpg', edge)"
}
] |
Count of acute, obtuse and right triangles with given sides - GeeksforGeeks
|
16 Apr, 2021
Given an array of n positive distinct integers representing lengths of lines that can form a triangle. The task is to find the number of acute triangles, obtuse triangles, and right triangles separately that can be formed from the given array.
Examples:
Input : arr[] = { 2, 3, 9, 10, 12, 15 }.
Output :
Acute Triangle: 2
Right Triangle: 1
Obtuse Triangle: 4
Acute triangles that can be formed are {10, 12, 15}
and { 9, 10, 12 }.
Right triangles that can be formed are {9, 12, 15}.
Obtuse triangles that can be formed are {2, 9, 10},
{3, 9, 10}, {3, 10, 12} and {9, 10, 15}.
Triangle having edges a, b, c, a <= b c. If a2 + b2 > c2, then it is acute triangle. If a2 + b2 = c2, then it is right triangle. If a2 + b2 < c2, then it is obtuse triangle.
Method 1 (Simple): A brute force can be, use three loops, one for each side. Check the above three conditions if a triangle is possible from three sides.
Method 2 (Efficient): An efficient approach is to first sort the array and run two loops for side a and b (a<b). Then find the farthest point q where a + b > c. So, from b to q all triangle are possible. Also find a farthest point p where a2 + b2 >= c2. Now, observe if a2 + b2 = c2, then increment count of right triangles. Also, the acute triangle will be p β b β 1, and the obtuse triangle will be q β p.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count of acute, obtuse and right// triangles in an array#include <bits/stdc++.h>using namespace std; // Find the number of acute, right, obtuse triangle// that can be formed from given array.void findTriangle(int a[], int n){ int b[n + 2]; // Finding the square of each element of array. for (int i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array and their squares. sort(a, a + n); sort(b, b + n); // x for acute triangles // y for right triangles // z for obtuse triangles int x=0,y=0,z=0; for (int i=0; i<n; i++) { int p = i+1; int q = i+1; for (int j=i+1; j<n; j++) { // Finding the farthest point p where // a^2 + b^2 >= c^2. while (p<n-1 && b[i]+b[j]>=b[p+1]) p++; q = max(q, p); // Finding the farthest point q where // a + b > c. while (q<n-1 && a[i]+a[j]>a[q+1]) q++; // If point p make right triangle. if (b[i]+b[j]==b[p]) { // All triangle between j and p are acute // triangles. So add p - j - 1 in x. x += max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q and p are acute // triangles. So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between j and p are acute // triangles. So add p - j in x. x += max(p - j, 0); // All triangle between q and p are acute // triangles. So add q - p in z. z += q - p; } } } cout << "Acute Triangle: " << x << endl; cout << "Right Triangle: " << y << endl; cout << "Obtuse Triangle: " << z << endl;} // Driver Codeint main(){ int arr[] = {2, 3, 9, 10, 12, 15}; int n = sizeof(arr)/sizeof(arr[0]); findTriangle(arr, n); return 0;}
// Java program to count of// acute, obtuse and right// triangles in an arrayimport java.util.*;class GFG{ // Find the number of acute,// right, obtuse triangle// that can be formed from// given array.static void findTriangle(int a[], int n){ int b[] = new int[n]; // Finding the square of // each element of array. for (int i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array // and their squares. Arrays.sort(a); Arrays.sort(b); // x for acute triangles // y for right triangles // z for obtuse triangles int x = 0, y = 0, z = 0; for (int i = 0; i < n; i++) { int p = i + 1; int q = i + 1; for (int j = i + 1; j < n; j++) { // Finding the farthest point // p where a^2 + b^2 >= c^2. while (p < n - 1 && b[i] + b[j] >= b[p + 1]) p++; q = Math.max(q, p); // Finding the farthest point // q where a + b > c. while (q < n - 1 && a[i] + a[j] > a[q + 1]) q++; // If point p make right triangle. if (b[i] + b[j] == b[p]) { // All triangle between j // and p are acute triangles. // So add p - j - 1 in x. x += Math.max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between // j and p are acute triangles. // So add p - j in x. x += Math.max(p - j, 0); // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } } } System.out.println("Acute Triangle: " + x); System.out.println("Right Triangle: " + y); System.out.println("Obtuse Triangle: " + z);} // Driver Codepublic static void main(String[] args){ int arr[] = {2, 3, 9, 10, 12, 15}; int n = arr.length; findTriangle(arr, n);}} // This code is contributed by Chitranayal
# Python3 program to count of acute, obtuse and right# triangles in an array # Find the number of acute, right, obtuse triangle# that can be formed from given array.def findTriangle(a, n) : b = [] # Finding the square of each element of array for i in range(n) : b.append(a[i] * a[i]) # Sort the sides of array and their squares. a.sort() b.sort() # x for acute triangles # y for right triangles # z for obtuse triangles x, y, z = 0, 0, 0 for i in range(n) : p = i+1 q = i+1 for j in range(i + 1, n) : # Finding the farthest point p where # a^2 + b^2 >= c^2. while (p<n-1 and b[i]+b[j]>=b[p+1]) : p += 1 q = max(q, p) # Finding the farthest point q where # a + b > c. while (q<n-1 and a[i]+a[j]>a[q+1]) : q += 1 # If point p make right triangle. if (b[i]+b[j]==b[p]) : # All triangle between j and p are acute # triangles. So add p - j - 1 in x. x += max(p - j - 1, 0) # Increment y by 1. y += 1 # All triangle between q and p are acute # triangles. So add q - p in z. z += q - p # If no right triangle else : # All triangle between j and p are acute # triangles. So add p - j in x. x += max(p - j, 0) # All triangle between q and p are acute # triangles. So add q - p in z. z += q - p print("Acute Triangle:",x ) print("Right Triangle:", y) print("Obtuse Triangle:", z) # Driver Codeif __name__ == "__main__" : arr = [2, 3, 9, 10, 12, 15] n = len(arr) findTriangle(arr, n) # This code is contributed by Ryuga
// C# program to count of// acute, obtuse and right// triangles in an arrayusing System; class GFG{ // Find the number of acute,// right, obtuse triangle// that can be formed from// given array.static void findTriangle(int []a, int n){ int []b = new int[n]; // Finding the square of // each element of array. for(int i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array // and their squares. Array.Sort(a); Array.Sort(b); // x for acute triangles // y for right triangles // z for obtuse triangles int x = 0, y = 0, z = 0; for(int i = 0; i < n; i++) { int p = i + 1; int q = i + 1; for(int j = i + 1; j < n; j++) { // Finding the farthest point // p where a^2 + b^2 >= c^2. while (p < n - 1 && b[i] + b[j] >= b[p + 1]) p++; q = Math.Max(q, p); // Finding the farthest point // q where a + b > c. while (q < n - 1 && a[i] + a[j] > a[q + 1]) q++; // If point p make right triangle. if (b[i] + b[j] == b[p]) { // All triangle between j // and p are acute triangles. // So add p - j - 1 in x. x += Math.Max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between // j and p are acute triangles. // So add p - j in x. x += Math.Max(p - j, 0); // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } } } Console.Write("Acute Triangle: " + x + "\n"); Console.Write("Right Triangle: " + y + "\n"); Console.Write("Obtuse Triangle: " + z + "\n");} // Driver Codepublic static void Main(string[] args){ int []arr = { 2, 3, 9, 10, 12, 15 }; int n = arr.Length; findTriangle(arr, n);}} // This code is contributed by rutvik_56
<?php// PHP program to count of acute, obtuse// and right triangles in an array // Find the number of acute, right, obtuse// triangle that can be formed from given array.function findTriangle($a, $n){ $b[$n + 2] = array(); // Finding the square of each // element of array. for ($i = 0; $i < $n; $i++) $b[$i] = $a[$i] * $a[$i]; // Sort the sides of array and // their squares. sort($a); sort($b); // x for acute triangles // y for right triangles // z for obtuse triangles $x = 0; $y = 0; $z = 0; for ($i = 0; $i < $n; $i++) { $p = $i + 1; $q = $i + 1; for ($j = $i + 1; $j < $n; $j++) { // Finding the farthest point p // where a^2 + b^2 >= c^2. while ($p < $n - 1 && $b[$i] + $b[$j] >= $b[$p + 1]) $p++; $q = max($q, $p); // Finding the farthest point q // where a + b > c. while ($q < $n - 1 && $a[$i] + $a[$j] > $a[$q + 1]) $q++; // If point p make right triangle. if ($b[$i] + $b[$j] == $b[$p]) { // All triangle between j and p are acute // triangles. So add p - j - 1 in x. $x += max($p - $j - 1, 0); // Increment y by 1. $y++; // All triangle between q and p are // acute triangles. So add q - p in z. $z += $q - $p; } // If no right triangle else { // All triangle between j and p are acute // triangles. So add p - j in x. $x += max($p - $j, 0); // All triangle between q and p are acute // triangles. So add q - p in z. $z += $q - $p; } } } echo "Acute Triangle: ", $x, "\n"; echo "Right Triangle: ", $y, "\n"; echo "Obtuse Triangle: ", $z, "\n";} // Driver Code$arr = array(2, 3, 9, 10, 12, 15);$n = sizeof($arr);findTriangle($arr, $n); // This code is contributed by akt_mit?>
<script> // Javascript program to count of// acute, obtuse and right// triangles in an array // Find the number of acute, // right, obtuse triangle // that can be formed from // given array. function findTriangle(a,n) { let b=new Array(n); for(let i=0;i<n;i++) { b[i]=0; } // Finding the square of // each element of array. for (let i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array // and their squares. a.sort(function(i,j){return i-j;}); b.sort(function(i,j){return i-j;}); // x for acute triangles // y for right triangles // z for obtuse triangles let x = 0, y = 0, z = 0; for (let i = 0; i < n; i++) { let p = i + 1; let q = i + 1; for (let j = i + 1; j < n; j++) { // Finding the farthest point // p where a^2 + b^2 >= c^2. while (p < n - 1 && b[i] + b[j] >= b[p + 1]) p++; q = Math.max(q, p); // Finding the farthest point // q where a + b > c. while (q < n - 1 && a[i] + a[j] > a[q + 1]) q++; // If point p make right triangle. if (b[i] + b[j] == b[p]) { // All triangle between j // and p are acute triangles. // So add p - j - 1 in x. x += Math.max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between // j and p are acute triangles. // So add p - j in x. x += Math.max(p - j, 0); // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } } } document.write("Acute Triangle: " + x+"<br>"); document.write("Right Triangle: " + y+"<br>"); document.write("Obtuse Triangle: " + z+"<br>"); } // Driver Code let arr=[2, 3, 9, 10, 12, 15]; let n = arr.length; findTriangle(arr, n); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Acute Triangle: 2
Right Triangle: 1
Obtuse Triangle: 4
This article is contributed by Anuj Chauhan. 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.
ankthon
jit_t
ukasp
rutvik_56
avanitrachhadiya2155
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull using Divide and Conquer Algorithm
Orientation of 3 ordered points
Equation of circle when three points on the circle are given
Program to find slope of a line
Program to find line passing through 2 Points
Circle and Lattice Points
Maximum Manhattan distance between a distinct pair from N coordinates
Minimum Cost Polygon Triangulation
Quickhull Algorithm for Convex Hull
Check whether triangle is valid or not if three points are given
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 25544,
"s": 25300,
"text": "Given an array of n positive distinct integers representing lengths of lines that can form a triangle. The task is to find the number of acute triangles, obtuse triangles, and right triangles separately that can be formed from the given array."
},
{
"code": null,
"e": 25555,
"s": 25544,
"text": "Examples: "
},
{
"code": null,
"e": 25879,
"s": 25555,
"text": "Input : arr[] = { 2, 3, 9, 10, 12, 15 }.\nOutput :\nAcute Triangle: 2\nRight Triangle: 1\nObtuse Triangle: 4\n\nAcute triangles that can be formed are {10, 12, 15} \nand { 9, 10, 12 }.\nRight triangles that can be formed are {9, 12, 15}.\nObtuse triangles that can be formed are {2, 9, 10}, \n{3, 9, 10}, {3, 10, 12} and {9, 10, 15}."
},
{
"code": null,
"e": 26053,
"s": 25879,
"text": "Triangle having edges a, b, c, a <= b c. If a2 + b2 > c2, then it is acute triangle. If a2 + b2 = c2, then it is right triangle. If a2 + b2 < c2, then it is obtuse triangle."
},
{
"code": null,
"e": 26207,
"s": 26053,
"text": "Method 1 (Simple): A brute force can be, use three loops, one for each side. Check the above three conditions if a triangle is possible from three sides."
},
{
"code": null,
"e": 26616,
"s": 26207,
"text": "Method 2 (Efficient): An efficient approach is to first sort the array and run two loops for side a and b (a<b). Then find the farthest point q where a + b > c. So, from b to q all triangle are possible. Also find a farthest point p where a2 + b2 >= c2. Now, observe if a2 + b2 = c2, then increment count of right triangles. Also, the acute triangle will be p β b β 1, and the obtuse triangle will be q β p. "
},
{
"code": null,
"e": 26620,
"s": 26616,
"text": "C++"
},
{
"code": null,
"e": 26625,
"s": 26620,
"text": "Java"
},
{
"code": null,
"e": 26633,
"s": 26625,
"text": "Python3"
},
{
"code": null,
"e": 26636,
"s": 26633,
"text": "C#"
},
{
"code": null,
"e": 26640,
"s": 26636,
"text": "PHP"
},
{
"code": null,
"e": 26651,
"s": 26640,
"text": "Javascript"
},
{
"code": "// C++ program to count of acute, obtuse and right// triangles in an array#include <bits/stdc++.h>using namespace std; // Find the number of acute, right, obtuse triangle// that can be formed from given array.void findTriangle(int a[], int n){ int b[n + 2]; // Finding the square of each element of array. for (int i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array and their squares. sort(a, a + n); sort(b, b + n); // x for acute triangles // y for right triangles // z for obtuse triangles int x=0,y=0,z=0; for (int i=0; i<n; i++) { int p = i+1; int q = i+1; for (int j=i+1; j<n; j++) { // Finding the farthest point p where // a^2 + b^2 >= c^2. while (p<n-1 && b[i]+b[j]>=b[p+1]) p++; q = max(q, p); // Finding the farthest point q where // a + b > c. while (q<n-1 && a[i]+a[j]>a[q+1]) q++; // If point p make right triangle. if (b[i]+b[j]==b[p]) { // All triangle between j and p are acute // triangles. So add p - j - 1 in x. x += max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q and p are acute // triangles. So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between j and p are acute // triangles. So add p - j in x. x += max(p - j, 0); // All triangle between q and p are acute // triangles. So add q - p in z. z += q - p; } } } cout << \"Acute Triangle: \" << x << endl; cout << \"Right Triangle: \" << y << endl; cout << \"Obtuse Triangle: \" << z << endl;} // Driver Codeint main(){ int arr[] = {2, 3, 9, 10, 12, 15}; int n = sizeof(arr)/sizeof(arr[0]); findTriangle(arr, n); return 0;}",
"e": 28730,
"s": 26651,
"text": null
},
{
"code": "// Java program to count of// acute, obtuse and right// triangles in an arrayimport java.util.*;class GFG{ // Find the number of acute,// right, obtuse triangle// that can be formed from// given array.static void findTriangle(int a[], int n){ int b[] = new int[n]; // Finding the square of // each element of array. for (int i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array // and their squares. Arrays.sort(a); Arrays.sort(b); // x for acute triangles // y for right triangles // z for obtuse triangles int x = 0, y = 0, z = 0; for (int i = 0; i < n; i++) { int p = i + 1; int q = i + 1; for (int j = i + 1; j < n; j++) { // Finding the farthest point // p where a^2 + b^2 >= c^2. while (p < n - 1 && b[i] + b[j] >= b[p + 1]) p++; q = Math.max(q, p); // Finding the farthest point // q where a + b > c. while (q < n - 1 && a[i] + a[j] > a[q + 1]) q++; // If point p make right triangle. if (b[i] + b[j] == b[p]) { // All triangle between j // and p are acute triangles. // So add p - j - 1 in x. x += Math.max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between // j and p are acute triangles. // So add p - j in x. x += Math.max(p - j, 0); // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } } } System.out.println(\"Acute Triangle: \" + x); System.out.println(\"Right Triangle: \" + y); System.out.println(\"Obtuse Triangle: \" + z);} // Driver Codepublic static void main(String[] args){ int arr[] = {2, 3, 9, 10, 12, 15}; int n = arr.length; findTriangle(arr, n);}} // This code is contributed by Chitranayal",
"e": 30750,
"s": 28730,
"text": null
},
{
"code": "# Python3 program to count of acute, obtuse and right# triangles in an array # Find the number of acute, right, obtuse triangle# that can be formed from given array.def findTriangle(a, n) : b = [] # Finding the square of each element of array for i in range(n) : b.append(a[i] * a[i]) # Sort the sides of array and their squares. a.sort() b.sort() # x for acute triangles # y for right triangles # z for obtuse triangles x, y, z = 0, 0, 0 for i in range(n) : p = i+1 q = i+1 for j in range(i + 1, n) : # Finding the farthest point p where # a^2 + b^2 >= c^2. while (p<n-1 and b[i]+b[j]>=b[p+1]) : p += 1 q = max(q, p) # Finding the farthest point q where # a + b > c. while (q<n-1 and a[i]+a[j]>a[q+1]) : q += 1 # If point p make right triangle. if (b[i]+b[j]==b[p]) : # All triangle between j and p are acute # triangles. So add p - j - 1 in x. x += max(p - j - 1, 0) # Increment y by 1. y += 1 # All triangle between q and p are acute # triangles. So add q - p in z. z += q - p # If no right triangle else : # All triangle between j and p are acute # triangles. So add p - j in x. x += max(p - j, 0) # All triangle between q and p are acute # triangles. So add q - p in z. z += q - p print(\"Acute Triangle:\",x ) print(\"Right Triangle:\", y) print(\"Obtuse Triangle:\", z) # Driver Codeif __name__ == \"__main__\" : arr = [2, 3, 9, 10, 12, 15] n = len(arr) findTriangle(arr, n) # This code is contributed by Ryuga",
"e": 32643,
"s": 30750,
"text": null
},
{
"code": "// C# program to count of// acute, obtuse and right// triangles in an arrayusing System; class GFG{ // Find the number of acute,// right, obtuse triangle// that can be formed from// given array.static void findTriangle(int []a, int n){ int []b = new int[n]; // Finding the square of // each element of array. for(int i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array // and their squares. Array.Sort(a); Array.Sort(b); // x for acute triangles // y for right triangles // z for obtuse triangles int x = 0, y = 0, z = 0; for(int i = 0; i < n; i++) { int p = i + 1; int q = i + 1; for(int j = i + 1; j < n; j++) { // Finding the farthest point // p where a^2 + b^2 >= c^2. while (p < n - 1 && b[i] + b[j] >= b[p + 1]) p++; q = Math.Max(q, p); // Finding the farthest point // q where a + b > c. while (q < n - 1 && a[i] + a[j] > a[q + 1]) q++; // If point p make right triangle. if (b[i] + b[j] == b[p]) { // All triangle between j // and p are acute triangles. // So add p - j - 1 in x. x += Math.Max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between // j and p are acute triangles. // So add p - j in x. x += Math.Max(p - j, 0); // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } } } Console.Write(\"Acute Triangle: \" + x + \"\\n\"); Console.Write(\"Right Triangle: \" + y + \"\\n\"); Console.Write(\"Obtuse Triangle: \" + z + \"\\n\");} // Driver Codepublic static void Main(string[] args){ int []arr = { 2, 3, 9, 10, 12, 15 }; int n = arr.Length; findTriangle(arr, n);}} // This code is contributed by rutvik_56",
"e": 34675,
"s": 32643,
"text": null
},
{
"code": "<?php// PHP program to count of acute, obtuse// and right triangles in an array // Find the number of acute, right, obtuse// triangle that can be formed from given array.function findTriangle($a, $n){ $b[$n + 2] = array(); // Finding the square of each // element of array. for ($i = 0; $i < $n; $i++) $b[$i] = $a[$i] * $a[$i]; // Sort the sides of array and // their squares. sort($a); sort($b); // x for acute triangles // y for right triangles // z for obtuse triangles $x = 0; $y = 0; $z = 0; for ($i = 0; $i < $n; $i++) { $p = $i + 1; $q = $i + 1; for ($j = $i + 1; $j < $n; $j++) { // Finding the farthest point p // where a^2 + b^2 >= c^2. while ($p < $n - 1 && $b[$i] + $b[$j] >= $b[$p + 1]) $p++; $q = max($q, $p); // Finding the farthest point q // where a + b > c. while ($q < $n - 1 && $a[$i] + $a[$j] > $a[$q + 1]) $q++; // If point p make right triangle. if ($b[$i] + $b[$j] == $b[$p]) { // All triangle between j and p are acute // triangles. So add p - j - 1 in x. $x += max($p - $j - 1, 0); // Increment y by 1. $y++; // All triangle between q and p are // acute triangles. So add q - p in z. $z += $q - $p; } // If no right triangle else { // All triangle between j and p are acute // triangles. So add p - j in x. $x += max($p - $j, 0); // All triangle between q and p are acute // triangles. So add q - p in z. $z += $q - $p; } } } echo \"Acute Triangle: \", $x, \"\\n\"; echo \"Right Triangle: \", $y, \"\\n\"; echo \"Obtuse Triangle: \", $z, \"\\n\";} // Driver Code$arr = array(2, 3, 9, 10, 12, 15);$n = sizeof($arr);findTriangle($arr, $n); // This code is contributed by akt_mit?>",
"e": 36820,
"s": 34675,
"text": null
},
{
"code": "<script> // Javascript program to count of// acute, obtuse and right// triangles in an array // Find the number of acute, // right, obtuse triangle // that can be formed from // given array. function findTriangle(a,n) { let b=new Array(n); for(let i=0;i<n;i++) { b[i]=0; } // Finding the square of // each element of array. for (let i = 0; i < n; i++) b[i] = a[i] * a[i]; // Sort the sides of array // and their squares. a.sort(function(i,j){return i-j;}); b.sort(function(i,j){return i-j;}); // x for acute triangles // y for right triangles // z for obtuse triangles let x = 0, y = 0, z = 0; for (let i = 0; i < n; i++) { let p = i + 1; let q = i + 1; for (let j = i + 1; j < n; j++) { // Finding the farthest point // p where a^2 + b^2 >= c^2. while (p < n - 1 && b[i] + b[j] >= b[p + 1]) p++; q = Math.max(q, p); // Finding the farthest point // q where a + b > c. while (q < n - 1 && a[i] + a[j] > a[q + 1]) q++; // If point p make right triangle. if (b[i] + b[j] == b[p]) { // All triangle between j // and p are acute triangles. // So add p - j - 1 in x. x += Math.max(p - j - 1, 0); // Increment y by 1. y++; // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } // If no right triangle else { // All triangle between // j and p are acute triangles. // So add p - j in x. x += Math.max(p - j, 0); // All triangle between q // and p are acute triangles. // So add q - p in z. z += q - p; } } } document.write(\"Acute Triangle: \" + x+\"<br>\"); document.write(\"Right Triangle: \" + y+\"<br>\"); document.write(\"Obtuse Triangle: \" + z+\"<br>\"); } // Driver Code let arr=[2, 3, 9, 10, 12, 15]; let n = arr.length; findTriangle(arr, n); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 39291,
"s": 36820,
"text": null
},
{
"code": null,
"e": 39300,
"s": 39291,
"text": "Output: "
},
{
"code": null,
"e": 39355,
"s": 39300,
"text": "Acute Triangle: 2\nRight Triangle: 1\nObtuse Triangle: 4"
},
{
"code": null,
"e": 39780,
"s": 39355,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39788,
"s": 39780,
"text": "ankthon"
},
{
"code": null,
"e": 39794,
"s": 39788,
"text": "jit_t"
},
{
"code": null,
"e": 39800,
"s": 39794,
"text": "ukasp"
},
{
"code": null,
"e": 39810,
"s": 39800,
"text": "rutvik_56"
},
{
"code": null,
"e": 39831,
"s": 39810,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 39841,
"s": 39831,
"text": "Geometric"
},
{
"code": null,
"e": 39851,
"s": 39841,
"text": "Geometric"
},
{
"code": null,
"e": 39949,
"s": 39851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39996,
"s": 39949,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 40028,
"s": 39996,
"text": "Orientation of 3 ordered points"
},
{
"code": null,
"e": 40089,
"s": 40028,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 40121,
"s": 40089,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 40167,
"s": 40121,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 40193,
"s": 40167,
"text": "Circle and Lattice Points"
},
{
"code": null,
"e": 40263,
"s": 40193,
"text": "Maximum Manhattan distance between a distinct pair from N coordinates"
},
{
"code": null,
"e": 40298,
"s": 40263,
"text": "Minimum Cost Polygon Triangulation"
},
{
"code": null,
"e": 40334,
"s": 40298,
"text": "Quickhull Algorithm for Convex Hull"
}
] |
Create a Plot Matrix of Scatterplots in R Programming - pairs() Function - GeeksforGeeks
|
10 Dec, 2021
pairs() function in R language is used to return a plot matrix, consisting of scatter plots corresponding to each data frame.
Syntax: pairs(data)
Parameters:
data: It is defined as value of pairs Plot.
Returns: Color, Labels, Panels, and by Group in pairs plot.
R
# Set seed for reproducibilityset.seed(425340) # Sample size of 800N <- 800 # Create variablex1 <- rnorm(N) # Create correlated variablex2 <- x1 + rnorm(N, 0, 4) # Create another correlated variablex3 <- 2 * x1 - x2 + rnorm(N, 0, 3) data <- data.frame(x1, x2, x3) pairs(data)
Output:
Here, in the above example, the diagonal shows the names of the three numeric variables. The middle graphic in the first-row shows the relation between x1 and x2 whereas the right graph in the first row shows the relation between x1 and x3 and so on.
R
# Set seed for reproducibilityset.seed(425340) # Sample size of 800N <- 800 # Create variablex1 <- rnorm(N) # Create correlated variablex2 <- x1 + rnorm(N, 0, 4) # Create another correlated variablex3 <- 2 * x1 - x2 + rnorm(N, 0, 3) data <- data.frame(x1, x2, x3) pairs(~ x1 + x3, data = data)
Output:
R
# Set seed for reproducibilityset.seed(425340) # Sample size of 800N <- 800 # Create variablex1 <- rnorm(N) # Create correlated variablex2 <- x1 + rnorm(N, 0, 4) # Create another correlated variablex3 <- 2 * x1 - x2 + rnorm(N, 0, 3) data <- data.frame(x1, x2, x3) pairs(~ x1 + x2 + x3, data = data)pairs(~ x1 + x3, data = data) pairs(data[, 1:3], col = "darkgreen", # Change color pch = 18, # Change shape of points # Change labels of diagonal labels = c("var1", "var2", "var3"), main = " pairs plot in R")
Output:
kumar_satyam
R Plot-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
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?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n10 Dec, 2021"
},
{
"code": null,
"e": 25368,
"s": 25242,
"text": "pairs() function in R language is used to return a plot matrix, consisting of scatter plots corresponding to each data frame."
},
{
"code": null,
"e": 25388,
"s": 25368,
"text": "Syntax: pairs(data)"
},
{
"code": null,
"e": 25401,
"s": 25388,
"text": "Parameters: "
},
{
"code": null,
"e": 25446,
"s": 25401,
"text": "data: It is defined as value of pairs Plot."
},
{
"code": null,
"e": 25508,
"s": 25446,
"text": "Returns: Color, Labels, Panels, and by Group in pairs plot. "
},
{
"code": null,
"e": 25510,
"s": 25508,
"text": "R"
},
{
"code": "# Set seed for reproducibilityset.seed(425340) # Sample size of 800N <- 800 # Create variablex1 <- rnorm(N) # Create correlated variablex2 <- x1 + rnorm(N, 0, 4) # Create another correlated variablex3 <- 2 * x1 - x2 + rnorm(N, 0, 3) data <- data.frame(x1, x2, x3) pairs(data) ",
"e": 25802,
"s": 25510,
"text": null
},
{
"code": null,
"e": 25811,
"s": 25802,
"text": "Output: "
},
{
"code": null,
"e": 26062,
"s": 25811,
"text": "Here, in the above example, the diagonal shows the names of the three numeric variables. The middle graphic in the first-row shows the relation between x1 and x2 whereas the right graph in the first row shows the relation between x1 and x3 and so on."
},
{
"code": null,
"e": 26064,
"s": 26062,
"text": "R"
},
{
"code": "# Set seed for reproducibilityset.seed(425340) # Sample size of 800N <- 800 # Create variablex1 <- rnorm(N) # Create correlated variablex2 <- x1 + rnorm(N, 0, 4) # Create another correlated variablex3 <- 2 * x1 - x2 + rnorm(N, 0, 3) data <- data.frame(x1, x2, x3) pairs(~ x1 + x3, data = data) ",
"e": 26381,
"s": 26064,
"text": null
},
{
"code": null,
"e": 26389,
"s": 26381,
"text": "Output:"
},
{
"code": null,
"e": 26391,
"s": 26389,
"text": "R"
},
{
"code": "# Set seed for reproducibilityset.seed(425340) # Sample size of 800N <- 800 # Create variablex1 <- rnorm(N) # Create correlated variablex2 <- x1 + rnorm(N, 0, 4) # Create another correlated variablex3 <- 2 * x1 - x2 + rnorm(N, 0, 3) data <- data.frame(x1, x2, x3) pairs(~ x1 + x2 + x3, data = data)pairs(~ x1 + x3, data = data) pairs(data[, 1:3], col = \"darkgreen\", # Change color pch = 18, # Change shape of points # Change labels of diagonal labels = c(\"var1\", \"var2\", \"var3\"), main = \" pairs plot in R\")",
"e": 26961,
"s": 26391,
"text": null
},
{
"code": null,
"e": 26969,
"s": 26961,
"text": "Output:"
},
{
"code": null,
"e": 26982,
"s": 26969,
"text": "kumar_satyam"
},
{
"code": null,
"e": 26998,
"s": 26982,
"text": "R Plot-Function"
},
{
"code": null,
"e": 27009,
"s": 26998,
"text": "R Language"
},
{
"code": null,
"e": 27107,
"s": 27009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27159,
"s": 27107,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27197,
"s": 27159,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27232,
"s": 27197,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27290,
"s": 27232,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27339,
"s": 27290,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27376,
"s": 27339,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27426,
"s": 27376,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27469,
"s": 27426,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27495,
"s": 27469,
"text": "Time Series Analysis in R"
}
] |
How to remove all classes that begin with a certain string in JavaScript? - GeeksforGeeks
|
06 Sep, 2019
The task is to remove all the classes of a certain element starting with a specific prefix. Here are a few of the most used techniques discussed. We are going to use JavaScript.
Approach 1:
Select a particular element.
Use .className property to get access to all the classes.
Use .replace() method to replace all the specific classes by space(Which means classes are removed from the element).
In this example, a RegExp is used for replacing.
Example 1: This example using the approach discussed above.
<!DOCTYPE HTML><html> <head> <title> How to remove all classes that begin with a certain string JavaScript? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> #div { height: 100px; } .el-color { color: white; } .el-background { background: green; } .el-border { border: 3px solid blue; } </style> </head> <body id="body" align="center"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div id="div" class="el-color el-background el-border"> Div Element </div> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to remove all "+ "classes starting with certain character."; function GFG_Fun() { $('#div')[0].className = $('#div')[0].className.replace(/\bel.*?\b/g, ''); el_down.innerHTML = "Every class starting with 'el' is removed from the element."; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2
Select a particular element.
Use .className property to get access to all the classes.
Use .split() method to get all classes as a element.
Use .filter() function to filter out the classes which are not starting with certain character.
Finally, put those classes with the element.
Example 2: This example using the approach discussed above.
<!DOCTYPE HTML><html> <head> <title> How to remove all classes that begin with a certain string JavaScript? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> #div { height: 100px; } .el-color { color: white; } .el-background { background: green; } .el-border { border: 3px solid blue; } </style> </head> <body id="body" align="center"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div id="div" class="el-color el-background el-border"> Div Element </div> <br> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="font-size: 20px; font-weight: bold; color:green;"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var el = document.getElementById('div'); el_up.innerHTML = "Click on the button to remove "+ "all classes starting with certain character."; function GFG_Fun() { var startsWith = "el"; var classes = el.className.split(" ").filter(function(v) { return v.lastIndexOf(startsWith, 0) !== 0; }); el.className = classes.join(" ").trim(); el_down.innerHTML = "Every class starting with 'el' is removed from the element."; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n06 Sep, 2019"
},
{
"code": null,
"e": 26723,
"s": 26545,
"text": "The task is to remove all the classes of a certain element starting with a specific prefix. Here are a few of the most used techniques discussed. We are going to use JavaScript."
},
{
"code": null,
"e": 26735,
"s": 26723,
"text": "Approach 1:"
},
{
"code": null,
"e": 26764,
"s": 26735,
"text": "Select a particular element."
},
{
"code": null,
"e": 26822,
"s": 26764,
"text": "Use .className property to get access to all the classes."
},
{
"code": null,
"e": 26940,
"s": 26822,
"text": "Use .replace() method to replace all the specific classes by space(Which means classes are removed from the element)."
},
{
"code": null,
"e": 26989,
"s": 26940,
"text": "In this example, a RegExp is used for replacing."
},
{
"code": null,
"e": 27049,
"s": 26989,
"text": "Example 1: This example using the approach discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to remove all classes that begin with a certain string JavaScript? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> #div { height: 100px; } .el-color { color: white; } .el-background { background: green; } .el-border { border: 3px solid blue; } </style> </head> <body id=\"body\" align=\"center\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div id=\"div\" class=\"el-color el-background el-border\"> Div Element </div> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to remove all \"+ \"classes starting with certain character.\"; function GFG_Fun() { $('#div')[0].className = $('#div')[0].className.replace(/\\bel.*?\\b/g, ''); el_down.innerHTML = \"Every class starting with 'el' is removed from the element.\"; } </script></body> </html>",
"e": 28580,
"s": 27049,
"text": null
},
{
"code": null,
"e": 28588,
"s": 28580,
"text": "Output:"
},
{
"code": null,
"e": 28619,
"s": 28588,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28649,
"s": 28619,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28660,
"s": 28649,
"text": "Approach 2"
},
{
"code": null,
"e": 28689,
"s": 28660,
"text": "Select a particular element."
},
{
"code": null,
"e": 28747,
"s": 28689,
"text": "Use .className property to get access to all the classes."
},
{
"code": null,
"e": 28800,
"s": 28747,
"text": "Use .split() method to get all classes as a element."
},
{
"code": null,
"e": 28896,
"s": 28800,
"text": "Use .filter() function to filter out the classes which are not starting with certain character."
},
{
"code": null,
"e": 28941,
"s": 28896,
"text": "Finally, put those classes with the element."
},
{
"code": null,
"e": 29001,
"s": 28941,
"text": "Example 2: This example using the approach discussed above."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to remove all classes that begin with a certain string JavaScript? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> #div { height: 100px; } .el-color { color: white; } .el-background { background: green; } .el-border { border: 3px solid blue; } </style> </head> <body id=\"body\" align=\"center\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div id=\"div\" class=\"el-color el-background el-border\"> Div Element </div> <br> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"font-size: 20px; font-weight: bold; color:green;\"> </p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); var el = document.getElementById('div'); el_up.innerHTML = \"Click on the button to remove \"+ \"all classes starting with certain character.\"; function GFG_Fun() { var startsWith = \"el\"; var classes = el.className.split(\" \").filter(function(v) { return v.lastIndexOf(startsWith, 0) !== 0; }); el.className = classes.join(\" \").trim(); el_down.innerHTML = \"Every class starting with 'el' is removed from the element.\"; } </script></body> </html>",
"e": 30702,
"s": 29001,
"text": null
},
{
"code": null,
"e": 30710,
"s": 30702,
"text": "Output:"
},
{
"code": null,
"e": 30741,
"s": 30710,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 30771,
"s": 30741,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 30787,
"s": 30771,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30798,
"s": 30787,
"text": "JavaScript"
},
{
"code": null,
"e": 30815,
"s": 30798,
"text": "Web Technologies"
},
{
"code": null,
"e": 30842,
"s": 30815,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30940,
"s": 30842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30980,
"s": 30940,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31041,
"s": 30980,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31082,
"s": 31041,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 31104,
"s": 31082,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 31158,
"s": 31104,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 31198,
"s": 31158,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31231,
"s": 31198,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31274,
"s": 31231,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31324,
"s": 31274,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to handle alert prompts in Selenium Python ? - GeeksforGeeks
|
15 May, 2020
Seleniumβs Python Module is built to perform automated testing with Python. Alerts are a way to show popups in the browser for either accepting data or displaying data. Selenium provides methods to handle alerts of all kinds. class selenium.webdriver.common.alert.Alert(driver) handles all alerts in Selenium Python. It contains methods for dismissing, accepting, inputting, and getting text from alert prompts. The two major tasks in alerts are accepting an alert or dismissing a alert.Selenium provides two methods for the same β
Alert(driver).accept()
Alert(driver).dismiss()
The major methods during handling of alerts in Selenium include β
accept() β Accepts the alert available.
dismiss() β Dismisses the alert available.
send_keys(keysToSend) β Send Keys to the Alert.
text β Gets the text of the Alert.
To illustrate alerts, letβs write manual javascript alert and check various methods on the same. We have created an example link β https://ide.geeksforgeeks.org/tryit.php/WXYeMD9tD4
# import webdriverfrom selenium import webdriver # import Alert from selenium.webdriver.common.alert import Alert # create webdriver objectdriver = webdriver.Firefox() # get ide.geeksforgeeks.orgdriver.get("https://ide.geeksforgeeks.org / tryit.php / WXYeMD9tD4") # create alert objectalert = Alert(driver) # get alert textprint(alert.text) # accept the alertalert.accept()
Output β
Terminal Output β
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26069,
"s": 26041,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 26601,
"s": 26069,
"text": "Seleniumβs Python Module is built to perform automated testing with Python. Alerts are a way to show popups in the browser for either accepting data or displaying data. Selenium provides methods to handle alerts of all kinds. class selenium.webdriver.common.alert.Alert(driver) handles all alerts in Selenium Python. It contains methods for dismissing, accepting, inputting, and getting text from alert prompts. The two major tasks in alerts are accepting an alert or dismissing a alert.Selenium provides two methods for the same β"
},
{
"code": null,
"e": 26648,
"s": 26601,
"text": "Alert(driver).accept()\nAlert(driver).dismiss()"
},
{
"code": null,
"e": 26714,
"s": 26648,
"text": "The major methods during handling of alerts in Selenium include β"
},
{
"code": null,
"e": 26754,
"s": 26714,
"text": "accept() β Accepts the alert available."
},
{
"code": null,
"e": 26797,
"s": 26754,
"text": "dismiss() β Dismisses the alert available."
},
{
"code": null,
"e": 26845,
"s": 26797,
"text": "send_keys(keysToSend) β Send Keys to the Alert."
},
{
"code": null,
"e": 26880,
"s": 26845,
"text": "text β Gets the text of the Alert."
},
{
"code": null,
"e": 27062,
"s": 26880,
"text": "To illustrate alerts, letβs write manual javascript alert and check various methods on the same. We have created an example link β https://ide.geeksforgeeks.org/tryit.php/WXYeMD9tD4"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Alert from selenium.webdriver.common.alert import Alert # create webdriver objectdriver = webdriver.Firefox() # get ide.geeksforgeeks.orgdriver.get(\"https://ide.geeksforgeeks.org / tryit.php / WXYeMD9tD4\") # create alert objectalert = Alert(driver) # get alert textprint(alert.text) # accept the alertalert.accept()",
"e": 27442,
"s": 27062,
"text": null
},
{
"code": null,
"e": 27451,
"s": 27442,
"text": "Output β"
},
{
"code": null,
"e": 27469,
"s": 27451,
"text": "Terminal Output β"
},
{
"code": null,
"e": 27485,
"s": 27469,
"text": "Python-selenium"
},
{
"code": null,
"e": 27494,
"s": 27485,
"text": "selenium"
},
{
"code": null,
"e": 27501,
"s": 27494,
"text": "Python"
},
{
"code": null,
"e": 27599,
"s": 27501,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27617,
"s": 27599,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27652,
"s": 27617,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27684,
"s": 27652,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27706,
"s": 27684,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27748,
"s": 27706,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27778,
"s": 27748,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27804,
"s": 27778,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27833,
"s": 27804,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27877,
"s": 27833,
"text": "Reading and Writing to text files in Python"
}
] |
Struts 2 & Spring Integration
|
Spring is a popular web framework that provides easy integration with lots of common web tasks. So the question is, why do we need Spring when we have Struts2? Well, Spring is more than a MVC framework - it offers many other goodies which are not available in Struts.
For example: dependency injection that can be useful to any framework. In this chapter, we will go through a simple example to see how to integrate Spring and Struts2 together.
First of all, you need to add the following files to the project's build path from Spring installation. You can download and install latest version of Spring Framework from https://www.springsource.org/download
org.springframework.asm-x.y.z.M(a).jar
org.springframework.beans-x.y.z.M(a).jar
org.springframework.context-x.y.z.M(a).jar
org.springframework.core-x.y.z.M(a).jar
org.springframework.expression-x.y.z.M(a).jar
org.springframework.web-x.y.z.M(a).jar
org.springframework.web.servlet-x.y.z.M(a).jar
Finally add struts2-spring-plugin-x.y.z.jar in your WEB-INF/lib from your struts lib directory. If you are using Eclipse then you may face an exception java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener.
To fix this problem, you should have to go in Marker tab and righ click on the class dependencies one by one and do Quick fix to publish/export all the dependences. Finally make sure there is no dependency conflict available under the marker tab.
Now let us setup the web.xml for the Struts-Spring integration as follows β
<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring's configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file
Let us create a simple action class called User.java with two properties - firstName and lastName.
package com.tutorialspoint.struts2;
public class User {
private String firstName;
private String lastName;
public String execute() {
return "success";
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Now let us create the applicationContext.xml spring configuration file and instantiate the User.java class. As mentioned earlier, this file should be under the WEB-INF folder β
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id = "userClass" class = "com.tutorialspoint.struts2.User">
<property name = "firstName" value = "Michael" />
<property name = "lastName" value = "Jackson" />
</bean>
</beans>
As seen above, we have configured the user bean and we have injected the values Michael and Jackson into the bean. We have also given this bean a name "userClass", so that we can reuse this elsewhere. Next let us create the User.jsp in the WebContent folder β
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World From Struts2 - Spring integration</h1>
<s:form>
<s:textfield name = "firstName" label = "First Name"/><br/>
<s:textfield name = "lastName" label = "Last Name"/><br/>
</s:form>
</body>
</html>
The User.jsp file is pretty straight forward. It serves only one purpose - to display the values of the firstname and lastname of the user object. Finally, let us put all entities together using the struts.xml file.
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "user" class="userClass"
method = "execute">
<result name = "success">/User.jsp</result>
</action>
</package>
</struts>
The important thing to note is that we are using the id userClass to refer to the class. This means that we are using spring to do the dependency injection for the User class.
Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/User.jsp. This will produce the following screen β
We have now seen how to bring two great frameworks together. This concludes the Struts - Spring integration chapter.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2514,
"s": 2246,
"text": "Spring is a popular web framework that provides easy integration with lots of common web tasks. So the question is, why do we need Spring when we have Struts2? Well, Spring is more than a MVC framework - it offers many other goodies which are not available in Struts."
},
{
"code": null,
"e": 2691,
"s": 2514,
"text": "For example: dependency injection that can be useful to any framework. In this chapter, we will go through a simple example to see how to integrate Spring and Struts2 together."
},
{
"code": null,
"e": 2902,
"s": 2691,
"text": "First of all, you need to add the following files to the project's build path from Spring installation. You can download and install latest version of Spring Framework from https://www.springsource.org/download"
},
{
"code": null,
"e": 2941,
"s": 2902,
"text": "org.springframework.asm-x.y.z.M(a).jar"
},
{
"code": null,
"e": 2982,
"s": 2941,
"text": "org.springframework.beans-x.y.z.M(a).jar"
},
{
"code": null,
"e": 3025,
"s": 2982,
"text": "org.springframework.context-x.y.z.M(a).jar"
},
{
"code": null,
"e": 3065,
"s": 3025,
"text": "org.springframework.core-x.y.z.M(a).jar"
},
{
"code": null,
"e": 3111,
"s": 3065,
"text": "org.springframework.expression-x.y.z.M(a).jar"
},
{
"code": null,
"e": 3150,
"s": 3111,
"text": "org.springframework.web-x.y.z.M(a).jar"
},
{
"code": null,
"e": 3197,
"s": 3150,
"text": "org.springframework.web.servlet-x.y.z.M(a).jar"
},
{
"code": null,
"e": 3438,
"s": 3197,
"text": "Finally add struts2-spring-plugin-x.y.z.jar in your WEB-INF/lib from your struts lib directory. If you are using Eclipse then you may face an exception java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener."
},
{
"code": null,
"e": 3685,
"s": 3438,
"text": "To fix this problem, you should have to go in Marker tab and righ click on the class dependencies one by one and do Quick fix to publish/export all the dependences. Finally make sure there is no dependency conflict available under the marker tab."
},
{
"code": null,
"e": 3761,
"s": 3685,
"text": "Now let us setup the web.xml for the Struts-Spring integration as follows β"
},
{
"code": null,
"e": 4710,
"s": 3761,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id = \"WebApp_ID\" version = \"3.0\">\n\t\n <display-name>Struts 2</display-name>\n \n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n\n <listener>\n <listener-class>\n org.springframework.web.context.ContextLoaderListener\n </listener-class>\n </listener>\n\n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>\n org.apache.struts2.dispatcher.FilterDispatcher\n </filter-class>\n </filter>\n\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</web-app>"
},
{
"code": null,
"e": 4981,
"s": 4710,
"text": "The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring's configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file"
},
{
"code": null,
"e": 5080,
"s": 4981,
"text": "Let us create a simple action class called User.java with two properties - firstName and lastName."
},
{
"code": null,
"e": 5553,
"s": 5080,
"text": "package com.tutorialspoint.struts2;\n\npublic class User {\n private String firstName;\n private String lastName;\n\n public String execute() {\n return \"success\";\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n}"
},
{
"code": null,
"e": 5730,
"s": 5553,
"text": "Now let us create the applicationContext.xml spring configuration file and instantiate the User.java class. As mentioned earlier, this file should be under the WEB-INF folder β"
},
{
"code": null,
"e": 6086,
"s": 5730,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \n\"http://www.springframework.org/dtd/spring-beans.dtd\">\n<beans>\n <bean id = \"userClass\" class = \"com.tutorialspoint.struts2.User\">\n <property name = \"firstName\" value = \"Michael\" />\n <property name = \"lastName\" value = \"Jackson\" />\n </bean>\n</beans>"
},
{
"code": null,
"e": 6346,
"s": 6086,
"text": "As seen above, we have configured the user bean and we have injected the values Michael and Jackson into the bean. We have also given this bean a name \"userClass\", so that we can reuse this elsewhere. Next let us create the User.jsp in the WebContent folder β"
},
{
"code": null,
"e": 6939,
"s": 6346,
"text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n <h1>Hello World From Struts2 - Spring integration</h1>\n\n <s:form>\n <s:textfield name = \"firstName\" label = \"First Name\"/><br/>\n <s:textfield name = \"lastName\" label = \"Last Name\"/><br/>\n </s:form>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7155,
"s": 6939,
"text": "The User.jsp file is pretty straight forward. It serves only one purpose - to display the values of the firstname and lastname of the user object. Finally, let us put all entities together using the struts.xml file."
},
{
"code": null,
"e": 7636,
"s": 7155,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n <action name = \"user\" class=\"userClass\" \n method = \"execute\">\n <result name = \"success\">/User.jsp</result>\n </action>\n </package>\n</struts>"
},
{
"code": null,
"e": 7812,
"s": 7636,
"text": "The important thing to note is that we are using the id userClass to refer to the class. This means that we are using spring to do the dependency injection for the User class."
},
{
"code": null,
"e": 8096,
"s": 7812,
"text": "Now right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/User.jsp. This will produce the following screen β"
},
{
"code": null,
"e": 8213,
"s": 8096,
"text": "We have now seen how to bring two great frameworks together. This concludes the Struts - Spring integration chapter."
},
{
"code": null,
"e": 8220,
"s": 8213,
"text": " Print"
},
{
"code": null,
"e": 8231,
"s": 8220,
"text": " Add Notes"
}
] |
Tryit Editor v3.6 - Show Node.js
|
var http = require('http');
β
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "var http = require('http');"
},
{
"code": null,
"e": 30,
"s": 28,
"text": "β"
},
{
"code": null,
"e": 56,
"s": 30,
"text": "//create a server object:"
},
{
"code": null,
"e": 96,
"s": 56,
"text": "http.createServer(function (req, res) {"
},
{
"code": null,
"e": 158,
"s": 96,
"text": " res.write('Hello World!'); //write a response to the client"
},
{
"code": null,
"e": 190,
"s": 158,
"text": " res.end(); //end the response"
}
] |
MYBATIS - Create Operation
|
To perform any Create, Read, Update, and Delete (CRUD) operation using MyBATIS, you would need to create a Plain Old Java Objects (POJO) class corresponding to the table. This class describes the objects that will "model" database table rows.
The POJO class would have implementation for all the methods required to perform desired operations.
Create the STUDENT table in MySQL database as shown below β
mysql> CREATE TABLE details.student(
-> ID int(10) NOT NULL AUTO_INCREMENT,
-> NAME varchar(100) NOT NULL,
-> BRANCH varchar(255) NOT NULL,
-> PERCENTAGE int(3) NOT NULL,
-> PHONE int(11) NOT NULL,
-> EMAIL varchar(255) NOT NULL,
-> PRIMARY KEY (`ID`)
->
);
Query OK, 0 rows affected (0.37 sec)
Create a STUDENT class in STUDENT.java file as
public class Student {
private int id;
private String name;
private String branch;
private int percentage;
private int phone;
private String email;
public Student(String name, String branch, int percentage, int phone, String email) {
super();
this.name = name;
this.branch = branch;
this.percentage = percentage;
this.phone = phone;
this.email = email;
}
}
You can define methods to set individual fields in the table. The next chapter explains how to get the values of individual fields.
To define SQL mapping statement using MyBatis, we would use <insert> tag. Inside this tag definition, we would define an "id." Further, the βidβ will be used in the mybatisInsert.java file for executing SQL INSERT query on database. Create student.xml file as shown below β
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace = "Student">
<insert id = "insert" parameterType = "Student">
INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});
<selectKey keyProperty = "id" resultType = "int" order = "AFTER">
select last_insert_id() as id
</selectKey>
</insert>
</mapper>
Here, parameteType β could take a value as string, int, float, double, or any class object based on requirement. In this example, we would pass Student object as a parameter, while calling insert method of SqlSession class.
If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column, or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey> element in an <insert> statement to use or return that database-generated value.
This file would have application level logic to insert records in the Student table. Create and save mybatisInsert.java file as shown below β
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class mybatisInsert {
public static void main(String args[]) throws IOException{
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
//Create a new student object
Student student = new Student("Mohammad","It", 80, 984803322, "Mohammad@gmail.com" );
//Insert student data
session.insert("Student.insert", student);
System.out.println("record inserted successfully");
session.commit();
session.close();
}
}
Here are the steps to compile and run the mybatisInsert.java file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution.
Create Student.xml as shown above.
Create Student.xml as shown above.
Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial.
Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial.
Create Student.java as shown above and compile it.
Create Student.java as shown above and compile it.
Create mybatisInsert.java as shown above and compile it.
Create mybatisInsert.java as shown above and compile it.
Execute mybatisInsert binary to run the program.
Execute mybatisInsert binary to run the program.
You would get the following result, and a record would be created in the STUDENT table.
$java mybatisInsert
Record Inserted Successfully
If you check the STUDENT table, it should display the following result β
mysql> select * from student;
+----+----------+--------+------------+-----------+--------------------+
| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |
+----+----------+--------+------------+-----------+--------------------+
| 1 | Mohammad | It | 80 | 984803322 | Mohammad@gmail.com |
+----+----------+--------+------------+-----------+--------------------+
1 row in set (0.00 sec)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2114,
"s": 1871,
"text": "To perform any Create, Read, Update, and Delete (CRUD) operation using MyBATIS, you would need to create a Plain Old Java Objects (POJO) class corresponding to the table. This class describes the objects that will \"model\" database table rows."
},
{
"code": null,
"e": 2215,
"s": 2114,
"text": "The POJO class would have implementation for all the methods required to perform desired operations."
},
{
"code": null,
"e": 2275,
"s": 2215,
"text": "Create the STUDENT table in MySQL database as shown below β"
},
{
"code": null,
"e": 2610,
"s": 2275,
"text": "mysql> CREATE TABLE details.student(\n -> ID int(10) NOT NULL AUTO_INCREMENT,\n -> NAME varchar(100) NOT NULL,\n -> BRANCH varchar(255) NOT NULL,\n -> PERCENTAGE int(3) NOT NULL,\n -> PHONE int(11) NOT NULL,\n -> EMAIL varchar(255) NOT NULL,\n -> PRIMARY KEY (`ID`)\n -> \n);\nQuery OK, 0 rows affected (0.37 sec)\n"
},
{
"code": null,
"e": 2657,
"s": 2610,
"text": "Create a STUDENT class in STUDENT.java file as"
},
{
"code": null,
"e": 3079,
"s": 2657,
"text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(String name, String branch, int percentage, int phone, String email) {\n super();\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n \n}"
},
{
"code": null,
"e": 3211,
"s": 3079,
"text": "You can define methods to set individual fields in the table. The next chapter explains how to get the values of individual fields."
},
{
"code": null,
"e": 3485,
"s": 3211,
"text": "To define SQL mapping statement using MyBatis, we would use <insert> tag. Inside this tag definition, we would define an \"id.\" Further, the βidβ will be used in the mybatisInsert.java file for executing SQL INSERT query on database. Create student.xml file as shown below β"
},
{
"code": null,
"e": 4026,
"s": 3485,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\n\n <insert id = \"insert\" parameterType = \"Student\">\n INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});\n\t\t\t\n <selectKey keyProperty = \"id\" resultType = \"int\" order = \"AFTER\">\n select last_insert_id() as id\n </selectKey> \n\t\t\t\n </insert>\n \t\n</mapper>"
},
{
"code": null,
"e": 4250,
"s": 4026,
"text": "Here, parameteType β could take a value as string, int, float, double, or any class object based on requirement. In this example, we would pass Student object as a parameter, while calling insert method of SqlSession class."
},
{
"code": null,
"e": 4476,
"s": 4250,
"text": "If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column, or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey> element in an <insert> statement to use or return that database-generated value."
},
{
"code": null,
"e": 4618,
"s": 4476,
"text": "This file would have application level logic to insert records in the Student table. Create and save mybatisInsert.java file as shown below β"
},
{
"code": null,
"e": 5543,
"s": 4618,
"text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisInsert { \n\n public static void main(String args[]) throws IOException{\n \n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //Create a new student object\n Student student = new Student(\"Mohammad\",\"It\", 80, 984803322, \"Mohammad@gmail.com\" ); \n \n //Insert student data \n session.insert(\"Student.insert\", student);\n System.out.println(\"record inserted successfully\");\n session.commit();\n session.close();\n\t\t\t\n }\n \n}"
},
{
"code": null,
"e": 5716,
"s": 5543,
"text": "Here are the steps to compile and run the mybatisInsert.java file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution."
},
{
"code": null,
"e": 5751,
"s": 5716,
"text": "Create Student.xml as shown above."
},
{
"code": null,
"e": 5786,
"s": 5751,
"text": "Create Student.xml as shown above."
},
{
"code": null,
"e": 5881,
"s": 5786,
"text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial."
},
{
"code": null,
"e": 5976,
"s": 5881,
"text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial."
},
{
"code": null,
"e": 6027,
"s": 5976,
"text": "Create Student.java as shown above and compile it."
},
{
"code": null,
"e": 6078,
"s": 6027,
"text": "Create Student.java as shown above and compile it."
},
{
"code": null,
"e": 6135,
"s": 6078,
"text": "Create mybatisInsert.java as shown above and compile it."
},
{
"code": null,
"e": 6192,
"s": 6135,
"text": "Create mybatisInsert.java as shown above and compile it."
},
{
"code": null,
"e": 6241,
"s": 6192,
"text": "Execute mybatisInsert binary to run the program."
},
{
"code": null,
"e": 6290,
"s": 6241,
"text": "Execute mybatisInsert binary to run the program."
},
{
"code": null,
"e": 6378,
"s": 6290,
"text": "You would get the following result, and a record would be created in the STUDENT table."
},
{
"code": null,
"e": 6428,
"s": 6378,
"text": "$java mybatisInsert\nRecord Inserted Successfully\n"
},
{
"code": null,
"e": 6501,
"s": 6428,
"text": "If you check the STUDENT table, it should display the following result β"
},
{
"code": null,
"e": 6921,
"s": 6501,
"text": "mysql> select * from student;\n+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | Mohammad@gmail.com |\n+----+----------+--------+------------+-----------+--------------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 6928,
"s": 6921,
"text": " Print"
},
{
"code": null,
"e": 6939,
"s": 6928,
"text": " Add Notes"
}
] |
How to add key/value pair to a JavaScript object? - GeeksforGeeks
|
22 Apr, 2019
In order to add key/value pair to a JavaScript object, Either we use dot notation or square bracket notation. Both methods are widely accepted.
Example 1: This example adds {βnextFavColorβ : βredβ} to the GFG_p object by using dot notation.
<!DOCTYPE html> <html> <head> <title> JavaScript | Add a key/value pair to JavaScript object </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="GFG_up" style="color:red;"></p> <button onclick = "Geeks()"> Click to add </button> <p id="GFG_down" style="color:green;"></p> <script> var GFG_p = {fName:"Geeks", lName:"forGeeks", age:100, favColor:"green"}; var p_up = document.getElementById("GFG_up"); var p_down = document.getElementById("GFG_down"); p_up.innerHTML = JSON.stringify(GFG_p); function Geeks() { GFG_p.nextFavColor = "Red"; p_down.innerHTML = JSON.stringify(GFG_p); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example adds {βthirdFavColorβ : βblueβ} to the GFG_p object by using square bracket notation.
<!DOCTYPE html> <html> <head> <title> JavaScript | Add a key/value pair to JavaScript object </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="GFG_up" style="color:blue;"></p> <button onclick = "Geeks()"> Click to add </button> <p id="GFG_down" style="color:green;"></p> <script> var GFG_p = {fName:"Geeks", lName:"forGeeks", age:100, favColor:"green"}; var p_up = document.getElementById("GFG_up"); var p_down = document.getElementById("GFG_down"); p_up.innerHTML = JSON.stringify(GFG_p); function Geeks() { GFG_p["thirdFavColor"] = "blue"; p_down.innerHTML = JSON.stringify(GFG_p); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-object
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24395,
"s": 24367,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 24539,
"s": 24395,
"text": "In order to add key/value pair to a JavaScript object, Either we use dot notation or square bracket notation. Both methods are widely accepted."
},
{
"code": null,
"e": 24636,
"s": 24539,
"text": "Example 1: This example adds {βnextFavColorβ : βredβ} to the GFG_p object by using dot notation."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Add a key/value pair to JavaScript object </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"GFG_up\" style=\"color:red;\"></p> <button onclick = \"Geeks()\"> Click to add </button> <p id=\"GFG_down\" style=\"color:green;\"></p> <script> var GFG_p = {fName:\"Geeks\", lName:\"forGeeks\", age:100, favColor:\"green\"}; var p_up = document.getElementById(\"GFG_up\"); var p_down = document.getElementById(\"GFG_down\"); p_up.innerHTML = JSON.stringify(GFG_p); function Geeks() { GFG_p.nextFavColor = \"Red\"; p_down.innerHTML = JSON.stringify(GFG_p); } </script> </body> </html> ",
"e": 25540,
"s": 24636,
"text": null
},
{
"code": null,
"e": 25548,
"s": 25540,
"text": "Output:"
},
{
"code": null,
"e": 25579,
"s": 25548,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 25609,
"s": 25579,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 25719,
"s": 25609,
"text": "Example 2: This example adds {βthirdFavColorβ : βblueβ} to the GFG_p object by using square bracket notation."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Add a key/value pair to JavaScript object </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id=\"GFG_up\" style=\"color:blue;\"></p> <button onclick = \"Geeks()\"> Click to add </button> <p id=\"GFG_down\" style=\"color:green;\"></p> <script> var GFG_p = {fName:\"Geeks\", lName:\"forGeeks\", age:100, favColor:\"green\"}; var p_up = document.getElementById(\"GFG_up\"); var p_down = document.getElementById(\"GFG_down\"); p_up.innerHTML = JSON.stringify(GFG_p); function Geeks() { GFG_p[\"thirdFavColor\"] = \"blue\"; p_down.innerHTML = JSON.stringify(GFG_p); } </script> </body> </html> ",
"e": 26630,
"s": 25719,
"text": null
},
{
"code": null,
"e": 26638,
"s": 26630,
"text": "Output:"
},
{
"code": null,
"e": 26669,
"s": 26638,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26699,
"s": 26669,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26717,
"s": 26699,
"text": "javascript-object"
},
{
"code": null,
"e": 26728,
"s": 26717,
"text": "JavaScript"
},
{
"code": null,
"e": 26745,
"s": 26728,
"text": "Web Technologies"
},
{
"code": null,
"e": 26772,
"s": 26745,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26870,
"s": 26772,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26879,
"s": 26870,
"text": "Comments"
},
{
"code": null,
"e": 26892,
"s": 26879,
"text": "Old Comments"
},
{
"code": null,
"e": 26953,
"s": 26892,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26998,
"s": 26953,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27070,
"s": 26998,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27122,
"s": 27070,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27168,
"s": 27122,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27224,
"s": 27168,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27257,
"s": 27224,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27319,
"s": 27257,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27362,
"s": 27319,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Apex - Governer Limits
|
Governor execution limits ensure the efficient use of resources on the Force.com multitenant platform. It is the limit specified by the Salesforce.com on code execution for efficient processing.
As we know, Apex runs in multi-tenant environment, i.e., a single resource is shared by all the customers and organizations. So, it is necessary to make sure that no one monopolizes the resources and hence Salesforce.com has created the set of limits which governs and limits the code execution. Whenever any of the governor limits are crossed, it will throw error and will halt the execution of program.
From a Developer's perspective, it is important to ensure that our code should be scalable and should not hit the limits.
All these limits are applied on per transaction basis. A single trigger execution is one transaction.
As we have seen, the trigger design pattern helps avoid the limit error. We will now see other important limits.
You can issue only 100 queries per transaction, that is, when your code will issue more than 100 SOQL queries then it will throw error.
This example shows how SOQL query limit can be reached β
The following trigger iterates over a list of customers and updates the child record's (Invoice) description with string 'Ok to Pay'.
// Helper class:Below code needs o be checked.
public class CustomerTriggerHelper {
public static void isAfterUpdateCall(Trigger.new) {
createInvoiceRecords(trigger.new);//Method call
updateCustomerDescription(trigger.new);
}
// Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
// Method to update the invoice records
public static updateCustomerDescription (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCust: customerList) {
List<apex_customer__c> invList = [SELECT Id, Name,
APEX_Description__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];
// This query will fire for the number of records customer list has and will
// hit the governor limit when records are more than 100
for (APEX_Invoice__c objInv: invList) {
objInv.APEX_Description__c = 'OK To Pay';
update objInv;
// Update invoice, this will also hit the governor limit for DML if large
// number(150) of records are there
}
}
}
}
When the 'updateCustomerDescription' method is called and the number of customer records are more than 100, then it will hit the SOQL limit. To avoid this, never write the SOQL query in the For Loop. In this case, the SOQL query has been written in the For loop.
Following is an example which will show how to avoid the DML as well as the SOQL limit. We have used the nested relationship query to fetch the invoice records and used the context variable trigger.newMap to get the map of id and Customer records.
// SOQL-Good Way to Write Query and avoid limit exception
// Helper Class
public class CustomerTriggerHelper {
public static void isAfterUpdateCall(Trigger.new) {
createInvoiceRecords(trigger.new); //Method call
updateCustomerDescription(trigger.new, trigger.newMap);
}
// Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c> customerList) {
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
// condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
InvoiceList.add(objInvoice);
}
}
insert InvoiceList; // DML to insert the Invoice List in SFDC
}
// Method to update the invoice records
public static updateCustomerDescription (List<apex_customer__c>
customerList, Map<id, apex_customer__c> newMapVariable) {
List<apex_customer__c> customerListWithInvoice = [SELECT id,
Name,(SELECT Id, Name, APEX_Description__c FROM APEX_Invoice__r) FROM
APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];
// Query will be for only one time and fetches all the records
List<apex_invoice__c> invoiceToUpdate = new
List<apex_invoice__c>();
for (APEX_Customer__c objCust: customerList) {
for (APEX_Invoice__c objInv: invList) {
objInv.APEX_Description__c = 'OK To Pay';
invoiceToUpdate.add(objInv);
// Add the modified records to List
}
}
update invoiceToUpdate;
}
}
This example shows the Bulk trigger along with the trigger helper class pattern. You must save the helper class first and then save the trigger.
Note β Paste the below code in 'CustomerTriggerHelper' class which we have created earlier.
// Helper Class
public class CustomerTriggerHelper {
public static void isAfterUpdateCall(List<apex_customer__c> customerList,
Map<id, apex_customer__c> mapIdToCustomers, Map<id, apex_customer__c>
mapOldItToCustomers) {
createInvoiceRecords(customerList, mapOldItToCustomers); //Method call
updateCustomerDescription(customerList,mapIdToCustomers,
mapOldItToCustomers);
}
// Method To Create Invoice Records
public static void createInvoiceRecords (List<apex_customer__c>
customerList, Map<id, apex_customer__c> mapOldItToCustomers) {
List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
List<apex_customer__c> customerToInvoice = [SELECT id, Name FROM
APEX_Customer__c LIMIT 1];
for (APEX_Customer__c objCustomer: customerList) {
if (objCustomer.APEX_Customer_Status__c == 'Active' &&
mapOldItToCustomers.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
//condition to check the old value and new value
APEX_Invoice__c objInvoice = new APEX_Invoice__c();
objInvoice.APEX_Status__c = 'Pending';
objInvoice.APEX_Customer__c = objCustomer.id;
InvoiceList.add(objInvoice);
}
}
system.debug('InvoiceList&&&'+InvoiceList);
insert InvoiceList;
// DML to insert the Invoice List in SFDC. This also follows the Bulk pattern
}
// Method to update the invoice records
public static void updateCustomerDescription (List<apex_customer__c>
customerList, Map<id, apex_customer__c> newMapVariable, Map<id,
apex_customer__c> oldCustomerMap) {
List<apex_customer__c> customerListWithInvoice = [SELECT id,
Name,(SELECT Id, Name, APEX_Description__c FROM Invoices__r) FROM
APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];
// Query will be for only one time and fetches all the records
List<apex_invoice__c> invoiceToUpdate = new List<apex_invoice__c>();
List<apex_invoice__c> invoiceFetched = new List<apex_invoice__c>();
invoiceFetched = customerListWithInvoice[0].Invoices__r;
system.debug('invoiceFetched'+invoiceFetched);
system.debug('customerListWithInvoice****'+customerListWithInvoice);
for (APEX_Customer__c objCust: customerList) {
system.debug('objCust.Invoices__r'+objCust.Invoices__r);
if (objCust.APEX_Active__c == true &&
oldCustomerMap.get(objCust.id).APEX_Active__c == false) {
for (APEX_Invoice__c objInv: invoiceFetched) {
system.debug('I am in For Loop'+objInv);
objInv.APEX_Description__c = 'OK To Pay';
invoiceToUpdate.add(objInv);
// Add the modified records to List
}
}
}
system.debug('Value of List ***'+invoiceToUpdate);
update invoiceToUpdate;
// This statement is Bulk DML which performs the DML on List and avoids
// the DML Governor limit
}
}
// Trigger Code for this class: Paste this code in 'Customer_After_Insert'
// trigger on Customer Object
trigger Customer_After_Insert on APEX_Customer__c (after update) {
CustomerTriggerHelper.isAfterUpdateCall(Trigger.new, trigger.newMap,
trigger.oldMap);
// Trigger calls the helper class and does not have any code in Trigger
}
Following table lists down the important governor limits.
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2247,
"s": 2052,
"text": "Governor execution limits ensure the efficient use of resources on the Force.com multitenant platform. It is the limit specified by the Salesforce.com on code execution for efficient processing."
},
{
"code": null,
"e": 2652,
"s": 2247,
"text": "As we know, Apex runs in multi-tenant environment, i.e., a single resource is shared by all the customers and organizations. So, it is necessary to make sure that no one monopolizes the resources and hence Salesforce.com has created the set of limits which governs and limits the code execution. Whenever any of the governor limits are crossed, it will throw error and will halt the execution of program."
},
{
"code": null,
"e": 2774,
"s": 2652,
"text": "From a Developer's perspective, it is important to ensure that our code should be scalable and should not hit the limits."
},
{
"code": null,
"e": 2876,
"s": 2774,
"text": "All these limits are applied on per transaction basis. A single trigger execution is one transaction."
},
{
"code": null,
"e": 2989,
"s": 2876,
"text": "As we have seen, the trigger design pattern helps avoid the limit error. We will now see other important limits."
},
{
"code": null,
"e": 3125,
"s": 2989,
"text": "You can issue only 100 queries per transaction, that is, when your code will issue more than 100 SOQL queries then it will throw error."
},
{
"code": null,
"e": 3182,
"s": 3125,
"text": "This example shows how SOQL query limit can be reached β"
},
{
"code": null,
"e": 3316,
"s": 3182,
"text": "The following trigger iterates over a list of customers and updates the child record's (Invoice) description with string 'Ok to Pay'."
},
{
"code": null,
"e": 5017,
"s": 3316,
"text": "// Helper class:Below code needs o be checked.\npublic class CustomerTriggerHelper {\n \n public static void isAfterUpdateCall(Trigger.new) {\n createInvoiceRecords(trigger.new);//Method call\n updateCustomerDescription(trigger.new);\n }\n \n // Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c> customerList) {\n for (APEX_Customer__c objCustomer: customerList) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n \n // Method to update the invoice records\n public static updateCustomerDescription (List<apex_customer__c> customerList) {\n for (APEX_Customer__c objCust: customerList) {\n List<apex_customer__c> invList = [SELECT Id, Name,\n APEX_Description__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];\n \n // This query will fire for the number of records customer list has and will\n // hit the governor limit when records are more than 100\n for (APEX_Invoice__c objInv: invList) {\n objInv.APEX_Description__c = 'OK To Pay';\n update objInv;\n // Update invoice, this will also hit the governor limit for DML if large\n // number(150) of records are there\n }\n }\n }\n}"
},
{
"code": null,
"e": 5280,
"s": 5017,
"text": "When the 'updateCustomerDescription' method is called and the number of customer records are more than 100, then it will hit the SOQL limit. To avoid this, never write the SOQL query in the For Loop. In this case, the SOQL query has been written in the For loop."
},
{
"code": null,
"e": 5528,
"s": 5280,
"text": "Following is an example which will show how to avoid the DML as well as the SOQL limit. We have used the nested relationship query to fetch the invoice records and used the context variable trigger.newMap to get the map of id and Customer records."
},
{
"code": null,
"e": 7339,
"s": 5528,
"text": "// SOQL-Good Way to Write Query and avoid limit exception\n// Helper Class\npublic class CustomerTriggerHelper {\n public static void isAfterUpdateCall(Trigger.new) {\n createInvoiceRecords(trigger.new); //Method call\n updateCustomerDescription(trigger.new, trigger.newMap);\n }\n \n // Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c> customerList) {\n for (APEX_Customer__c objCustomer: customerList) {\n \n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n InvoiceList.add(objInvoice);\n }\n }\n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n \n // Method to update the invoice records\n public static updateCustomerDescription (List<apex_customer__c>\n customerList, Map<id, apex_customer__c> newMapVariable) {\n List<apex_customer__c> customerListWithInvoice = [SELECT id,\n Name,(SELECT Id, Name, APEX_Description__c FROM APEX_Invoice__r) FROM\n APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];\n \n // Query will be for only one time and fetches all the records\n List<apex_invoice__c> invoiceToUpdate = new\n List<apex_invoice__c>();\n \n for (APEX_Customer__c objCust: customerList) {\n for (APEX_Invoice__c objInv: invList) {\n objInv.APEX_Description__c = 'OK To Pay';\n invoiceToUpdate.add(objInv);\n // Add the modified records to List\n }\n }\n update invoiceToUpdate;\n }\n}"
},
{
"code": null,
"e": 7484,
"s": 7339,
"text": "This example shows the Bulk trigger along with the trigger helper class pattern. You must save the helper class first and then save the trigger."
},
{
"code": null,
"e": 7576,
"s": 7484,
"text": "Note β Paste the below code in 'CustomerTriggerHelper' class which we have created earlier."
},
{
"code": null,
"e": 10958,
"s": 7576,
"text": "// Helper Class\npublic class CustomerTriggerHelper {\n public static void isAfterUpdateCall(List<apex_customer__c> customerList,\n Map<id, apex_customer__c> mapIdToCustomers, Map<id, apex_customer__c>\n mapOldItToCustomers) {\n createInvoiceRecords(customerList, mapOldItToCustomers); //Method call\n updateCustomerDescription(customerList,mapIdToCustomers,\n mapOldItToCustomers);\n }\n \n // Method To Create Invoice Records\n public static void createInvoiceRecords (List<apex_customer__c>\n customerList, Map<id, apex_customer__c> mapOldItToCustomers) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n List<apex_customer__c> customerToInvoice = [SELECT id, Name FROM\n APEX_Customer__c LIMIT 1];\n \n for (APEX_Customer__c objCustomer: customerList) {\n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n mapOldItToCustomers.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n //condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n objInvoice.APEX_Customer__c = objCustomer.id;\n InvoiceList.add(objInvoice);\n }\n }\n system.debug('InvoiceList&&&'+InvoiceList);\n insert InvoiceList;\n // DML to insert the Invoice List in SFDC. This also follows the Bulk pattern\n }\n \n // Method to update the invoice records\n public static void updateCustomerDescription (List<apex_customer__c>\n customerList, Map<id, apex_customer__c> newMapVariable, Map<id,\n apex_customer__c> oldCustomerMap) {\n List<apex_customer__c> customerListWithInvoice = [SELECT id,\n Name,(SELECT Id, Name, APEX_Description__c FROM Invoices__r) FROM\n APEX_Customer__c WHERE Id IN :newMapVariable.keySet()];\n \n // Query will be for only one time and fetches all the records\n List<apex_invoice__c> invoiceToUpdate = new List<apex_invoice__c>();\n List<apex_invoice__c> invoiceFetched = new List<apex_invoice__c>();\n invoiceFetched = customerListWithInvoice[0].Invoices__r;\n system.debug('invoiceFetched'+invoiceFetched);\n system.debug('customerListWithInvoice****'+customerListWithInvoice);\n \n for (APEX_Customer__c objCust: customerList) {\n system.debug('objCust.Invoices__r'+objCust.Invoices__r);\n if (objCust.APEX_Active__c == true &&\n oldCustomerMap.get(objCust.id).APEX_Active__c == false) {\n for (APEX_Invoice__c objInv: invoiceFetched) {\n system.debug('I am in For Loop'+objInv);\n objInv.APEX_Description__c = 'OK To Pay';\n invoiceToUpdate.add(objInv);\n // Add the modified records to List\n }\n }\n }\n system.debug('Value of List ***'+invoiceToUpdate);\n update invoiceToUpdate;\n // This statement is Bulk DML which performs the DML on List and avoids\n // the DML Governor limit\n }\n}\n\n// Trigger Code for this class: Paste this code in 'Customer_After_Insert'\n// trigger on Customer Object\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n CustomerTriggerHelper.isAfterUpdateCall(Trigger.new, trigger.newMap,\n trigger.oldMap);\n // Trigger calls the helper class and does not have any code in Trigger\n}"
},
{
"code": null,
"e": 11016,
"s": 10958,
"text": "Following table lists down the important governor limits."
},
{
"code": null,
"e": 11049,
"s": 11016,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11062,
"s": 11049,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 11094,
"s": 11062,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11102,
"s": 11094,
"text": " Uplatz"
},
{
"code": null,
"e": 11135,
"s": 11102,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11160,
"s": 11135,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 11193,
"s": 11160,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 11208,
"s": 11193,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 11241,
"s": 11208,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11254,
"s": 11241,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 11289,
"s": 11254,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11301,
"s": 11289,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 11308,
"s": 11301,
"text": " Print"
},
{
"code": null,
"e": 11319,
"s": 11308,
"text": " Add Notes"
}
] |
Closure in JavaScript - GeeksforGeeks
|
13 May, 2021
Most of the JavaScript Developers use closure consciously or unconsciously. Even if they do unconsciously it works fine in most of the cases. But knowing closure will provide better control over the code when using them. And another reason for learning closure is that it is the most frequently asked question in the interview for the JavaScript developers. Prerequisite:: Variable Scope in JavaScript
Letβs see and understand closure through an example.
Example 1:
Javascript
// Explanation of closure/* 1 */ function foo()/* 2 */ {/* 3 */ var b = 1;/* 4 */ function inner(){/* 5 */ return b;/* 6 */ }/* 7 */ return inner;/* 8 */ }/* 9 */ var get_func_inner = foo(); /* 10 */ console.log(get_func_inner());/* 11 */ console.log(get_func_inner());/* 12 */ console.log(get_func_inner());
Explanation:Interesting thing to note here is from line number 9 to line number 12. At line number 9 we are done with the execution of function foo() and the entire body of function inner() is returned and stored in var get_func_inner, due to the line 7 return inner. [The return statement does not execute the inner function β function is executed only when followed by (), but rather the return statement returns the reference to the function as a function in JavaScript is also an object.]
We can access the variable b which is defined in function foo() through function inner() as the later preserves the scope chain of enclosing function at the time of execution of enclosing function i.e. the inner function knows the value of b through itβs scope chain. This is closure in action that is inner function can have access to the outer function variables as well as all the global variables. Output of the above code:
In order to see the variable and function bound within closure we can write as:
Javascript
/* 13 */ console.dir(get_func_inner);
Output:
As we can see the variables within the closure in the scope section.
Definition of Closure:
In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] -Wikipedia
or
In other words, closure is created when a child function keep the environment of the parent scope even after the parent function has already executed
Now lets look at the another example.
Example 2:
Javascript
function foo(outer_arg) { function inner(inner_arg) { return outer_arg + inner_arg; } return inner;}var get_func_inner = foo(5); console.log(get_func_inner(4));console.log(get_func_inner(3));
Explanation: In the above example we used a parameter function rather than a default one. Note even when we are done with the execution of foo(5) we can access the outer_arg variable from the inner function. And on execution of inner function produce the summation of outer_arg and inner_arg as desired.
Output:
Now letβs see an example of closure within a loop. In this example we would to store a anonymous function at every index of an array.
Example 3:
Javascript
// Outer functionfunction outer(){ var arr = []; var i; for (i = 0; i < 4; i++) { // storing anonymous function arr[i] = function () { return i; } } // returning the array. return arr;} var get_arr = outer(); console.log(get_arr[0]());console.log(get_arr[1]());console.log(get_arr[2]());console.log(get_arr[3]());
Output:
Explanation: Did you guess the right answer? In the above code we have created four closure which point to the variable i which is local variable to the function outer. Closure donβt remember the value of the variable it only points to the variable or stores the reference of the variable and hence, returns the current value. In the above code when we try to update the value of it gets reflected to all because the closure stores the reference.
Lets see an correct way to write the above code so as to get different values of i at different index.
Example 4:
Javascript
// Outer functionfunction outer(){ function create_Closure(val) { return function() { return val; } } var arr = []; var i; for (i = 0; i < 4; i++) { arr[i] = create_Closure(i); } return arr;}var get_arr = outer();console.log(get_arr[0]());console.log(get_arr[1]());console.log(get_arr[2]());console.log(get_arr[3]());
Output:
Explanation: In the above code we are updating the argument of the function create_Closure with every call. Hence, we get different values of i at different index.
Note : It may be slightly difficult to get the concept of closure at once but try experimenting with closure in different scenarios like for creating getter/setter, callbacks and so on.
Reference: βObject Oriented JavaScriptβ by Stoyan Stefanov This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ashutoshrcf
Manas Yadav
nidhi_biet
ranjan prasad
Akanksha_Rai
clintra
JavaScript-ES
javascript-math
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
Node.js | fs.writeFileSync() Method
Set the value of an input field in JavaScript
How to read a local text file using JavaScript?
|
[
{
"code": null,
"e": 24312,
"s": 24284,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 24715,
"s": 24312,
"text": "Most of the JavaScript Developers use closure consciously or unconsciously. Even if they do unconsciously it works fine in most of the cases. But knowing closure will provide better control over the code when using them. And another reason for learning closure is that it is the most frequently asked question in the interview for the JavaScript developers. Prerequisite:: Variable Scope in JavaScript "
},
{
"code": null,
"e": 24769,
"s": 24715,
"text": "Letβs see and understand closure through an example. "
},
{
"code": null,
"e": 24781,
"s": 24769,
"text": "Example 1: "
},
{
"code": null,
"e": 24792,
"s": 24781,
"text": "Javascript"
},
{
"code": "// Explanation of closure/* 1 */ function foo()/* 2 */ {/* 3 */ var b = 1;/* 4 */ function inner(){/* 5 */ return b;/* 6 */ }/* 7 */ return inner;/* 8 */ }/* 9 */ var get_func_inner = foo(); /* 10 */ console.log(get_func_inner());/* 11 */ console.log(get_func_inner());/* 12 */ console.log(get_func_inner());",
"e": 25228,
"s": 24792,
"text": null
},
{
"code": null,
"e": 25721,
"s": 25228,
"text": "Explanation:Interesting thing to note here is from line number 9 to line number 12. At line number 9 we are done with the execution of function foo() and the entire body of function inner() is returned and stored in var get_func_inner, due to the line 7 return inner. [The return statement does not execute the inner function β function is executed only when followed by (), but rather the return statement returns the reference to the function as a function in JavaScript is also an object.]"
},
{
"code": null,
"e": 26150,
"s": 25721,
"text": "We can access the variable b which is defined in function foo() through function inner() as the later preserves the scope chain of enclosing function at the time of execution of enclosing function i.e. the inner function knows the value of b through itβs scope chain. This is closure in action that is inner function can have access to the outer function variables as well as all the global variables. Output of the above code: "
},
{
"code": null,
"e": 26232,
"s": 26150,
"text": "In order to see the variable and function bound within closure we can write as: "
},
{
"code": null,
"e": 26243,
"s": 26232,
"text": "Javascript"
},
{
"code": "/* 13 */ console.dir(get_func_inner);",
"e": 26289,
"s": 26243,
"text": null
},
{
"code": null,
"e": 26298,
"s": 26289,
"text": "Output: "
},
{
"code": null,
"e": 26367,
"s": 26298,
"text": "As we can see the variables within the closure in the scope section."
},
{
"code": null,
"e": 26391,
"s": 26367,
"text": "Definition of Closure: "
},
{
"code": null,
"e": 26892,
"s": 26391,
"text": "In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] -Wikipedia"
},
{
"code": null,
"e": 26897,
"s": 26892,
"text": " or "
},
{
"code": null,
"e": 27048,
"s": 26897,
"text": "In other words, closure is created when a child function keep the environment of the parent scope even after the parent function has already executed "
},
{
"code": null,
"e": 27087,
"s": 27048,
"text": "Now lets look at the another example. "
},
{
"code": null,
"e": 27100,
"s": 27087,
"text": "Example 2: "
},
{
"code": null,
"e": 27111,
"s": 27100,
"text": "Javascript"
},
{
"code": "function foo(outer_arg) { function inner(inner_arg) { return outer_arg + inner_arg; } return inner;}var get_func_inner = foo(5); console.log(get_func_inner(4));console.log(get_func_inner(3));",
"e": 27320,
"s": 27111,
"text": null
},
{
"code": null,
"e": 27625,
"s": 27320,
"text": "Explanation: In the above example we used a parameter function rather than a default one. Note even when we are done with the execution of foo(5) we can access the outer_arg variable from the inner function. And on execution of inner function produce the summation of outer_arg and inner_arg as desired. "
},
{
"code": null,
"e": 27635,
"s": 27625,
"text": "Output: "
},
{
"code": null,
"e": 27770,
"s": 27635,
"text": "Now letβs see an example of closure within a loop. In this example we would to store a anonymous function at every index of an array. "
},
{
"code": null,
"e": 27783,
"s": 27770,
"text": "Example 3: "
},
{
"code": null,
"e": 27794,
"s": 27783,
"text": "Javascript"
},
{
"code": "// Outer functionfunction outer(){ var arr = []; var i; for (i = 0; i < 4; i++) { // storing anonymous function arr[i] = function () { return i; } } // returning the array. return arr;} var get_arr = outer(); console.log(get_arr[0]());console.log(get_arr[1]());console.log(get_arr[2]());console.log(get_arr[3]());",
"e": 28144,
"s": 27794,
"text": null
},
{
"code": null,
"e": 28153,
"s": 28144,
"text": "Output: "
},
{
"code": null,
"e": 28601,
"s": 28153,
"text": "Explanation: Did you guess the right answer? In the above code we have created four closure which point to the variable i which is local variable to the function outer. Closure donβt remember the value of the variable it only points to the variable or stores the reference of the variable and hence, returns the current value. In the above code when we try to update the value of it gets reflected to all because the closure stores the reference. "
},
{
"code": null,
"e": 28705,
"s": 28601,
"text": "Lets see an correct way to write the above code so as to get different values of i at different index. "
},
{
"code": null,
"e": 28718,
"s": 28705,
"text": "Example 4: "
},
{
"code": null,
"e": 28729,
"s": 28718,
"text": "Javascript"
},
{
"code": "// Outer functionfunction outer(){ function create_Closure(val) { return function() { return val; } } var arr = []; var i; for (i = 0; i < 4; i++) { arr[i] = create_Closure(i); } return arr;}var get_arr = outer();console.log(get_arr[0]());console.log(get_arr[1]());console.log(get_arr[2]());console.log(get_arr[3]());",
"e": 29113,
"s": 28729,
"text": null
},
{
"code": null,
"e": 29122,
"s": 29113,
"text": "Output: "
},
{
"code": null,
"e": 29286,
"s": 29122,
"text": "Explanation: In the above code we are updating the argument of the function create_Closure with every call. Hence, we get different values of i at different index."
},
{
"code": null,
"e": 29473,
"s": 29286,
"text": "Note : It may be slightly difficult to get the concept of closure at once but try experimenting with closure in different scenarios like for creating getter/setter, callbacks and so on. "
},
{
"code": null,
"e": 29951,
"s": 29473,
"text": "Reference: βObject Oriented JavaScriptβ by Stoyan Stefanov This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 29963,
"s": 29951,
"text": "ashutoshrcf"
},
{
"code": null,
"e": 29975,
"s": 29963,
"text": "Manas Yadav"
},
{
"code": null,
"e": 29986,
"s": 29975,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30000,
"s": 29986,
"text": "ranjan prasad"
},
{
"code": null,
"e": 30013,
"s": 30000,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30021,
"s": 30013,
"text": "clintra"
},
{
"code": null,
"e": 30035,
"s": 30021,
"text": "JavaScript-ES"
},
{
"code": null,
"e": 30051,
"s": 30035,
"text": "javascript-math"
},
{
"code": null,
"e": 30067,
"s": 30051,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30078,
"s": 30067,
"text": "JavaScript"
},
{
"code": null,
"e": 30176,
"s": 30078,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30221,
"s": 30176,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30282,
"s": 30221,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30354,
"s": 30282,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30406,
"s": 30354,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30452,
"s": 30406,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 30493,
"s": 30452,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30534,
"s": 30493,
"text": "JavaScript | console.log() with Examples"
},
{
"code": null,
"e": 30570,
"s": 30534,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 30616,
"s": 30570,
"text": "Set the value of an input field in JavaScript"
}
] |
What is CLR (1) Parser?
|
CLR defines canonical lookahead. CLR parsing use the canonical collection of LR (1) items to construct the CLR (1) parsing table. CLR (1) parsing table makes the more number of states as compare to the SLR (1) parsing. In the CLR (1), it can locate the reduce node only in the lookahead symbols.
Working of CLR Parser
Construction of LR (1) collection of items for Grammar
It requires three things
Augmented Grammar
Closure Function
goto Function
Augmented Grammar It is a new Grammar Gβ² which contains a new production
Sβ² β S with all other productions of given grammar G.
Closure
procedure closure (I)
begin
Repeat
for each item A β Ξ± β B Ξ², a in I,
each production B β Ξ³ and
each terminal b β FIRST (Ξ² a)
If B β β Ξ³ is not in I
Add B β β Ξ³, b to I
Until no more elements can be joined to I;
end
goto(I, X): If there is a production A β Ξ± β X Ξ², a in I then goto(I, X) is the closure
of the set of items of A β Ξ± X β Ξ², a.
Algorithm for Construction of LR (1) Set of Items
begin
C = {closure(Sβ²ββS,$)}
Repeat
for each set of items I in C and each grammar symbol X (terminal or non-terminal)
Add goto(I, X) to C
Until no more sets of elements can be added to C.
end.
Construction of Canonical LR Parsing Table Algorithm
Input β An Augmented Grammar G.β²
Output β CLR Parsing Table
Method
Initially construct set of items C = {I0, I1, I2 ... ... In} where C is a collection of LR (1)
items for G.
Initially construct set of items C = {I0, I1, I2 ... ... In} where C is a collection of LR (1)
items for G.
Parsing actions are based on each item or state I1.
Parsing actions are based on each item or state I1.
Various Actions are β
If A β Ξ± β a Ξ² is in Ii and goto (Ii, a) = Ij then create an entry in Action table Action [i, a] = shift j".
If A β Ξ± β, a is in Ii then set in Action table Action [i, a] to reduce AβΞ±. " Here, A should not be Sβ².
If Sβ² β S β is in Ii then Action [i, $] = accept".
The goto part of the SLR table can be filled as β
If goto (Ii, A) = Ij then goto [i, A] = j
If goto (Ii, A) = Ij then goto [i, A] = j
All entries not defined by rules 2 and 3 are considered to be "error. "
|
[
{
"code": null,
"e": 1358,
"s": 1062,
"text": "CLR defines canonical lookahead. CLR parsing use the canonical collection of LR (1) items to construct the CLR (1) parsing table. CLR (1) parsing table makes the more number of states as compare to the SLR (1) parsing. In the CLR (1), it can locate the reduce node only in the lookahead symbols."
},
{
"code": null,
"e": 1380,
"s": 1358,
"text": "Working of CLR Parser"
},
{
"code": null,
"e": 1435,
"s": 1380,
"text": "Construction of LR (1) collection of items for Grammar"
},
{
"code": null,
"e": 1460,
"s": 1435,
"text": "It requires three things"
},
{
"code": null,
"e": 1478,
"s": 1460,
"text": "Augmented Grammar"
},
{
"code": null,
"e": 1495,
"s": 1478,
"text": "Closure Function"
},
{
"code": null,
"e": 1509,
"s": 1495,
"text": "goto Function"
},
{
"code": null,
"e": 1583,
"s": 1509,
"text": "Augmented Grammar It is a new Grammar Gβ² which contains a new production"
},
{
"code": null,
"e": 1637,
"s": 1583,
"text": "Sβ² β S with all other productions of given grammar G."
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Closure"
},
{
"code": null,
"e": 1667,
"s": 1645,
"text": "procedure closure (I)"
},
{
"code": null,
"e": 1870,
"s": 1667,
"text": "begin\nRepeat\nfor each item A β Ξ± β B Ξ², a in I,\n each production B β Ξ³ and\n each terminal b β FIRST (Ξ² a)\nIf B β β Ξ³ is not in I\nAdd B β β Ξ³, b to I\nUntil no more elements can be joined to I;\nend"
},
{
"code": null,
"e": 1997,
"s": 1870,
"text": "goto(I, X): If there is a production A β Ξ± β X Ξ², a in I then goto(I, X) is the closure\nof the set of items of A β Ξ± X β Ξ², a."
},
{
"code": null,
"e": 2047,
"s": 1997,
"text": "Algorithm for Construction of LR (1) Set of Items"
},
{
"code": null,
"e": 2243,
"s": 2047,
"text": "begin\nC = {closure(Sβ²ββS,$)}\nRepeat\nfor each set of items I in C and each grammar symbol X (terminal or non-terminal)\n Add goto(I, X) to C\nUntil no more sets of elements can be added to C.\nend."
},
{
"code": null,
"e": 2296,
"s": 2243,
"text": "Construction of Canonical LR Parsing Table Algorithm"
},
{
"code": null,
"e": 2329,
"s": 2296,
"text": "Input β An Augmented Grammar G.β²"
},
{
"code": null,
"e": 2356,
"s": 2329,
"text": "Output β CLR Parsing Table"
},
{
"code": null,
"e": 2363,
"s": 2356,
"text": "Method"
},
{
"code": null,
"e": 2471,
"s": 2363,
"text": "Initially construct set of items C = {I0, I1, I2 ... ... In} where C is a collection of LR (1)\nitems for G."
},
{
"code": null,
"e": 2579,
"s": 2471,
"text": "Initially construct set of items C = {I0, I1, I2 ... ... In} where C is a collection of LR (1)\nitems for G."
},
{
"code": null,
"e": 2631,
"s": 2579,
"text": "Parsing actions are based on each item or state I1."
},
{
"code": null,
"e": 2683,
"s": 2631,
"text": "Parsing actions are based on each item or state I1."
},
{
"code": null,
"e": 2705,
"s": 2683,
"text": "Various Actions are β"
},
{
"code": null,
"e": 2814,
"s": 2705,
"text": "If A β Ξ± β a Ξ² is in Ii and goto (Ii, a) = Ij then create an entry in Action table Action [i, a] = shift j\"."
},
{
"code": null,
"e": 2919,
"s": 2814,
"text": "If A β Ξ± β, a is in Ii then set in Action table Action [i, a] to reduce AβΞ±. \" Here, A should not be Sβ²."
},
{
"code": null,
"e": 2970,
"s": 2919,
"text": "If Sβ² β S β is in Ii then Action [i, $] = accept\"."
},
{
"code": null,
"e": 3020,
"s": 2970,
"text": "The goto part of the SLR table can be filled as β"
},
{
"code": null,
"e": 3062,
"s": 3020,
"text": "If goto (Ii, A) = Ij then goto [i, A] = j"
},
{
"code": null,
"e": 3104,
"s": 3062,
"text": "If goto (Ii, A) = Ij then goto [i, A] = j"
},
{
"code": null,
"e": 3176,
"s": 3104,
"text": "All entries not defined by rules 2 and 3 are considered to be \"error. \""
}
] |
Climbing B-tree Indexes in Postgres | by GreekDataGuy | Towards Data Science
|
Your query was slow so you decided to speed it up by adding an index. What type of index was it? Probably a B-tree.
Postgres has a few index types but B-trees are by far the most common. Theyβre good for sorting and matching; and once you understand what they look like under the hood, itβs immediately apparent why.
Weβre going to take a dive into the internals of B-treeβs implementation in Postgres, then do some SQL examples to show their effect. Iβve provided queries so you can run the same experiments yourself.
This post assumes you already have a general idea what an index is and does. If not, the often provided abstraction is the glossary in a textbook. Rather than reading every line in the book to find a word/topic, you can look it up alphabetically in the glossary, then jump to the page itβs on. Weβll see shortly the reality is slightly more complicated.
B-tree stands for Balanced Tree.
Itβs NOT a binary tree, which allows a max of 2 child nodes per parent and was designed for in-memory search.
From Wikipedia,
In computer science, a B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree generalizes the binary search tree, allowing for nodes with more than two children.[2] Unlike other self-balancing binary search trees, the B-tree is well suited for storage systems that read and write relatively large blocks of data, such as discs. It is commonly used in databases and file systems.
Thatβs a pretty good non-technical introduction. For a really technical explanation, see this paper by Lehman and Yao, on which the Postgres implementation is based.
B-trees are βbalancedβ because the distance from the root to any leaf node is the same. A leaf node is a node without children. The root node is the node at the top.
A node has keys. In our root node below, [10,15,20] are keys. Keys map to values in the database but also bound keys in child nodes.
The first child node, [2, 9], has values less than 10, hence the pointer on the left side of 10.
The 2nd child node, [12], has a value between 10 and 15, hence the pointer from there.
The 3rd child node, [22] is greater than 20, hence the pointer on the right side of 20.
Now if we wanted to look up the key, 12, weβd compare 12 to values in the root node and see that itβs between 10 and 15. So weβd use the pointer between 10 and 15 to find the node containing 12.
This is an abstraction over Postgresβ implementation but you can already imagine why this is faster than iterating over every number in a table and checking if it equals 12.
This is why B-trees can search, insert and delete in O(logN) time.
B-trees also have a minimum and maximum number of keys per node. Nodes are joined and split on inserts and deletes to keep nodes in range.
Weβre going to work through 3 examples where B-trees can have a huge impact: numbers, text and dates.
Create a table for each datatype. Each table has 2 columns but weβll only index one of them.
create table numbers( val integer, val_indexed integer);CREATE INDEX numbers_indexed ON numbers using btree (val_indexed);create table strings( val varchar, val_indexed varchar);CREATE INDEX strings_indexed ON strings using btree (val_indexed);create table dates( val varchar, val_indexed varchar);CREATE INDEX dates_indexed ON dates using btree (val_indexed);
Letβs generate 1M random integers between 1 and ~1M.
insert into numbersselect (random()*1000000 +1)::int, (random()*1000000 +1)::intfrom (SELECT * FROM generate_series(1,1000000)) ser;
Weβll repeatedly run the below queries, record query time, then add an additional 1M additional records.
select * from numbers order by val desc;select * from numbers order by val_indexed desc;
What we see is a massive difference in query time in ordering the indexed vs non-indexed column.
5 million records is small potatoes for Postgres but we can already see a huge difference in efficiency.
Why the difference? Letβs use the explain function in Postgres to dig into it.
explain select * from numbers order by val desc;explain select * from numbers order by val_indexed desc;
We see the non-indexed search using a sequential scan, while the indexed search using an index scan. Given the above discussed structure of a B-tree, itβs easy to see why searching the index would be much faster than searching the table.
Letβs do the same comparison but with strings. Though this time weβll incrementally add 100k rows at a time.
insert into stringsSELECT md5(random()::text), md5(random()::text)from ( SELECT * FROM generate_series(1,100000) AS id) AS ser;
Now order those rows.
select * from strings order by val desc;select * from strings order by val_indexed desc;
What do we see? The exact same pattern where the indexed search blows non-indexed search out of the water.
Peeking at explain , we see the same cause.
explain select * from strings order by val desc;explain select * from strings order by val_indexed desc;
Letβs do this one more time with dates. Again, weβll only generate 100k rows at a time.
with cte as (select timestamp '1900-01-10 20:00:00' + random() * ( timestamp '2000-01-20 20:00:00'-timestamp '1900-01-10 10:00:00' ) rdate from (SELECT * FROM generate_series(1,100000) AS id) ser)insert into datesselect rdate, rdatefrom cte;
Query the dates and record query times.
select * from dates order by val desc;select * from dates order by val_indexed desc;
Compare the difference.
We can already guess what explain is going to show but letβs take a look anyway.
explain select * from dates order by val desc;explain select * from dates order by val_indexed desc;
Once again, ordering rows via index scans is orders of magnitude faster than sequence scans.
My aim was to give you a general sense of how indexes are structured so you can intuitively understand why they improve query times.
Then we covered some examples where adding an index made a night-and-day difference.
We only covered ordering rows, but it would be interesting to investigate query times and look at explain for other types of queries like where or exists.
|
[
{
"code": null,
"e": 287,
"s": 171,
"text": "Your query was slow so you decided to speed it up by adding an index. What type of index was it? Probably a B-tree."
},
{
"code": null,
"e": 488,
"s": 287,
"text": "Postgres has a few index types but B-trees are by far the most common. Theyβre good for sorting and matching; and once you understand what they look like under the hood, itβs immediately apparent why."
},
{
"code": null,
"e": 690,
"s": 488,
"text": "Weβre going to take a dive into the internals of B-treeβs implementation in Postgres, then do some SQL examples to show their effect. Iβve provided queries so you can run the same experiments yourself."
},
{
"code": null,
"e": 1044,
"s": 690,
"text": "This post assumes you already have a general idea what an index is and does. If not, the often provided abstraction is the glossary in a textbook. Rather than reading every line in the book to find a word/topic, you can look it up alphabetically in the glossary, then jump to the page itβs on. Weβll see shortly the reality is slightly more complicated."
},
{
"code": null,
"e": 1077,
"s": 1044,
"text": "B-tree stands for Balanced Tree."
},
{
"code": null,
"e": 1187,
"s": 1077,
"text": "Itβs NOT a binary tree, which allows a max of 2 child nodes per parent and was designed for in-memory search."
},
{
"code": null,
"e": 1203,
"s": 1187,
"text": "From Wikipedia,"
},
{
"code": null,
"e": 1699,
"s": 1203,
"text": "In computer science, a B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree generalizes the binary search tree, allowing for nodes with more than two children.[2] Unlike other self-balancing binary search trees, the B-tree is well suited for storage systems that read and write relatively large blocks of data, such as discs. It is commonly used in databases and file systems."
},
{
"code": null,
"e": 1865,
"s": 1699,
"text": "Thatβs a pretty good non-technical introduction. For a really technical explanation, see this paper by Lehman and Yao, on which the Postgres implementation is based."
},
{
"code": null,
"e": 2031,
"s": 1865,
"text": "B-trees are βbalancedβ because the distance from the root to any leaf node is the same. A leaf node is a node without children. The root node is the node at the top."
},
{
"code": null,
"e": 2164,
"s": 2031,
"text": "A node has keys. In our root node below, [10,15,20] are keys. Keys map to values in the database but also bound keys in child nodes."
},
{
"code": null,
"e": 2261,
"s": 2164,
"text": "The first child node, [2, 9], has values less than 10, hence the pointer on the left side of 10."
},
{
"code": null,
"e": 2348,
"s": 2261,
"text": "The 2nd child node, [12], has a value between 10 and 15, hence the pointer from there."
},
{
"code": null,
"e": 2436,
"s": 2348,
"text": "The 3rd child node, [22] is greater than 20, hence the pointer on the right side of 20."
},
{
"code": null,
"e": 2631,
"s": 2436,
"text": "Now if we wanted to look up the key, 12, weβd compare 12 to values in the root node and see that itβs between 10 and 15. So weβd use the pointer between 10 and 15 to find the node containing 12."
},
{
"code": null,
"e": 2805,
"s": 2631,
"text": "This is an abstraction over Postgresβ implementation but you can already imagine why this is faster than iterating over every number in a table and checking if it equals 12."
},
{
"code": null,
"e": 2872,
"s": 2805,
"text": "This is why B-trees can search, insert and delete in O(logN) time."
},
{
"code": null,
"e": 3011,
"s": 2872,
"text": "B-trees also have a minimum and maximum number of keys per node. Nodes are joined and split on inserts and deletes to keep nodes in range."
},
{
"code": null,
"e": 3113,
"s": 3011,
"text": "Weβre going to work through 3 examples where B-trees can have a huge impact: numbers, text and dates."
},
{
"code": null,
"e": 3206,
"s": 3113,
"text": "Create a table for each datatype. Each table has 2 columns but weβll only index one of them."
},
{
"code": null,
"e": 3573,
"s": 3206,
"text": "create table numbers( val integer, val_indexed integer);CREATE INDEX numbers_indexed ON numbers using btree (val_indexed);create table strings( val varchar, val_indexed varchar);CREATE INDEX strings_indexed ON strings using btree (val_indexed);create table dates( val varchar, val_indexed varchar);CREATE INDEX dates_indexed ON dates using btree (val_indexed);"
},
{
"code": null,
"e": 3626,
"s": 3573,
"text": "Letβs generate 1M random integers between 1 and ~1M."
},
{
"code": null,
"e": 3761,
"s": 3626,
"text": "insert into numbersselect (random()*1000000 +1)::int, (random()*1000000 +1)::intfrom (SELECT * FROM generate_series(1,1000000)) ser;"
},
{
"code": null,
"e": 3866,
"s": 3761,
"text": "Weβll repeatedly run the below queries, record query time, then add an additional 1M additional records."
},
{
"code": null,
"e": 3955,
"s": 3866,
"text": "select * from numbers order by val desc;select * from numbers order by val_indexed desc;"
},
{
"code": null,
"e": 4052,
"s": 3955,
"text": "What we see is a massive difference in query time in ordering the indexed vs non-indexed column."
},
{
"code": null,
"e": 4157,
"s": 4052,
"text": "5 million records is small potatoes for Postgres but we can already see a huge difference in efficiency."
},
{
"code": null,
"e": 4236,
"s": 4157,
"text": "Why the difference? Letβs use the explain function in Postgres to dig into it."
},
{
"code": null,
"e": 4341,
"s": 4236,
"text": "explain select * from numbers order by val desc;explain select * from numbers order by val_indexed desc;"
},
{
"code": null,
"e": 4579,
"s": 4341,
"text": "We see the non-indexed search using a sequential scan, while the indexed search using an index scan. Given the above discussed structure of a B-tree, itβs easy to see why searching the index would be much faster than searching the table."
},
{
"code": null,
"e": 4688,
"s": 4579,
"text": "Letβs do the same comparison but with strings. Though this time weβll incrementally add 100k rows at a time."
},
{
"code": null,
"e": 4819,
"s": 4688,
"text": "insert into stringsSELECT md5(random()::text), md5(random()::text)from ( SELECT * FROM generate_series(1,100000) AS id) AS ser;"
},
{
"code": null,
"e": 4841,
"s": 4819,
"text": "Now order those rows."
},
{
"code": null,
"e": 4930,
"s": 4841,
"text": "select * from strings order by val desc;select * from strings order by val_indexed desc;"
},
{
"code": null,
"e": 5037,
"s": 4930,
"text": "What do we see? The exact same pattern where the indexed search blows non-indexed search out of the water."
},
{
"code": null,
"e": 5081,
"s": 5037,
"text": "Peeking at explain , we see the same cause."
},
{
"code": null,
"e": 5186,
"s": 5081,
"text": "explain select * from strings order by val desc;explain select * from strings order by val_indexed desc;"
},
{
"code": null,
"e": 5274,
"s": 5186,
"text": "Letβs do this one more time with dates. Again, weβll only generate 100k rows at a time."
},
{
"code": null,
"e": 5527,
"s": 5274,
"text": "with cte as (select timestamp '1900-01-10 20:00:00' + random() * ( timestamp '2000-01-20 20:00:00'-timestamp '1900-01-10 10:00:00' ) rdate from (SELECT * FROM generate_series(1,100000) AS id) ser)insert into datesselect rdate, rdatefrom cte;"
},
{
"code": null,
"e": 5567,
"s": 5527,
"text": "Query the dates and record query times."
},
{
"code": null,
"e": 5652,
"s": 5567,
"text": "select * from dates order by val desc;select * from dates order by val_indexed desc;"
},
{
"code": null,
"e": 5676,
"s": 5652,
"text": "Compare the difference."
},
{
"code": null,
"e": 5757,
"s": 5676,
"text": "We can already guess what explain is going to show but letβs take a look anyway."
},
{
"code": null,
"e": 5858,
"s": 5757,
"text": "explain select * from dates order by val desc;explain select * from dates order by val_indexed desc;"
},
{
"code": null,
"e": 5951,
"s": 5858,
"text": "Once again, ordering rows via index scans is orders of magnitude faster than sequence scans."
},
{
"code": null,
"e": 6084,
"s": 5951,
"text": "My aim was to give you a general sense of how indexes are structured so you can intuitively understand why they improve query times."
},
{
"code": null,
"e": 6169,
"s": 6084,
"text": "Then we covered some examples where adding an index made a night-and-day difference."
}
] |
Introducing Arauto: an interactive tool for Time Series Forecasting | by Paulo Vasconcellos | Towards Data Science
|
Time series forecasting has been an outstanding field to apply machine learning and statistical models, although many data scientists might not see it as a field as sexy as computer vision or NLP, to name a few. The fact is that many companies depend on time series forecasting and analysis to understand the future of the business, like predict revenue, active clients, average ticket, and so on.
Today, I would like to introduce a tool that has been helping me to optimize and increase my productivity when building time series models: Arauto, an open-source application made with Python that aims to bring an interactive and intuitive way to build mixed autoregressive moving average models (AR, MA, ARMA, ARIMA, SARIMA, ARIMAX, SARIMAX).
In my current job, Iβm responsible for creating and maintain multiple time series models running in production. Hotmart is one of the biggest platforms for digital products in the world and our C Levels, investors, managers, and leadership need to understand what we can expect for some key business metrics in future, like how much revenue weβll earn, how much money weβll spend in infrastructure, or how many active users we can expect for the next months.
However, Iβve noticed that I had two main problems while I was building models:
Most of my time was wasted building repeatedly processes and code: things that surely could be automated;
It was not so productive to iterate and experiment over different models and parameters for my models.
These points lead me to build a tool that could help me β and surely more people that are facing a similar problem β to be more agile and productive in my projects. The result of this project was Arauto.
Arauto is an open-source tool that combines an interactive and intuitive web application that guides you through the analysis and building of your time series models. Arauto aims to give you a predictive model in just a couple of minutes and, at the end of the process, it generates the code used to transform and train the model, so you can copy and modify it on Jupyter Notebook or Python script. Here are some features that you will find on Arauto:
Support for exogenous regressors;
Seasonal decompose that lets you know the Trend, Seasonality, and Resid of your data;
Stationarity Test using Augmented Dickey-Fuller test;
Customization of data transforming for stationarity: you can use from First Difference to Seasonal Log to transform your data;
ACF (Autocorrelation function) and PACF (Parcial correlation function) for terms estimation;
Customize ARIMA terms or let Arauto choose the best for you based on your data;
Grid search feature for parameters tuning;
Code generation: at the end of the process, Arauto returns the code used to transform the data and train the model
Itβs pretty easy to get started with Arauto. If are curious about what you can do, thereβs a live web version that you can access by clicking on this link. Please keep in mind that this is a lightweight version made for demonstration purposes since itβs using a Herokuβs free tier instance.
Arauto can be easily installed using Docker. By running three commands, you will be ready to use Arauto on your own infrastructure.
# Clone the repositorygit clone https://github.com/paulozip/arauto.gitcd arauto# Run the docker composedocker-compose up --build
Thereβs another option to install Arauto by using Condaβs environment. Please, refer to the Github repository for further information.
Arauto was made to be as intuitive as possible, even for those who donβt have deep knowledge in Statistics. However, we made a complete tutorial for you getting started with Arauto in a couple of minutes. Please, refer to Arautoβs documentation to know more.
Currently, this project is maintained by just one person. It would be great to have more people collaborating and contributing to this open-source project. If you want to collaborate with Arauto, hereβs what you can do:
Documentation and tutorial: itβs really important to make users get into Arauto as soon as they open the browser. Tutorials and deeper documentation could help us to achieve it.
New algorithms: there are many different algorithms that we could add to Arauto, like ARCH, VAR, and Tree-based algorithms, to name a few. All you need to do is fork the repository, build the feature and open a PR to merge it.
Bug fixes: something might be broken. We need good people to fix it.
Tests: Arauto doesnβt contain tests, and this is wrong.
Request features: You can suggest new ideas and features using our issue tracking. Requests will be prioritized by thumbs up emoji (π)
New features will be added to Arauto. If you want to know when a new version arrives, please, subscribe to Arautoβs newsletter to get informed about new things. We will NOT send spams or share your email. Only content related to Arauto will be sent.
I hope you are excited to build new things with Arauto. Iβm Paulo Vasconcellos, Data Scientist at Hotmart and co-founder of Data Hackers: the biggest data science and machine learning community in Brazil. Feel free to follow me on Linkedin or Twitter (tweets and posts are in PT-BR) to know more about Arauto and data science. See ya!
|
[
{
"code": null,
"e": 569,
"s": 171,
"text": "Time series forecasting has been an outstanding field to apply machine learning and statistical models, although many data scientists might not see it as a field as sexy as computer vision or NLP, to name a few. The fact is that many companies depend on time series forecasting and analysis to understand the future of the business, like predict revenue, active clients, average ticket, and so on."
},
{
"code": null,
"e": 913,
"s": 569,
"text": "Today, I would like to introduce a tool that has been helping me to optimize and increase my productivity when building time series models: Arauto, an open-source application made with Python that aims to bring an interactive and intuitive way to build mixed autoregressive moving average models (AR, MA, ARMA, ARIMA, SARIMA, ARIMAX, SARIMAX)."
},
{
"code": null,
"e": 1372,
"s": 913,
"text": "In my current job, Iβm responsible for creating and maintain multiple time series models running in production. Hotmart is one of the biggest platforms for digital products in the world and our C Levels, investors, managers, and leadership need to understand what we can expect for some key business metrics in future, like how much revenue weβll earn, how much money weβll spend in infrastructure, or how many active users we can expect for the next months."
},
{
"code": null,
"e": 1452,
"s": 1372,
"text": "However, Iβve noticed that I had two main problems while I was building models:"
},
{
"code": null,
"e": 1558,
"s": 1452,
"text": "Most of my time was wasted building repeatedly processes and code: things that surely could be automated;"
},
{
"code": null,
"e": 1661,
"s": 1558,
"text": "It was not so productive to iterate and experiment over different models and parameters for my models."
},
{
"code": null,
"e": 1865,
"s": 1661,
"text": "These points lead me to build a tool that could help me β and surely more people that are facing a similar problem β to be more agile and productive in my projects. The result of this project was Arauto."
},
{
"code": null,
"e": 2317,
"s": 1865,
"text": "Arauto is an open-source tool that combines an interactive and intuitive web application that guides you through the analysis and building of your time series models. Arauto aims to give you a predictive model in just a couple of minutes and, at the end of the process, it generates the code used to transform and train the model, so you can copy and modify it on Jupyter Notebook or Python script. Here are some features that you will find on Arauto:"
},
{
"code": null,
"e": 2351,
"s": 2317,
"text": "Support for exogenous regressors;"
},
{
"code": null,
"e": 2437,
"s": 2351,
"text": "Seasonal decompose that lets you know the Trend, Seasonality, and Resid of your data;"
},
{
"code": null,
"e": 2491,
"s": 2437,
"text": "Stationarity Test using Augmented Dickey-Fuller test;"
},
{
"code": null,
"e": 2618,
"s": 2491,
"text": "Customization of data transforming for stationarity: you can use from First Difference to Seasonal Log to transform your data;"
},
{
"code": null,
"e": 2711,
"s": 2618,
"text": "ACF (Autocorrelation function) and PACF (Parcial correlation function) for terms estimation;"
},
{
"code": null,
"e": 2791,
"s": 2711,
"text": "Customize ARIMA terms or let Arauto choose the best for you based on your data;"
},
{
"code": null,
"e": 2834,
"s": 2791,
"text": "Grid search feature for parameters tuning;"
},
{
"code": null,
"e": 2949,
"s": 2834,
"text": "Code generation: at the end of the process, Arauto returns the code used to transform the data and train the model"
},
{
"code": null,
"e": 3240,
"s": 2949,
"text": "Itβs pretty easy to get started with Arauto. If are curious about what you can do, thereβs a live web version that you can access by clicking on this link. Please keep in mind that this is a lightweight version made for demonstration purposes since itβs using a Herokuβs free tier instance."
},
{
"code": null,
"e": 3372,
"s": 3240,
"text": "Arauto can be easily installed using Docker. By running three commands, you will be ready to use Arauto on your own infrastructure."
},
{
"code": null,
"e": 3501,
"s": 3372,
"text": "# Clone the repositorygit clone https://github.com/paulozip/arauto.gitcd arauto# Run the docker composedocker-compose up --build"
},
{
"code": null,
"e": 3636,
"s": 3501,
"text": "Thereβs another option to install Arauto by using Condaβs environment. Please, refer to the Github repository for further information."
},
{
"code": null,
"e": 3895,
"s": 3636,
"text": "Arauto was made to be as intuitive as possible, even for those who donβt have deep knowledge in Statistics. However, we made a complete tutorial for you getting started with Arauto in a couple of minutes. Please, refer to Arautoβs documentation to know more."
},
{
"code": null,
"e": 4115,
"s": 3895,
"text": "Currently, this project is maintained by just one person. It would be great to have more people collaborating and contributing to this open-source project. If you want to collaborate with Arauto, hereβs what you can do:"
},
{
"code": null,
"e": 4293,
"s": 4115,
"text": "Documentation and tutorial: itβs really important to make users get into Arauto as soon as they open the browser. Tutorials and deeper documentation could help us to achieve it."
},
{
"code": null,
"e": 4520,
"s": 4293,
"text": "New algorithms: there are many different algorithms that we could add to Arauto, like ARCH, VAR, and Tree-based algorithms, to name a few. All you need to do is fork the repository, build the feature and open a PR to merge it."
},
{
"code": null,
"e": 4589,
"s": 4520,
"text": "Bug fixes: something might be broken. We need good people to fix it."
},
{
"code": null,
"e": 4645,
"s": 4589,
"text": "Tests: Arauto doesnβt contain tests, and this is wrong."
},
{
"code": null,
"e": 4780,
"s": 4645,
"text": "Request features: You can suggest new ideas and features using our issue tracking. Requests will be prioritized by thumbs up emoji (π)"
},
{
"code": null,
"e": 5030,
"s": 4780,
"text": "New features will be added to Arauto. If you want to know when a new version arrives, please, subscribe to Arautoβs newsletter to get informed about new things. We will NOT send spams or share your email. Only content related to Arauto will be sent."
}
] |
Find row number of a binary matrix having maximum number of 1s - GeeksforGeeks
|
17 Aug, 2021
Given a binary matrix (containing only 0 and 1) of order nΓn. All rows are sorted already, We need to find the row number with the maximum number of 1s. Also, find the number of 1 in that row. Note: in case of a tie, print the smaller row number.
Examples :
Input : mat[3][3] = {0, 0, 1,
0, 1, 1,
0, 0, 0}
Output : Row number = 2, MaxCount = 2
Input : mat[3][3] = {1, 1, 1,
1, 1, 1,
0, 0, 0}
Output : Row number = 1, MaxCount = 3
Basic Approach: Traverse whole of matrix and for each row find the number of 1 and among all that keep updating the row number with the maximum number of 1. This approach will result in O(n^2) time complexity.Better Approach: We can perform better if we try to apply the binary search for finding the position of the first 1 in each row and as per that we can find the number of 1 from each row as each row is in sorted order. This will result in O(nlogn) time complexity.Efficient Approach: Start with the top right corner with index (1, n) and try to go left until you reach the last 1 in that row (jth column), now if we traverse left to that row, we will find 0, so switch to the row just below, with the same column. Now your position will be (2, j) again in the 2nd row if the jth element is 1 try to go left until you find the last 1 otherwise in the 2nd row if jth element is 0 goes to the next row. So Finally say if you are at any ith row and jth column which is the index of last 1 from right in that row, increment i. So now if we have Aij = 0 again increment i otherwise keep decreasing j until you find the last 1 in that particular row. Sample Illustration :
Algorithm :
for (int i=0, j=n-1; i<n;i++)
{
// find left most position of 1 in a row
// find 1st zero in a row
while (arr[i][j]==1)
{
row = i;
j--;
}
}
cout << "Row number =" << row+1;
cout << "MaxCount =" << n-j;
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find row with maximum 1// in row sorted binary matrix#include<bits/stdc++.h>#define N 4using namespace std; // function for finding row with maximum 1void findMax (int arr[][N]){ int row = 0, i, j; for (i=0, j=N-1; i<N;i++) { // find left most position of 1 in a row // find 1st zero in a row while (arr[i][j] == 1 && j >= 0) { row = i; j--; } } cout << "Row number = " << row+1; cout << ", MaxCount = " << N-1-j;} // driver programint main(){ int arr[N][N] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1}; findMax(arr); return 0;}
// Java program to find row with maximum 1// in row sorted binary matrixclass GFG { static final int N = 4; // function for finding row with maximum 1 static void findMax(int arr[][]) { int row = 0, i, j; for (i = 0, j = N - 1; i < N; i++) { // find left most position of 1 in // a row find 1st zero in a row while (j >= 0 && arr[i][j] == 1) { row = i; j--; } } System.out.print("Row number = " + (row + 1)); System.out.print(", MaxCount = " + (N - 1 - j)); } // Driver code public static void main(String[] args) { int arr[][] = {{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 1}}; findMax(arr); }} // This code is contributed by Anant Agarwal.
# python program to find row with# maximum 1 in row sorted binary# matrix N = 4 # function for finding row with# maximum 1def findMax (arr): row = 0 j = N - 1 for i in range(0, N): # find left most position # of 1 in a row find 1st # zero in a row while (arr[i][j] == 1 and j >= 0): row = i j -= 1 print("Row number = " , row + 1, ", MaxCount = ", N - 1 - j) # driver programarr = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 1, 1, 1] ] findMax(arr) # This code is contributed by Sam007
// C# program to find row with maximum// 1 in row sorted binary matrixusing System; class GFG { static int N = 4; // function for finding row with maximum 1 static void findMax(int [,]arr) { int row = 0, i, j; for (i = 0, j = N - 1; i < N; i++) { // find left most position of 1 in // a row find 1st zero in a row while (arr[i,j] == 1 && j >= 0) { row = i; j--; } } Console.Write("Row number = " + (row + 1)); Console.Write(", MaxCount = " + (N - 1 - j)); } // Driver code public static void Main() { int [,]arr = {{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 1}}; findMax(arr); }} // This code is contributed by nitin mittal
<?php// PHP program to find// row with maximum 1// in row sorted// binary matrix$N = 4; // function for finding// row with maximum 1function findMax ($arr){ global $N; $row = 0; $i; $j=$N - 1; for ($i = 0; $i < $N; $i++) { // find left most position // of 1 in a row find 1st // zero in a row while ($arr[$i][$j] == 1 && $j >= 0) { $row = $i; $j--; } } echo "Row number = " , $row + 1; echo ", MaxCount = " , $N - 1 - $j;} // Driver Code $arr = array(array(0, 0, 0, 1), array(0, 0, 0, 1), array(0, 0, 0, 0), array(0, 1, 1, 1)); findMax($arr); // This code is contributed by vt_m.?>
<script> // Javascript program to find row with maximum 1// in row sorted binary matrixvar N = 4 // function for finding row with maximum 1function findMax (arr){ var row = 0, i, j; for (i=0, j=N-1; i<N;i++) { // find left most position of 1 in a row // find 1st zero in a row while (arr[i][j] == 1 && j >= 0) { row = i; j--; } } document.write( "Row number = " + (row+1)); document.write( ", MaxCount = " + (N-1-j));} // driver programvar arr = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 1, 1, 1]];findMax(arr); </script>
Output:
Row number = 4, MaxCount = 3
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
nitin mittal
vt_m
Sam007
OrTubul
itsok
kushjmehta
Matrix
Searching
Searching
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6
Count all possible paths from top left to bottom right of a mXn matrix
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
|
[
{
"code": null,
"e": 25374,
"s": 25346,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 25622,
"s": 25374,
"text": "Given a binary matrix (containing only 0 and 1) of order nΓn. All rows are sorted already, We need to find the row number with the maximum number of 1s. Also, find the number of 1 in that row. Note: in case of a tie, print the smaller row number. "
},
{
"code": null,
"e": 25634,
"s": 25622,
"text": "Examples : "
},
{
"code": null,
"e": 25891,
"s": 25634,
"text": "Input : mat[3][3] = {0, 0, 1,\n 0, 1, 1,\n 0, 0, 0}\nOutput : Row number = 2, MaxCount = 2\n\nInput : mat[3][3] = {1, 1, 1,\n 1, 1, 1,\n 0, 0, 0}\nOutput : Row number = 1, MaxCount = 3"
},
{
"code": null,
"e": 27065,
"s": 25891,
"text": "Basic Approach: Traverse whole of matrix and for each row find the number of 1 and among all that keep updating the row number with the maximum number of 1. This approach will result in O(n^2) time complexity.Better Approach: We can perform better if we try to apply the binary search for finding the position of the first 1 in each row and as per that we can find the number of 1 from each row as each row is in sorted order. This will result in O(nlogn) time complexity.Efficient Approach: Start with the top right corner with index (1, n) and try to go left until you reach the last 1 in that row (jth column), now if we traverse left to that row, we will find 0, so switch to the row just below, with the same column. Now your position will be (2, j) again in the 2nd row if the jth element is 1 try to go left until you find the last 1 otherwise in the 2nd row if jth element is 0 goes to the next row. So Finally say if you are at any ith row and jth column which is the index of last 1 from right in that row, increment i. So now if we have Aij = 0 again increment i otherwise keep decreasing j until you find the last 1 in that particular row. Sample Illustration :"
},
{
"code": null,
"e": 27078,
"s": 27065,
"text": "Algorithm : "
},
{
"code": null,
"e": 27317,
"s": 27078,
"text": "for (int i=0, j=n-1; i<n;i++)\n{\n // find left most position of 1 in a row\n // find 1st zero in a row\n while (arr[i][j]==1) \n {\n row = i;\n j--;\n }\n}\ncout << \"Row number =\" << row+1;\ncout << \"MaxCount =\" << n-j;"
},
{
"code": null,
"e": 27321,
"s": 27317,
"text": "C++"
},
{
"code": null,
"e": 27326,
"s": 27321,
"text": "Java"
},
{
"code": null,
"e": 27334,
"s": 27326,
"text": "Python3"
},
{
"code": null,
"e": 27337,
"s": 27334,
"text": "C#"
},
{
"code": null,
"e": 27341,
"s": 27337,
"text": "PHP"
},
{
"code": null,
"e": 27352,
"s": 27341,
"text": "Javascript"
},
{
"code": "// CPP program to find row with maximum 1// in row sorted binary matrix#include<bits/stdc++.h>#define N 4using namespace std; // function for finding row with maximum 1void findMax (int arr[][N]){ int row = 0, i, j; for (i=0, j=N-1; i<N;i++) { // find left most position of 1 in a row // find 1st zero in a row while (arr[i][j] == 1 && j >= 0) { row = i; j--; } } cout << \"Row number = \" << row+1; cout << \", MaxCount = \" << N-1-j;} // driver programint main(){ int arr[N][N] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1}; findMax(arr); return 0;}",
"e": 28049,
"s": 27352,
"text": null
},
{
"code": "// Java program to find row with maximum 1// in row sorted binary matrixclass GFG { static final int N = 4; // function for finding row with maximum 1 static void findMax(int arr[][]) { int row = 0, i, j; for (i = 0, j = N - 1; i < N; i++) { // find left most position of 1 in // a row find 1st zero in a row while (j >= 0 && arr[i][j] == 1) { row = i; j--; } } System.out.print(\"Row number = \" + (row + 1)); System.out.print(\", MaxCount = \" + (N - 1 - j)); } // Driver code public static void main(String[] args) { int arr[][] = {{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 1}}; findMax(arr); }} // This code is contributed by Anant Agarwal.",
"e": 29031,
"s": 28049,
"text": null
},
{
"code": "# python program to find row with# maximum 1 in row sorted binary# matrix N = 4 # function for finding row with# maximum 1def findMax (arr): row = 0 j = N - 1 for i in range(0, N): # find left most position # of 1 in a row find 1st # zero in a row while (arr[i][j] == 1 and j >= 0): row = i j -= 1 print(\"Row number = \" , row + 1, \", MaxCount = \", N - 1 - j) # driver programarr = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 1, 1, 1] ] findMax(arr) # This code is contributed by Sam007",
"e": 29649,
"s": 29031,
"text": null
},
{
"code": "// C# program to find row with maximum// 1 in row sorted binary matrixusing System; class GFG { static int N = 4; // function for finding row with maximum 1 static void findMax(int [,]arr) { int row = 0, i, j; for (i = 0, j = N - 1; i < N; i++) { // find left most position of 1 in // a row find 1st zero in a row while (arr[i,j] == 1 && j >= 0) { row = i; j--; } } Console.Write(\"Row number = \" + (row + 1)); Console.Write(\", MaxCount = \" + (N - 1 - j)); } // Driver code public static void Main() { int [,]arr = {{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 1}}; findMax(arr); }} // This code is contributed by nitin mittal",
"e": 30540,
"s": 29649,
"text": null
},
{
"code": "<?php// PHP program to find// row with maximum 1// in row sorted// binary matrix$N = 4; // function for finding// row with maximum 1function findMax ($arr){ global $N; $row = 0; $i; $j=$N - 1; for ($i = 0; $i < $N; $i++) { // find left most position // of 1 in a row find 1st // zero in a row while ($arr[$i][$j] == 1 && $j >= 0) { $row = $i; $j--; } } echo \"Row number = \" , $row + 1; echo \", MaxCount = \" , $N - 1 - $j;} // Driver Code $arr = array(array(0, 0, 0, 1), array(0, 0, 0, 1), array(0, 0, 0, 0), array(0, 1, 1, 1)); findMax($arr); // This code is contributed by vt_m.?>",
"e": 31309,
"s": 30540,
"text": null
},
{
"code": "<script> // Javascript program to find row with maximum 1// in row sorted binary matrixvar N = 4 // function for finding row with maximum 1function findMax (arr){ var row = 0, i, j; for (i=0, j=N-1; i<N;i++) { // find left most position of 1 in a row // find 1st zero in a row while (arr[i][j] == 1 && j >= 0) { row = i; j--; } } document.write( \"Row number = \" + (row+1)); document.write( \", MaxCount = \" + (N-1-j));} // driver programvar arr = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 1, 1, 1]];findMax(arr); </script>",
"e": 31961,
"s": 31309,
"text": null
},
{
"code": null,
"e": 31970,
"s": 31961,
"text": "Output: "
},
{
"code": null,
"e": 31999,
"s": 31970,
"text": "Row number = 4, MaxCount = 3"
},
{
"code": null,
"e": 32440,
"s": 31999,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32453,
"s": 32440,
"text": "nitin mittal"
},
{
"code": null,
"e": 32458,
"s": 32453,
"text": "vt_m"
},
{
"code": null,
"e": 32465,
"s": 32458,
"text": "Sam007"
},
{
"code": null,
"e": 32473,
"s": 32465,
"text": "OrTubul"
},
{
"code": null,
"e": 32479,
"s": 32473,
"text": "itsok"
},
{
"code": null,
"e": 32490,
"s": 32479,
"text": "kushjmehta"
},
{
"code": null,
"e": 32497,
"s": 32490,
"text": "Matrix"
},
{
"code": null,
"e": 32507,
"s": 32497,
"text": "Searching"
},
{
"code": null,
"e": 32517,
"s": 32507,
"text": "Searching"
},
{
"code": null,
"e": 32524,
"s": 32517,
"text": "Matrix"
},
{
"code": null,
"e": 32622,
"s": 32524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32646,
"s": 32622,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 32697,
"s": 32646,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 32718,
"s": 32697,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 32789,
"s": 32718,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 32871,
"s": 32789,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 32885,
"s": 32871,
"text": "Binary Search"
},
{
"code": null,
"e": 32899,
"s": 32885,
"text": "Linear Search"
},
{
"code": null,
"e": 32967,
"s": 32899,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32991,
"s": 32967,
"text": "Find the Missing Number"
}
] |
MariaDB - Select Query
|
In this chapter, we will learn how to select data from a table.
SELECT statements retrieve selected rows. They can include UNION statements, an ordering clause, a LIMIT clause, a WHERE clause, a GROUP BY...HAVING clause, and subqueries.
Review the following general syntax β
SELECT field, field2,... FROM table_name, table_name2,... WHERE...
A SELECT statement provides multiple options for specifying the table used β
database_name.table_name
database_name.table_name
table_name.column_name
table_name.column_name
database_name.table_name.column_name
database_name.table_name.column_name
All select statements must contain one or more select expressions. Select expressions consist of one of the following options β
A column name.
A column name.
An expression employing operators and functions.
An expression employing operators and functions.
The specification βtable_name.*β to select all columns within the given table.
The specification βtable_name.*β to select all columns within the given table.
The character β*β to select all columns from all tables specified in the FROM clause.
The character β*β to select all columns from all tables specified in the FROM clause.
The command prompt or a PHP script can be employed in executing a select statement.
At the command prompt, execute statements as follows β
root@host# mysql -u root -p password;
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> SELECT * from products_tbl
+-------------+---------------+
| ID_number | Nomenclature |
+-------------+---------------+
| 12345 | Orbitron 4000 |
+-------------+---------------+
Employ the same SELECT statement(s) within a PHP function to perform the operation. You will use the mysql_query() function once again. Review an example given below β
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT product_id, product_name,product_manufacturer, ship_date FROM products_tbl';
mysql_select_db('PRODUCTS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Product ID :{$row['product_id']} <br> ".
"Name: {$row['product_name']} <br> ".
"Manufacturer: {$row['product_manufacturer']} <br> ".
"Ship Date : {$row['ship_date']} <br>".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
On successful data retrieval, you will see the following output β
Product ID: 12345
Nomenclature: Orbitron 4000
Manufacturer: XYZ Corp
Ship Date: 01/01/17
----------------------------------------------
Product ID: 12346
Nomenclature: Orbitron 3000
Manufacturer: XYZ Corp
Ship Date: 01/02/17
----------------------------------------------
mysql> Fetched data successfully
Best practices suggest releasing cursor memory after every SELECT statement. PHP provides the mysql_free_result() function for this purpose. Review its use as shown below β
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT product_id, product_name, product_manufacturer, ship_date FROM products_tbl';
mysql_select_db('PRODUCTS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM)) {
echo "Product ID :{$row[0]} <br> ".
"Name: {$row[1]} <br> ".
"Manufacturer: {$row[2]} <br> ".
"Ship Date : {$row[3]} <br> ".
"--------------------------------<br>";
}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2426,
"s": 2362,
"text": "In this chapter, we will learn how to select data from a table."
},
{
"code": null,
"e": 2599,
"s": 2426,
"text": "SELECT statements retrieve selected rows. They can include UNION statements, an ordering clause, a LIMIT clause, a WHERE clause, a GROUP BY...HAVING clause, and subqueries."
},
{
"code": null,
"e": 2637,
"s": 2599,
"text": "Review the following general syntax β"
},
{
"code": null,
"e": 2705,
"s": 2637,
"text": "SELECT field, field2,... FROM table_name, table_name2,... WHERE...\n"
},
{
"code": null,
"e": 2782,
"s": 2705,
"text": "A SELECT statement provides multiple options for specifying the table used β"
},
{
"code": null,
"e": 2807,
"s": 2782,
"text": "database_name.table_name"
},
{
"code": null,
"e": 2832,
"s": 2807,
"text": "database_name.table_name"
},
{
"code": null,
"e": 2855,
"s": 2832,
"text": "table_name.column_name"
},
{
"code": null,
"e": 2878,
"s": 2855,
"text": "table_name.column_name"
},
{
"code": null,
"e": 2915,
"s": 2878,
"text": "database_name.table_name.column_name"
},
{
"code": null,
"e": 2952,
"s": 2915,
"text": "database_name.table_name.column_name"
},
{
"code": null,
"e": 3080,
"s": 2952,
"text": "All select statements must contain one or more select expressions. Select expressions consist of one of the following options β"
},
{
"code": null,
"e": 3095,
"s": 3080,
"text": "A column name."
},
{
"code": null,
"e": 3110,
"s": 3095,
"text": "A column name."
},
{
"code": null,
"e": 3159,
"s": 3110,
"text": "An expression employing operators and functions."
},
{
"code": null,
"e": 3208,
"s": 3159,
"text": "An expression employing operators and functions."
},
{
"code": null,
"e": 3287,
"s": 3208,
"text": "The specification βtable_name.*β to select all columns within the given table."
},
{
"code": null,
"e": 3366,
"s": 3287,
"text": "The specification βtable_name.*β to select all columns within the given table."
},
{
"code": null,
"e": 3452,
"s": 3366,
"text": "The character β*β to select all columns from all tables specified in the FROM clause."
},
{
"code": null,
"e": 3538,
"s": 3452,
"text": "The character β*β to select all columns from all tables specified in the FROM clause."
},
{
"code": null,
"e": 3622,
"s": 3538,
"text": "The command prompt or a PHP script can be employed in executing a select statement."
},
{
"code": null,
"e": 3677,
"s": 3622,
"text": "At the command prompt, execute statements as follows β"
},
{
"code": null,
"e": 3971,
"s": 3677,
"text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use PRODUCTS;\nDatabase changed\nmysql> SELECT * from products_tbl\n+-------------+---------------+\n| ID_number | Nomenclature |\n+-------------+---------------+\n| 12345 | Orbitron 4000 |\n+-------------+---------------+\n"
},
{
"code": null,
"e": 4139,
"s": 3971,
"text": "Employ the same SELECT statement(s) within a PHP function to perform the operation. You will use the mysql_query() function once again. Review an example given below β"
},
{
"code": null,
"e": 4997,
"s": 4139,
"text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n\n $sql = 'SELECT product_id, product_name,product_manufacturer, ship_date FROM products_tbl';\n mysql_select_db('PRODUCTS');\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not get data: ' . mysql_error());\n }\n\n while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {\n echo \"Product ID :{$row['product_id']} <br> \".\n \"Name: {$row['product_name']} <br> \".\n \"Manufacturer: {$row['product_manufacturer']} <br> \".\n \"Ship Date : {$row['ship_date']} <br>\".\n \"--------------------------------<br>\";\n }\n\n echo \"Fetched data successfully\\n\";\n mysql_close($conn);\n?>"
},
{
"code": null,
"e": 5063,
"s": 4997,
"text": "On successful data retrieval, you will see the following output β"
},
{
"code": null,
"e": 5369,
"s": 5063,
"text": "Product ID: 12345\nNomenclature: Orbitron 4000\nManufacturer: XYZ Corp\nShip Date: 01/01/17\n----------------------------------------------\nProduct ID: 12346\nNomenclature: Orbitron 3000\nManufacturer: XYZ Corp\nShip Date: 01/02/17\n----------------------------------------------\nmysql> Fetched data successfully\n"
},
{
"code": null,
"e": 5542,
"s": 5369,
"text": "Best practices suggest releasing cursor memory after every SELECT statement. PHP provides the mysql_free_result() function for this purpose. Review its use as shown below β"
},
{
"code": null,
"e": 6373,
"s": 5542,
"text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n\n $sql = 'SELECT product_id, product_name, product_manufacturer, ship_date FROM products_tbl';\n mysql_select_db('PRODUCTS');\n $retval = mysql_query( $sql, $conn );\n\n if(! $retval ) {\n die('Could not get data: ' . mysql_error());\n }\n\n while($row = mysql_fetch_array($retval, MYSQL_NUM)) {\n echo \"Product ID :{$row[0]} <br> \".\n \"Name: {$row[1]} <br> \".\n \"Manufacturer: {$row[2]} <br> \".\n \"Ship Date : {$row[3]} <br> \".\n \"--------------------------------<br>\";\n }\n\n mysql_free_result($retval);\n echo \"Fetched data successfully\\n\";\n mysql_close($conn);\n?>"
},
{
"code": null,
"e": 6380,
"s": 6373,
"text": " Print"
},
{
"code": null,
"e": 6391,
"s": 6380,
"text": " Add Notes"
}
] |
Neo4j CQL - Relationship Functions
|
Neo4j CQL has provided a set of Relationship functions to know the details of a Relationship in getting Start Node,End Node etc. details.
Here, we are going to discuss some of the important and frequently used functions
Now we will discuss each Neo4j CQL Relationship Functions in detail with examples
It takes a string as an input and convert into upper case letters. All CQL Functions should use "( )" brackets.
STARTNODE (<relationship-label-name>)
NOTE:-
<relationship-label-name> may be a property name of a node or relationship from Neo4j Database.
Example -
This example demonstrates how to use CQL STARTNODE Relationship function to retrieve a Start Node Details of a Relationship.
Before executing STARTNODE() function on Relationship "ACTION_MOVIES", we will check it's details
Step 1 - Type the below command at dollar prompt in Data Browser.
MATCH (video1:YoutubeVideo1)-[movie:ACTION_MOVIES]->(video2:YoutubeVideo2)
RETURN movie
Step 2 - Click on Execute button and observe the results.
Here, We can observe that STARTNODE of Relationship "ACTION_MOVIES" is "YoutubeVideo1". Let us check this with function.
Step 3 - Type the below command and click on Execute button.
MATCH (a)-[movie:ACTION_MOVIES]->(b)
RETURN STARTNODE(movie)
It uses STARTNODE() Relationship function to print Start Node of Relationship "ACTION_MOVIES".
Here, We can observe that STARTNODE of Relationship "ACTION_MOVIES" is "YoutubeVideo1".
Example -
This example demonstrates how to use CQL ENDNODE Relationship function to retrieve a End Node Details of a Relationship.
Before executing ENDNODE() function on Relationship "ACTION_MOVIES", we will check it's details
Step 1 - Type the below command at dollar prompt in Data Browser.
MATCH (video1:YoutubeVideo1)-[movie:ACTION_MOVIES]->(video2:YoutubeVideo2)
RETURN movie
Step 2 - Click on Execute button and observe the results.
Here, We can observe that End Node of Relationship "ACTION_MOVIES" is "YoutubeVideo2". Let us check this with function.
Step 3 - Type the below command and click on Execute button.
MATCH (a)-[movie:ACTION_MOVIES]->(b)
RETURN ENDNODE(movie)
It uses ENDNODE() Relationship function to print Start Node of Relationship "ACTION_MOVIES".
Here, We can observe that ENDNODE of Relationship "ACTION_MOVIES" is "YoutubeVideo2".
Example -
This example demonstrates how to use CQL ID & TYPE Relationship functions to retrieve Id and Type Details of a Relationship.
Before executing ID & TYPE functions on Relationship "ACTION_MOVIES", we will check it's details
Step 1 - Type the below command at dollar prompt in Data Browser.
MATCH (video1:YoutubeVideo1)-[movie:ACTION_MOVIES]->(video2:YoutubeVideo2)
RETURN movie
Step 2 - Click on Execute button and observe the results.
Here, We can observe that ID and TYPE of Relationship "ACTION_MOVIES" are "2" and "ACTION_MOVIES". Let us check this with function.
Step 3 - Type the below command and click on Execute button.
MATCH (a)-[movie:ACTION_MOVIES]->(b)
RETURN ID(movie),TYPE(movie)
It uses ID() and TYPE() Relationship functions to print ID and Type of Relationship "ACTION_MOVIES" details.
Here, We can observe that ID and TYPE of Relationship "ACTION_MOVIES" are "2" and "ACTION_MOVIES".
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2478,
"s": 2339,
"text": "Neo4j CQL has provided a set of Relationship functions to know the details of a Relationship in getting Start Node,End Node etc. details. "
},
{
"code": null,
"e": 2560,
"s": 2478,
"text": "Here, we are going to discuss some of the important and frequently used functions"
},
{
"code": null,
"e": 2642,
"s": 2560,
"text": "Now we will discuss each Neo4j CQL Relationship Functions in detail with examples"
},
{
"code": null,
"e": 2754,
"s": 2642,
"text": "It takes a string as an input and convert into upper case letters. All CQL Functions should use \"( )\" brackets."
},
{
"code": null,
"e": 2792,
"s": 2754,
"text": "STARTNODE (<relationship-label-name>)"
},
{
"code": null,
"e": 2799,
"s": 2792,
"text": "NOTE:-"
},
{
"code": null,
"e": 2895,
"s": 2799,
"text": "<relationship-label-name> may be a property name of a node or relationship from Neo4j Database."
},
{
"code": null,
"e": 2905,
"s": 2895,
"text": "Example -"
},
{
"code": null,
"e": 3030,
"s": 2905,
"text": "This example demonstrates how to use CQL STARTNODE Relationship function to retrieve a Start Node Details of a Relationship."
},
{
"code": null,
"e": 3128,
"s": 3030,
"text": "Before executing STARTNODE() function on Relationship \"ACTION_MOVIES\", we will check it's details"
},
{
"code": null,
"e": 3194,
"s": 3128,
"text": "Step 1 - Type the below command at dollar prompt in Data Browser."
},
{
"code": null,
"e": 3283,
"s": 3194,
"text": "MATCH (video1:YoutubeVideo1)-[movie:ACTION_MOVIES]->(video2:YoutubeVideo2) \nRETURN movie"
},
{
"code": null,
"e": 3341,
"s": 3283,
"text": "Step 2 - Click on Execute button and observe the results."
},
{
"code": null,
"e": 3462,
"s": 3341,
"text": "Here, We can observe that STARTNODE of Relationship \"ACTION_MOVIES\" is \"YoutubeVideo1\". Let us check this with function."
},
{
"code": null,
"e": 3523,
"s": 3462,
"text": "Step 3 - Type the below command and click on Execute button."
},
{
"code": null,
"e": 3585,
"s": 3523,
"text": "MATCH (a)-[movie:ACTION_MOVIES]->(b) \nRETURN STARTNODE(movie)"
},
{
"code": null,
"e": 3680,
"s": 3585,
"text": "It uses STARTNODE() Relationship function to print Start Node of Relationship \"ACTION_MOVIES\"."
},
{
"code": null,
"e": 3768,
"s": 3680,
"text": "Here, We can observe that STARTNODE of Relationship \"ACTION_MOVIES\" is \"YoutubeVideo1\"."
},
{
"code": null,
"e": 3778,
"s": 3768,
"text": "Example -"
},
{
"code": null,
"e": 3899,
"s": 3778,
"text": "This example demonstrates how to use CQL ENDNODE Relationship function to retrieve a End Node Details of a Relationship."
},
{
"code": null,
"e": 3995,
"s": 3899,
"text": "Before executing ENDNODE() function on Relationship \"ACTION_MOVIES\", we will check it's details"
},
{
"code": null,
"e": 4061,
"s": 3995,
"text": "Step 1 - Type the below command at dollar prompt in Data Browser."
},
{
"code": null,
"e": 4150,
"s": 4061,
"text": "MATCH (video1:YoutubeVideo1)-[movie:ACTION_MOVIES]->(video2:YoutubeVideo2) \nRETURN movie"
},
{
"code": null,
"e": 4208,
"s": 4150,
"text": "Step 2 - Click on Execute button and observe the results."
},
{
"code": null,
"e": 4328,
"s": 4208,
"text": "Here, We can observe that End Node of Relationship \"ACTION_MOVIES\" is \"YoutubeVideo2\". Let us check this with function."
},
{
"code": null,
"e": 4389,
"s": 4328,
"text": "Step 3 - Type the below command and click on Execute button."
},
{
"code": null,
"e": 4449,
"s": 4389,
"text": "MATCH (a)-[movie:ACTION_MOVIES]->(b) \nRETURN ENDNODE(movie)"
},
{
"code": null,
"e": 4542,
"s": 4449,
"text": "It uses ENDNODE() Relationship function to print Start Node of Relationship \"ACTION_MOVIES\"."
},
{
"code": null,
"e": 4628,
"s": 4542,
"text": "Here, We can observe that ENDNODE of Relationship \"ACTION_MOVIES\" is \"YoutubeVideo2\"."
},
{
"code": null,
"e": 4638,
"s": 4628,
"text": "Example -"
},
{
"code": null,
"e": 4763,
"s": 4638,
"text": "This example demonstrates how to use CQL ID & TYPE Relationship functions to retrieve Id and Type Details of a Relationship."
},
{
"code": null,
"e": 4860,
"s": 4763,
"text": "Before executing ID & TYPE functions on Relationship \"ACTION_MOVIES\", we will check it's details"
},
{
"code": null,
"e": 4926,
"s": 4860,
"text": "Step 1 - Type the below command at dollar prompt in Data Browser."
},
{
"code": null,
"e": 5015,
"s": 4926,
"text": "MATCH (video1:YoutubeVideo1)-[movie:ACTION_MOVIES]->(video2:YoutubeVideo2) \nRETURN movie"
},
{
"code": null,
"e": 5073,
"s": 5015,
"text": "Step 2 - Click on Execute button and observe the results."
},
{
"code": null,
"e": 5205,
"s": 5073,
"text": "Here, We can observe that ID and TYPE of Relationship \"ACTION_MOVIES\" are \"2\" and \"ACTION_MOVIES\". Let us check this with function."
},
{
"code": null,
"e": 5266,
"s": 5205,
"text": "Step 3 - Type the below command and click on Execute button."
},
{
"code": null,
"e": 5333,
"s": 5266,
"text": "MATCH (a)-[movie:ACTION_MOVIES]->(b) \nRETURN ID(movie),TYPE(movie)"
},
{
"code": null,
"e": 5442,
"s": 5333,
"text": "It uses ID() and TYPE() Relationship functions to print ID and Type of Relationship \"ACTION_MOVIES\" details."
},
{
"code": null,
"e": 5541,
"s": 5442,
"text": "Here, We can observe that ID and TYPE of Relationship \"ACTION_MOVIES\" are \"2\" and \"ACTION_MOVIES\"."
},
{
"code": null,
"e": 5548,
"s": 5541,
"text": " Print"
},
{
"code": null,
"e": 5559,
"s": 5548,
"text": " Add Notes"
}
] |
Multiplication of two Matrices in Single line using Numpy in Python - GeeksforGeeks
|
22 Mar, 2022
Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. Example: Multiplication of two matrices by each other of size 3Γ3.
Input:matrix1 = ([1, 2, 3],
[3, 4, 5],
[7, 6, 4])
matrix2 = ([5, 2, 6],
[5, 6, 7],
[7, 6, 4])
Output : [[36 32 32]
[70 60 66]
[93 74 100]]
Methods to multiply two matrices in python 1.Using explicit for loops: This is a simple technique to multiply matrices but one of the expensive method for larger input data set.In this, we use nested for loops to iterate each row and each column. If matrix1 is a n x m matrix and matrix2 is a m x l matrix.
Python3
# input two matrices of size n x mmatrix1 = [[12,7,3], [4 ,5,6], [7 ,8,9]]matrix2 = [[5,8,1], [6,7,3], [4,5,9]] res = [[0 for x in range(3)] for y in range(3)] # explicit for loopsfor i in range(len(matrix1)): for j in range(len(matrix2[0])): for k in range(len(matrix2)): # resulted matrix res[i][j] += matrix1[i][k] * matrix2[k][j] print (res)
Output:
[[114 160 60]
[ 74 97 73]
[119 157 112]]
In this program, we have used nested for loops for computation of result which will iterate through each row and column of the matrices, at last it will accumulate the sum of product in the result. 2. Using Numpy : Multiplication using Numpy also know as vectorization which main aim to reduce or remove the explicit use of for loops in the program by which computation becomes faster. Numpy is a build in a package in python for array-processing and manipulation.For larger matrix operations we use numpy python package which is 1000 times faster than iterative one method. For detail about Numpy please visit the Link
Python3
# We need install numpy in order to import itimport numpy as np # input two matricesmat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7]) # This will return dot productres = np.dot(mat1,mat2) # print resulted matrixprint(res)
Output:
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]
Using numpy
Python3
# same result will be obtained when we use @ operator# as shown below(only in python >3.5)import numpy as np # input two matricesmat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7]) # This will return matrix product of two arrayres = mat1 @ mat2 # print resulted matrixprint(res)
Output:
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]
In the above example we have used dot product and in mathematics the dot product is an algebraic operation that takes two vectors of equal size and returns a single number. The result is calculated by multiplying corresponding entries and adding up those products.This article is contributed by Dheeraj Sharma. 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.
AkshanshSaxena
kashyapabhishek22
vallabhtiwari2020
Python numpy-program
Python-numpy
Matrix
Python
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Sudoku | Backtracking-7
Inplace rotate square matrix by 90 degrees | Set 1
The Celebrity Problem
Min Cost Path | DP-6
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n22 Mar, 2022"
},
{
"code": null,
"e": 25608,
"s": 25224,
"text": "Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. Example: Multiplication of two matrices by each other of size 3Γ3. "
},
{
"code": null,
"e": 25842,
"s": 25608,
"text": "Input:matrix1 = ([1, 2, 3],\n [3, 4, 5],\n [7, 6, 4])\n matrix2 = ([5, 2, 6],\n [5, 6, 7],\n [7, 6, 4])\n\nOutput : [[36 32 32]\n [70 60 66]\n [93 74 100]]"
},
{
"code": null,
"e": 26152,
"s": 25844,
"text": "Methods to multiply two matrices in python 1.Using explicit for loops: This is a simple technique to multiply matrices but one of the expensive method for larger input data set.In this, we use nested for loops to iterate each row and each column. If matrix1 is a n x m matrix and matrix2 is a m x l matrix. "
},
{
"code": null,
"e": 26160,
"s": 26152,
"text": "Python3"
},
{
"code": "# input two matrices of size n x mmatrix1 = [[12,7,3], [4 ,5,6], [7 ,8,9]]matrix2 = [[5,8,1], [6,7,3], [4,5,9]] res = [[0 for x in range(3)] for y in range(3)] # explicit for loopsfor i in range(len(matrix1)): for j in range(len(matrix2[0])): for k in range(len(matrix2)): # resulted matrix res[i][j] += matrix1[i][k] * matrix2[k][j] print (res)",
"e": 26567,
"s": 26160,
"text": null
},
{
"code": null,
"e": 26577,
"s": 26567,
"text": "Output: "
},
{
"code": null,
"e": 26623,
"s": 26577,
"text": "[[114 160 60]\n [ 74 97 73]\n [119 157 112]]"
},
{
"code": null,
"e": 27244,
"s": 26623,
"text": "In this program, we have used nested for loops for computation of result which will iterate through each row and column of the matrices, at last it will accumulate the sum of product in the result. 2. Using Numpy : Multiplication using Numpy also know as vectorization which main aim to reduce or remove the explicit use of for loops in the program by which computation becomes faster. Numpy is a build in a package in python for array-processing and manipulation.For larger matrix operations we use numpy python package which is 1000 times faster than iterative one method. For detail about Numpy please visit the Link "
},
{
"code": null,
"e": 27252,
"s": 27244,
"text": "Python3"
},
{
"code": "# We need install numpy in order to import itimport numpy as np # input two matricesmat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7]) # This will return dot productres = np.dot(mat1,mat2) # print resulted matrixprint(res)",
"e": 27503,
"s": 27252,
"text": null
},
{
"code": null,
"e": 27513,
"s": 27503,
"text": "Output: "
},
{
"code": null,
"e": 27559,
"s": 27513,
"text": "[[ 63 320 83]\n [ 77 484 102]\n [ 84 248 117]]"
},
{
"code": null,
"e": 27573,
"s": 27559,
"text": "Using numpy "
},
{
"code": null,
"e": 27581,
"s": 27573,
"text": "Python3"
},
{
"code": "# same result will be obtained when we use @ operator# as shown below(only in python >3.5)import numpy as np # input two matricesmat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7]) # This will return matrix product of two arrayres = mat1 @ mat2 # print resulted matrixprint(res)",
"e": 27889,
"s": 27581,
"text": null
},
{
"code": null,
"e": 27899,
"s": 27889,
"text": "Output: "
},
{
"code": null,
"e": 27945,
"s": 27899,
"text": "[[ 63 320 83]\n [ 77 484 102]\n [ 84 248 117]]"
},
{
"code": null,
"e": 28632,
"s": 27945,
"text": "In the above example we have used dot product and in mathematics the dot product is an algebraic operation that takes two vectors of equal size and returns a single number. The result is calculated by multiplying corresponding entries and adding up those products.This article is contributed by Dheeraj Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28647,
"s": 28632,
"text": "AkshanshSaxena"
},
{
"code": null,
"e": 28665,
"s": 28647,
"text": "kashyapabhishek22"
},
{
"code": null,
"e": 28683,
"s": 28665,
"text": "vallabhtiwari2020"
},
{
"code": null,
"e": 28704,
"s": 28683,
"text": "Python numpy-program"
},
{
"code": null,
"e": 28717,
"s": 28704,
"text": "Python-numpy"
},
{
"code": null,
"e": 28724,
"s": 28717,
"text": "Matrix"
},
{
"code": null,
"e": 28731,
"s": 28724,
"text": "Python"
},
{
"code": null,
"e": 28738,
"s": 28731,
"text": "Matrix"
},
{
"code": null,
"e": 28836,
"s": 28738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28845,
"s": 28836,
"text": "Comments"
},
{
"code": null,
"e": 28858,
"s": 28845,
"text": "Old Comments"
},
{
"code": null,
"e": 28882,
"s": 28858,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 28933,
"s": 28882,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 28955,
"s": 28933,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 28976,
"s": 28955,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 29058,
"s": 28976,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 29086,
"s": 29058,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29136,
"s": 29086,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29158,
"s": 29136,
"text": "Python map() function"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.