title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Number of Triangles in an Undirected Graph - GeeksforGeeks
18 Apr, 2022 Given an Undirected simple graph, We need to find how many triangles it can have. For example below graph have 2 triangles in it. Let A[][] be the adjacency matrix representation of the graph. If we calculate A3, then the number of triangles in Undirected Graph is equal to trace(A3) / 6. Where trace(A) is the sum of the elements on the main diagonal of matrix A. Trace of a graph represented as adjacency matrix A[V][V] is, trace(A[V][V]) = A[0][0] + A[1][1] + .... + A[V-1][V-1] Count of triangles = trace(A3) / 6 Below is the implementation of the above formula. C++ Java Python3 C# Javascript // A C++ program for finding// number of triangles in an// Undirected Graph. The program// is for adjacency matrix// representation of the graph#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 4 // Utility function for matrix// multiplicationvoid multiply(int A[][V], int B[][V], int C[][V]){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { C[i][j] = 0; for (int k = 0; k < V; k++) C[i][j] += A[i][k]*B[k][j]; } }} // Utility function to calculate// trace of a matrix (sum of// diagonal elements)int getTrace(int graph[][V]){ int trace = 0; for (int i = 0; i < V; i++) trace += graph[i][i]; return trace;} // Utility function for calculating// number of triangles in graphint triangleInGraph(int graph[][V]){ // To Store graph^2 int aux2[V][V]; // To Store graph^3 int aux3[V][V]; // Initialising aux // matrices with 0 for (int i = 0; i < V; ++i) for (int j = 0; j < V; ++j) aux2[i][j] = aux3[i][j] = 0; // aux2 is graph^2 now printMatrix(aux2); multiply(graph, graph, aux2); // after this multiplication aux3 is // graph^3 printMatrix(aux3); multiply(graph, aux2, aux3); int trace = getTrace(aux3); return trace / 6;} // driver codeint main(){ int graph[V][V] = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0} }; printf("Total number of Triangle in Graph : %d\n", triangleInGraph(graph)); return 0;} // Java program to find number// of triangles in an Undirected// Graph. The program is for// adjacency matrix representation// of the graphimport java.io.*; class Directed{ // Number of vertices in // the graph int V = 4; // Utility function for // matrix multiplication void multiply(int A[][], int B[][], int C[][]) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { C[i][j] = 0; for (int k = 0; k < V; k++) { C[i][j] += A[i][k]* B[k][j]; } } } } // Utility function to calculate // trace of a matrix (sum of // diagonal elements) int getTrace(int graph[][]) { int trace = 0; for (int i = 0; i < V; i++) { trace += graph[i][i]; } return trace; } // Utility function for // calculating number of // triangles in graph int triangleInGraph(int graph[][]) { // To Store graph^2 int[][] aux2 = new int[V][V]; // To Store graph^3 int[][] aux3 = new int[V][V]; // Initialising aux matrices // with 0 for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { aux2[i][j] = aux3[i][j] = 0; } } // aux2 is graph^2 now // printMatrix(aux2) multiply(graph, graph, aux2); // after this multiplication aux3 // is graph^3 printMatrix(aux3) multiply(graph, aux2, aux3); int trace = getTrace(aux3); return trace / 6; } // Driver code public static void main(String args[]) { Directed obj = new Directed(); int graph[][] = { {0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0} }; System.out.println("Total number of Triangle in Graph : "+ obj.triangleInGraph(graph)); }} // This code is contributed by Anshika Goyal. # A Python3 program for finding number of# triangles in an Undirected Graph. The# program is for adjacency matrix# representation of the graph # Utility function for matrix# multiplicationdef multiply(A, B, C): global V for i in range(V): for j in range(V): C[i][j] = 0 for k in range(V): C[i][j] += A[i][k] * B[k][j] # Utility function to calculate# trace of a matrix (sum of# diagonal elements)def getTrace(graph): global V trace = 0 for i in range(V): trace += graph[i][i] return trace # Utility function for calculating# number of triangles in graphdef triangleInGraph(graph): global V # To Store graph^2 aux2 = [[None] * V for i in range(V)] # To Store graph^3 aux3 = [[None] * V for i in range(V)] # Initialising aux # matrices with 0 for i in range(V): for j in range(V): aux2[i][j] = aux3[i][j] = 0 # aux2 is graph^2 now printMatrix(aux2) multiply(graph, graph, aux2) # after this multiplication aux3 is # graph^3 printMatrix(aux3) multiply(graph, aux2, aux3) trace = getTrace(aux3) return trace // 6 # Driver Code # Number of vertices in the graphV = 4graph = [[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]] print("Total number of Triangle in Graph :", triangleInGraph(graph)) # This code is contributed by PranchalK // C# program to find number// of triangles in an Undirected// Graph. The program is for// adjacency matrix representation// of the graphusing System; class GFG{// Number of vertices// in the graphint V = 4; // Utility function for// matrix multiplicationvoid multiply(int [,]A, int [,]B, int [,]C){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { C[i, j] = 0; for (int k = 0; k < V; k++) { C[i, j] += A[i, k]* B[k, j]; } } }} // Utility function to// calculate trace of// a matrix (sum of// diagonal elements)int getTrace(int [,]graph){ int trace = 0; for (int i = 0; i < V; i++) { trace += graph[i, i]; } return trace;} // Utility function for// calculating number of// triangles in graphint triangleInGraph(int [,]graph){ // To Store graph^2 int[,] aux2 = new int[V, V]; // To Store graph^3 int[,] aux3 = new int[V, V]; // Initialising aux matrices // with 0 for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { aux2[i, j] = aux3[i, j] = 0; } } // aux2 is graph^2 now // printMatrix(aux2) multiply(graph, graph, aux2); // after this multiplication aux3 // is graph^3 printMatrix(aux3) multiply(graph, aux2, aux3); int trace = getTrace(aux3); return trace / 6;} // Driver codepublic static void Main(){ GFG obj = new GFG(); int [,]graph = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0}}; Console.WriteLine("Total number of " + "Triangle in Graph : "+ obj.triangleInGraph(graph));}} // This code is contributed by anuj_67. <script> // Javascript program to find number// of triangles in an Undirected// Graph. The program is for// adjacency matrix representation// of the graph // Number of vertices in the graphlet V = 4; // Utility function for matrix// multiplicationfunction multiply(A, B, C){ for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { C[i][j] = 0; for(let k = 0; k < V; k++) C[i][j] += A[i][k] * B[k][j]; } }} // Utility function to calculate// trace of a matrix (sum of// diagonal elements)function getTrace(graph){ let trace = 0; for(let i = 0; i < V; i++) trace += graph[i][i]; return trace;} // Utility function for calculating// number of triangles in graphfunction triangleInGraph(graph){ // To Store graph^2 let aux2 = new Array(V); // To Store graph^3 let aux3 = new Array(V); // Initialising aux // matrices with 0 for(let i = 0; i < V; ++i) { aux2[i] = new Array(V); aux3[i] = new Array(V); for(let j = 0; j < V; ++j) { aux2[i][j] = aux3[i][j] = 0; } } // aux2 is graph^2 now printMatrix(aux2); multiply(graph, graph, aux2); // After this multiplication aux3 is // graph^3 printMatrix(aux3); multiply(graph, aux2, aux3); let trace = getTrace(aux3); return (trace / 6);} // Driver codelet graph = [ [ 0, 1, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 1, 0 ] ]; document.write("Total number of Triangle in Graph : " + triangleInGraph(graph)); // This code is contributed by divyesh072019 </script> Output: Total number of Triangle in Graph : 2 How does this work? If we compute An for an adjacency matrix representation of the graph, then a value An[i][j] represents the number of distinct walks between vertex i to j in the graph. In A3, we get all distinct paths of length 3 between every pair of vertices.A triangle is a cyclic path of length three, i.e. begins and ends at the same vertex. So A3[i][i] represents a triangle beginning and ending with vertex i. Since a triangle has three vertices and it is counted for every vertex, we need to divide the result by 3. Furthermore, since the graph is undirected, every triangle twice as i-p-q-j and i-q-p-j, so we divide by 2 also. Therefore, the number of triangles is trace(A3) / 6. Time Complexity: The time complexity of above algorithm is O(V3) where V is number of vertices in the graph, we can improve the performance to O(V2.8074) using Strassen’s matrix multiplication algorithm. YouTubeGeeksforGeeks502K subscribersNumber of Triangles in an Undirected Graph | GeeksForGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ChdNz1Ui1uc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Another approach: Using Bitsets as adjacency lists. For each node in the graph compute the corresponding adjacency list as a bitmask. If two nodes, i & j, are adjacent compute the number of nodes that are adjacent to i & j and add it to the answer. In the end, divide the answer by 6 to avoid duplicates. In order to compute the number of nodes adjacent to two nodes, i & j, we use the bitwise operation & (and) on the adjacency list of i and j, then we count the number of ones. Below is the implementation of the above approach: C++ #include<iostream>#include<string>#include<algorithm>#include<cstring>#include<vector>#include<bitset> using namespace std; #define V 4 int main(){ // Graph represented as adjacency matrix int graph[][V] = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0}}; // create the adjacency list of the graph (as bit masks) // set the bits at positions [i][j] & [j][i] to 1, if there is an undirected edge between i and j vector<bitset<V>> Bitset_Adj_List(V); for (int i = 0; i < V;i++) for (int j = 0; j < V;j++) if(graph[i][j]) Bitset_Adj_List[i][j] = 1, Bitset_Adj_List[j][i] = 1; int ans = 0; for (int i = 0; i < V;i++) for (int j = 0; j < V;j++) // if i & j are adjacent // compute the number of nodes that are adjacent to i & j if(Bitset_Adj_List[i][j] == 1 && i != j){ bitset<V> Mask = Bitset_Adj_List[i] & Bitset_Adj_List[j]; ans += Mask.count(); } // divide the answer by 6 to avoid duplicates ans /= 6; cout << "The number of Triangles in the Graph is : " << ans; // This code is contributed // by Gatea David} The number of Triangles in the Graph is : 2 Time Complexity: First we have the two for nested loops O(V2) flowed by Bitset operations & and count, both have a time complexity of O(V / Word RAM), where V = number of nodes in the graph and Word RAM is usually 32 or 64. So the final time complexity is O(V2 * V / 32) or O(V3). References: http://www.d.umn.edu/math/Technical%20Reports/Technical%20Reports%202007-/TR%202012/yang.pdf Number of Triangles in Directed and Undirected Graphs. This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m PranchalKatiyar divyesh072019 davidgatea21 simmytarika5 surindertarika1234 surinderdawra388 triangle Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Check whether a given graph is Bipartite or not Ford-Fulkerson Algorithm for Maximum Flow Problem Traveling Salesman Problem (TSP) Implementation Detect cycle in an undirected graph Shortest path in an unweighted graph Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
[ { "code": null, "e": 25016, "s": 24988, "text": "\n18 Apr, 2022" }, { "code": null, "e": 25147, "s": 25016, "text": "Given an Undirected simple graph, We need to find how many triangles it can have. For example below graph have 2 triangles in it. " }, { "code": null, "e": 25384, "s": 25147, "text": "Let A[][] be the adjacency matrix representation of the graph. If we calculate A3, then the number of triangles in Undirected Graph is equal to trace(A3) / 6. Where trace(A) is the sum of the elements on the main diagonal of matrix A. " }, { "code": null, "e": 25537, "s": 25384, "text": "Trace of a graph represented as adjacency matrix A[V][V] is,\ntrace(A[V][V]) = A[0][0] + A[1][1] + .... + A[V-1][V-1]\n\nCount of triangles = trace(A3) / 6" }, { "code": null, "e": 25588, "s": 25537, "text": "Below is the implementation of the above formula. " }, { "code": null, "e": 25592, "s": 25588, "text": "C++" }, { "code": null, "e": 25597, "s": 25592, "text": "Java" }, { "code": null, "e": 25605, "s": 25597, "text": "Python3" }, { "code": null, "e": 25608, "s": 25605, "text": "C#" }, { "code": null, "e": 25619, "s": 25608, "text": "Javascript" }, { "code": "// A C++ program for finding// number of triangles in an// Undirected Graph. The program// is for adjacency matrix// representation of the graph#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 4 // Utility function for matrix// multiplicationvoid multiply(int A[][V], int B[][V], int C[][V]){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { C[i][j] = 0; for (int k = 0; k < V; k++) C[i][j] += A[i][k]*B[k][j]; } }} // Utility function to calculate// trace of a matrix (sum of// diagonal elements)int getTrace(int graph[][V]){ int trace = 0; for (int i = 0; i < V; i++) trace += graph[i][i]; return trace;} // Utility function for calculating// number of triangles in graphint triangleInGraph(int graph[][V]){ // To Store graph^2 int aux2[V][V]; // To Store graph^3 int aux3[V][V]; // Initialising aux // matrices with 0 for (int i = 0; i < V; ++i) for (int j = 0; j < V; ++j) aux2[i][j] = aux3[i][j] = 0; // aux2 is graph^2 now printMatrix(aux2); multiply(graph, graph, aux2); // after this multiplication aux3 is // graph^3 printMatrix(aux3); multiply(graph, aux2, aux3); int trace = getTrace(aux3); return trace / 6;} // driver codeint main(){ int graph[V][V] = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0} }; printf(\"Total number of Triangle in Graph : %d\\n\", triangleInGraph(graph)); return 0;}", "e": 27242, "s": 25619, "text": null }, { "code": "// Java program to find number// of triangles in an Undirected// Graph. The program is for// adjacency matrix representation// of the graphimport java.io.*; class Directed{ // Number of vertices in // the graph int V = 4; // Utility function for // matrix multiplication void multiply(int A[][], int B[][], int C[][]) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { C[i][j] = 0; for (int k = 0; k < V; k++) { C[i][j] += A[i][k]* B[k][j]; } } } } // Utility function to calculate // trace of a matrix (sum of // diagonal elements) int getTrace(int graph[][]) { int trace = 0; for (int i = 0; i < V; i++) { trace += graph[i][i]; } return trace; } // Utility function for // calculating number of // triangles in graph int triangleInGraph(int graph[][]) { // To Store graph^2 int[][] aux2 = new int[V][V]; // To Store graph^3 int[][] aux3 = new int[V][V]; // Initialising aux matrices // with 0 for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { aux2[i][j] = aux3[i][j] = 0; } } // aux2 is graph^2 now // printMatrix(aux2) multiply(graph, graph, aux2); // after this multiplication aux3 // is graph^3 printMatrix(aux3) multiply(graph, aux2, aux3); int trace = getTrace(aux3); return trace / 6; } // Driver code public static void main(String args[]) { Directed obj = new Directed(); int graph[][] = { {0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0} }; System.out.println(\"Total number of Triangle in Graph : \"+ obj.triangleInGraph(graph)); }} // This code is contributed by Anshika Goyal.", "e": 29362, "s": 27242, "text": null }, { "code": "# A Python3 program for finding number of# triangles in an Undirected Graph. The# program is for adjacency matrix# representation of the graph # Utility function for matrix# multiplicationdef multiply(A, B, C): global V for i in range(V): for j in range(V): C[i][j] = 0 for k in range(V): C[i][j] += A[i][k] * B[k][j] # Utility function to calculate# trace of a matrix (sum of# diagonal elements)def getTrace(graph): global V trace = 0 for i in range(V): trace += graph[i][i] return trace # Utility function for calculating# number of triangles in graphdef triangleInGraph(graph): global V # To Store graph^2 aux2 = [[None] * V for i in range(V)] # To Store graph^3 aux3 = [[None] * V for i in range(V)] # Initialising aux # matrices with 0 for i in range(V): for j in range(V): aux2[i][j] = aux3[i][j] = 0 # aux2 is graph^2 now printMatrix(aux2) multiply(graph, graph, aux2) # after this multiplication aux3 is # graph^3 printMatrix(aux3) multiply(graph, aux2, aux3) trace = getTrace(aux3) return trace // 6 # Driver Code # Number of vertices in the graphV = 4graph = [[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]] print(\"Total number of Triangle in Graph :\", triangleInGraph(graph)) # This code is contributed by PranchalK", "e": 30782, "s": 29362, "text": null }, { "code": "// C# program to find number// of triangles in an Undirected// Graph. The program is for// adjacency matrix representation// of the graphusing System; class GFG{// Number of vertices// in the graphint V = 4; // Utility function for// matrix multiplicationvoid multiply(int [,]A, int [,]B, int [,]C){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { C[i, j] = 0; for (int k = 0; k < V; k++) { C[i, j] += A[i, k]* B[k, j]; } } }} // Utility function to// calculate trace of// a matrix (sum of// diagonal elements)int getTrace(int [,]graph){ int trace = 0; for (int i = 0; i < V; i++) { trace += graph[i, i]; } return trace;} // Utility function for// calculating number of// triangles in graphint triangleInGraph(int [,]graph){ // To Store graph^2 int[,] aux2 = new int[V, V]; // To Store graph^3 int[,] aux3 = new int[V, V]; // Initialising aux matrices // with 0 for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { aux2[i, j] = aux3[i, j] = 0; } } // aux2 is graph^2 now // printMatrix(aux2) multiply(graph, graph, aux2); // after this multiplication aux3 // is graph^3 printMatrix(aux3) multiply(graph, aux2, aux3); int trace = getTrace(aux3); return trace / 6;} // Driver codepublic static void Main(){ GFG obj = new GFG(); int [,]graph = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0}}; Console.WriteLine(\"Total number of \" + \"Triangle in Graph : \"+ obj.triangleInGraph(graph));}} // This code is contributed by anuj_67.", "e": 32620, "s": 30782, "text": null }, { "code": "<script> // Javascript program to find number// of triangles in an Undirected// Graph. The program is for// adjacency matrix representation// of the graph // Number of vertices in the graphlet V = 4; // Utility function for matrix// multiplicationfunction multiply(A, B, C){ for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { C[i][j] = 0; for(let k = 0; k < V; k++) C[i][j] += A[i][k] * B[k][j]; } }} // Utility function to calculate// trace of a matrix (sum of// diagonal elements)function getTrace(graph){ let trace = 0; for(let i = 0; i < V; i++) trace += graph[i][i]; return trace;} // Utility function for calculating// number of triangles in graphfunction triangleInGraph(graph){ // To Store graph^2 let aux2 = new Array(V); // To Store graph^3 let aux3 = new Array(V); // Initialising aux // matrices with 0 for(let i = 0; i < V; ++i) { aux2[i] = new Array(V); aux3[i] = new Array(V); for(let j = 0; j < V; ++j) { aux2[i][j] = aux3[i][j] = 0; } } // aux2 is graph^2 now printMatrix(aux2); multiply(graph, graph, aux2); // After this multiplication aux3 is // graph^3 printMatrix(aux3); multiply(graph, aux2, aux3); let trace = getTrace(aux3); return (trace / 6);} // Driver codelet graph = [ [ 0, 1, 1, 0 ], [ 1, 0, 1, 1 ], [ 1, 1, 0, 1 ], [ 0, 1, 1, 0 ] ]; document.write(\"Total number of Triangle in Graph : \" + triangleInGraph(graph)); // This code is contributed by divyesh072019 </script>", "e": 34305, "s": 32620, "text": null }, { "code": null, "e": 34314, "s": 34305, "text": "Output: " }, { "code": null, "e": 34352, "s": 34314, "text": "Total number of Triangle in Graph : 2" }, { "code": null, "e": 35045, "s": 34352, "text": "How does this work? If we compute An for an adjacency matrix representation of the graph, then a value An[i][j] represents the number of distinct walks between vertex i to j in the graph. In A3, we get all distinct paths of length 3 between every pair of vertices.A triangle is a cyclic path of length three, i.e. begins and ends at the same vertex. So A3[i][i] represents a triangle beginning and ending with vertex i. Since a triangle has three vertices and it is counted for every vertex, we need to divide the result by 3. Furthermore, since the graph is undirected, every triangle twice as i-p-q-j and i-q-p-j, so we divide by 2 also. Therefore, the number of triangles is trace(A3) / 6." }, { "code": null, "e": 35250, "s": 35045, "text": "Time Complexity: The time complexity of above algorithm is O(V3) where V is number of vertices in the graph, we can improve the performance to O(V2.8074) using Strassen’s matrix multiplication algorithm. " }, { "code": null, "e": 36091, "s": 35250, "text": "YouTubeGeeksforGeeks502K subscribersNumber of Triangles in an Undirected Graph | GeeksForGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:44•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ChdNz1Ui1uc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36143, "s": 36091, "text": "Another approach: Using Bitsets as adjacency lists." }, { "code": null, "e": 36225, "s": 36143, "text": "For each node in the graph compute the corresponding adjacency list as a bitmask." }, { "code": null, "e": 36340, "s": 36225, "text": "If two nodes, i & j, are adjacent compute the number of nodes that are adjacent to i & j and add it to the answer." }, { "code": null, "e": 36396, "s": 36340, "text": "In the end, divide the answer by 6 to avoid duplicates." }, { "code": null, "e": 36571, "s": 36396, "text": "In order to compute the number of nodes adjacent to two nodes, i & j, we use the bitwise operation & (and) on the adjacency list of i and j, then we count the number of ones." }, { "code": null, "e": 36622, "s": 36571, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 36626, "s": 36622, "text": "C++" }, { "code": "#include<iostream>#include<string>#include<algorithm>#include<cstring>#include<vector>#include<bitset> using namespace std; #define V 4 int main(){ // Graph represented as adjacency matrix int graph[][V] = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0}}; // create the adjacency list of the graph (as bit masks) // set the bits at positions [i][j] & [j][i] to 1, if there is an undirected edge between i and j vector<bitset<V>> Bitset_Adj_List(V); for (int i = 0; i < V;i++) for (int j = 0; j < V;j++) if(graph[i][j]) Bitset_Adj_List[i][j] = 1, Bitset_Adj_List[j][i] = 1; int ans = 0; for (int i = 0; i < V;i++) for (int j = 0; j < V;j++) // if i & j are adjacent // compute the number of nodes that are adjacent to i & j if(Bitset_Adj_List[i][j] == 1 && i != j){ bitset<V> Mask = Bitset_Adj_List[i] & Bitset_Adj_List[j]; ans += Mask.count(); } // divide the answer by 6 to avoid duplicates ans /= 6; cout << \"The number of Triangles in the Graph is : \" << ans; // This code is contributed // by Gatea David}", "e": 37893, "s": 36626, "text": null }, { "code": null, "e": 37937, "s": 37893, "text": "The number of Triangles in the Graph is : 2" }, { "code": null, "e": 38218, "s": 37937, "text": "Time Complexity: First we have the two for nested loops O(V2) flowed by Bitset operations & and count, both have a time complexity of O(V / Word RAM), where V = number of nodes in the graph and Word RAM is usually 32 or 64. So the final time complexity is O(V2 * V / 32) or O(V3)." }, { "code": null, "e": 38230, "s": 38218, "text": "References:" }, { "code": null, "e": 38323, "s": 38230, "text": "http://www.d.umn.edu/math/Technical%20Reports/Technical%20Reports%202007-/TR%202012/yang.pdf" }, { "code": null, "e": 38379, "s": 38323, "text": "Number of Triangles in Directed and Undirected Graphs. " }, { "code": null, "e": 38552, "s": 38379, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38557, "s": 38552, "text": "vt_m" }, { "code": null, "e": 38573, "s": 38557, "text": "PranchalKatiyar" }, { "code": null, "e": 38587, "s": 38573, "text": "divyesh072019" }, { "code": null, "e": 38600, "s": 38587, "text": "davidgatea21" }, { "code": null, "e": 38613, "s": 38600, "text": "simmytarika5" }, { "code": null, "e": 38632, "s": 38613, "text": "surindertarika1234" }, { "code": null, "e": 38649, "s": 38632, "text": "surinderdawra388" }, { "code": null, "e": 38658, "s": 38649, "text": "triangle" }, { "code": null, "e": 38664, "s": 38658, "text": "Graph" }, { "code": null, "e": 38670, "s": 38664, "text": "Graph" }, { "code": null, "e": 38768, "s": 38670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38788, "s": 38768, "text": "Topological Sorting" }, { "code": null, "e": 38821, "s": 38788, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 38896, "s": 38821, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 38964, "s": 38896, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 39012, "s": 38964, "text": "Check whether a given graph is Bipartite or not" }, { "code": null, "e": 39062, "s": 39012, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 39110, "s": 39062, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 39146, "s": 39110, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 39183, "s": 39146, "text": "Shortest path in an unweighted graph" } ]
TypeORM - Working with Repository
Repository is specific to an entity. In other words, each entity will have its own, build-in repository and it can be accessed using getRepository() method of connection object as specified below − const studRepository = manager.getRepository(Student); Once the student repository object is created, it can be used to do all database operation of student object. Repository is classified into four categories. They are as follows − Default repository of an entity and it can be accessed using getRepository() method as specified below − const studRepository = manager.getRepository(Student); Now, studRepository can be used to query student table Used for tree like structure entities and it can be accessed using getTreeRepository() method as specified below − const studcaRepository = manager.getTreeRepository(Student); Used inside mongoDB operation entities and it can be accessed using getMongoRepository() method as specified below − const detailsRepository = manager.getMongoRepository(Details); Used to customize the repository and it can be accessed using getCustomRepository() method as specified below, const myUserRepository = manager.getCustomRepository(UserRepository); Let us learn most important method of the EntityManager in this chapter. We can access EntityManager using manager method as specified below − const manager = repository.manager; queryRunner method returns custom query runner object and it is used for database operations by repository. The sample code is as follows − const queryRunner = repository.queryRunner; metadata returns repository’s metadata. The sample code is as follows − const metadata = repository.metadata; query method executes SQL queries. Simple select query as shown below − const qur = await repository.query(`select * from students`); insert method is used to insert a new entity or array of entities to the database. The sample code is as follows − await repository.insert({ Name: "Student3", Age: 14 }); The above query is equivalent to, insert into student(Name,age) values("Student3",14) update is used to update the existing records in the database. await repository.update(1, { Name: "Adam" }); This query works similar to the one mentioned below − update student SET Name = "Adam" where id = 1 delete method will delete the specified record from the table, await repository.delete(Student, 1); This will delete student with id 1 from the student table. It is equivalent to, delete from student where id=1; If you want to delete by name then use the below query, await repository.delete({ Name: "Student1" }); This query will delete all the student having name, Student1 ** softDelete and restore ** It is used to soft delete the data and you can restore the record based on the id of the student. The sample code is as follows − await repository.softDelete(1); You can restore the student record using below command − await repository.restore(1); An alternative option to delete and restore is to use softRemove and recover methods. The sample code is as follows − //find the entities const enty = await repository.find(); //soft removed entity const entySoftRemove = await repository.softRemove(enty); And, you can recover them using recover method as specified below, await repository.recover(entySoftRemove); save is used to save the given entity into the database. Simple Student entity can be save as shown below − import {Student} from "./entity/Student"; createConnection().then(async connection => { console.log("Inserting a new record into the student database..."); const stud = new Student(); stud.Name = "student1"; stud.age = 12; await repository.save(stud); This will add new student record into the database. remove is used to delete the given entity from the database. Simple Student entity can be deleted as shown below − await repository.remove(stud); count method will return the number of records available in the table and you can use it pagination purposes. The sample code is as follows − const cnt = await repository.count(Student, { age: 12 }); find method is used for searching purposes. It fetches all the record from database as shown below − const result = await repository.find({ id: 1 }); Similar to find method, but returns the first matched record. The sample code is as follows − const result = await repository.findOne({ id: 1 }); clear method clears all the data from the table. The sample code is as follows − await repository.clear(); 19 Lectures 50 mins James Coonce Print Add Notes Bookmark this page
[ { "code": null, "e": 2249, "s": 2051, "text": "Repository is specific to an entity. In other words, each entity will have its own, build-in repository and it can be accessed using getRepository() method of connection object as specified below −" }, { "code": null, "e": 2305, "s": 2249, "text": "const studRepository = manager.getRepository(Student);\n" }, { "code": null, "e": 2415, "s": 2305, "text": "Once the student repository object is created, it can be used to do all database operation of student object." }, { "code": null, "e": 2484, "s": 2415, "text": "Repository is classified into four categories. They are as follows −" }, { "code": null, "e": 2589, "s": 2484, "text": "Default repository of an entity and it can be accessed using getRepository() method as specified below −" }, { "code": null, "e": 2645, "s": 2589, "text": "const studRepository = manager.getRepository(Student);\n" }, { "code": null, "e": 2700, "s": 2645, "text": "Now, studRepository can be used to query student table" }, { "code": null, "e": 2815, "s": 2700, "text": "Used for tree like structure entities and it can be accessed using getTreeRepository() method as specified below −" }, { "code": null, "e": 2877, "s": 2815, "text": "const studcaRepository = manager.getTreeRepository(Student);\n" }, { "code": null, "e": 2994, "s": 2877, "text": "Used inside mongoDB operation entities and it can be accessed using getMongoRepository() method as specified below −" }, { "code": null, "e": 3058, "s": 2994, "text": "const detailsRepository = manager.getMongoRepository(Details);\n" }, { "code": null, "e": 3169, "s": 3058, "text": "Used to customize the repository and it can be accessed using getCustomRepository() method as specified below," }, { "code": null, "e": 3240, "s": 3169, "text": "const myUserRepository = manager.getCustomRepository(UserRepository);\n" }, { "code": null, "e": 3313, "s": 3240, "text": "Let us learn most important method of the EntityManager in this chapter." }, { "code": null, "e": 3383, "s": 3313, "text": "We can access EntityManager using manager method as specified below −" }, { "code": null, "e": 3420, "s": 3383, "text": "const manager = repository.manager;\n" }, { "code": null, "e": 3560, "s": 3420, "text": "queryRunner method returns custom query runner object and it is used for database operations by repository. The sample code is as follows −" }, { "code": null, "e": 3605, "s": 3560, "text": "const queryRunner = repository.queryRunner;\n" }, { "code": null, "e": 3677, "s": 3605, "text": "metadata returns repository’s metadata. The sample code is as follows −" }, { "code": null, "e": 3716, "s": 3677, "text": "const metadata = repository.metadata;\n" }, { "code": null, "e": 3788, "s": 3716, "text": "query method executes SQL queries. Simple select query as shown below −" }, { "code": null, "e": 3851, "s": 3788, "text": "const qur = await repository.query(`select * from students`);\n" }, { "code": null, "e": 3966, "s": 3851, "text": "insert method is used to insert a new entity or array of entities to the database. The sample code is as follows −" }, { "code": null, "e": 4032, "s": 3966, "text": "await repository.insert({ \n Name: \"Student3\", \n Age: 14 \n});\n" }, { "code": null, "e": 4066, "s": 4032, "text": "The above query is equivalent to," }, { "code": null, "e": 4119, "s": 4066, "text": "insert into student(Name,age) values(\"Student3\",14)\n" }, { "code": null, "e": 4182, "s": 4119, "text": "update is used to update the existing records in the database." }, { "code": null, "e": 4229, "s": 4182, "text": "await repository.update(1, { Name: \"Adam\" });\n" }, { "code": null, "e": 4283, "s": 4229, "text": "This query works similar to the one mentioned below −" }, { "code": null, "e": 4330, "s": 4283, "text": "update student SET Name = \"Adam\" where id = 1\n" }, { "code": null, "e": 4393, "s": 4330, "text": "delete method will delete the specified record from the table," }, { "code": null, "e": 4431, "s": 4393, "text": "await repository.delete(Student, 1);\n" }, { "code": null, "e": 4511, "s": 4431, "text": "This will delete student with id 1 from the student table. It is equivalent to," }, { "code": null, "e": 4544, "s": 4511, "text": "delete from student where id=1;\n" }, { "code": null, "e": 4600, "s": 4544, "text": "If you want to delete by name then use the below query," }, { "code": null, "e": 4648, "s": 4600, "text": "await repository.delete({ Name: \"Student1\" });\n" }, { "code": null, "e": 4709, "s": 4648, "text": "This query will delete all the student having name, Student1" }, { "code": null, "e": 4738, "s": 4709, "text": "** softDelete and restore **" }, { "code": null, "e": 4868, "s": 4738, "text": "It is used to soft delete the data and you can restore the record based on the id of the student. The sample code is as follows −" }, { "code": null, "e": 4901, "s": 4868, "text": "await repository.softDelete(1);\n" }, { "code": null, "e": 4958, "s": 4901, "text": "You can restore the student record using below command −" }, { "code": null, "e": 4988, "s": 4958, "text": "await repository.restore(1);\n" }, { "code": null, "e": 5106, "s": 4988, "text": "An alternative option to delete and restore is to use softRemove and recover methods. The sample code is as follows −" }, { "code": null, "e": 5247, "s": 5106, "text": "//find the entities const enty = await repository.find(); \n\n//soft removed entity const entySoftRemove = await repository.softRemove(enty);\n" }, { "code": null, "e": 5314, "s": 5247, "text": "And, you can recover them using recover method as specified below," }, { "code": null, "e": 5357, "s": 5314, "text": "await repository.recover(entySoftRemove);\n" }, { "code": null, "e": 5465, "s": 5357, "text": "save is used to save the given entity into the database. Simple Student entity can be save as shown below −" }, { "code": null, "e": 5759, "s": 5465, "text": "import {Student} from \"./entity/Student\"; \n\ncreateConnection().then(async connection => { \n console.log(\"Inserting a new record into the student database...\"); \n const stud = new Student();\n stud.Name = \"student1\"; \n stud.age = 12; \n await repository.save(stud);\n" }, { "code": null, "e": 5811, "s": 5759, "text": "This will add new student record into the database." }, { "code": null, "e": 5926, "s": 5811, "text": "remove is used to delete the given entity from the database. Simple Student entity can be deleted as shown below −" }, { "code": null, "e": 5958, "s": 5926, "text": "await repository.remove(stud);\n" }, { "code": null, "e": 6100, "s": 5958, "text": "count method will return the number of records available in the table and you can use it pagination purposes. The sample code is as follows −" }, { "code": null, "e": 6159, "s": 6100, "text": "const cnt = await repository.count(Student, { age: 12 });\n" }, { "code": null, "e": 6260, "s": 6159, "text": "find method is used for searching purposes. It fetches all the record from database as shown below −" }, { "code": null, "e": 6310, "s": 6260, "text": "const result = await repository.find({ id: 1 });\n" }, { "code": null, "e": 6404, "s": 6310, "text": "Similar to find method, but returns the first matched record. The sample code is as follows −" }, { "code": null, "e": 6457, "s": 6404, "text": "const result = await repository.findOne({ id: 1 });\n" }, { "code": null, "e": 6538, "s": 6457, "text": "clear method clears all the data from the table. The sample code is as follows −" }, { "code": null, "e": 6565, "s": 6538, "text": "await repository.clear();\n" }, { "code": null, "e": 6597, "s": 6565, "text": "\n 19 Lectures \n 50 mins\n" }, { "code": null, "e": 6611, "s": 6597, "text": " James Coonce" }, { "code": null, "e": 6618, "s": 6611, "text": " Print" }, { "code": null, "e": 6629, "s": 6618, "text": " Add Notes" } ]
Neo4j CQL - Sorting
Neo4j CQL has provided "ORDER BY" Clause in MATCH Command to sort the results returned by a MATCH query. We can sort rows either ascending order or descending order. By default, it sorts rows in ascending order. If we want to sort them in descending order, we need to use DESC clause ORDER BY <property-name-list> [DESC] <node-label-name>.<property1-name>, <node-label-name>.<property2-name>, .... <node-label-name>.<propertyn-name> Syntax Description NOTE - We should use comma(,) operator to separate the property names list. This example demonstrates how to use sort results in Ascending order by Employee name. Step 1 - Open Neo4j Data Browser Step 2 - Type the below command on Data Browser MATCH (emp:Employee) RETURN emp.empid,emp.name,emp.salary,emp.deptno Step 3 - Click on "Execute" button and observe the results. It returns total number of results available in the database: 4 records Step 4 - Type the below command on Data Browser MATCH (emp:Employee) RETURN emp.empid,emp.name,emp.salary,emp.deptno ORDER BY emp.name Step 5 - Click on "Execute" button and observe the results. If we observe the results, now records are sorted by Employee.name in ascending order. This example demonstrates how to use sort results in Descending order by Employee name. Step 1 - Open Neo4j Data Browser Step 2 - Type the below command on Data Browser MATCH (emp:Employee) RETURN emp.empid,emp.name,emp.salary,emp.deptno Step 3 - Click on "Execute" button and observe the results. It returns total number of results available in the database: 4 records Step 4 - Type the below command on Data Browser MATCH (emp:Employee) RETURN emp.empid,emp.name,emp.salary,emp.deptno ORDER BY emp.name DESC Step 5 - Click on "Execute" button and observe the results. If we observe the results, now records are sorted by Employee.name in Descending order. Print Add Notes Bookmark this page
[ { "code": null, "e": 2444, "s": 2339, "text": "Neo4j CQL has provided \"ORDER BY\" Clause in MATCH Command to sort the results returned by a MATCH query." }, { "code": null, "e": 2505, "s": 2444, "text": "We can sort rows either ascending order or descending order." }, { "code": null, "e": 2623, "s": 2505, "text": "By default, it sorts rows in ascending order. If we want to sort them in descending order, we need to use DESC clause" }, { "code": null, "e": 2663, "s": 2623, "text": "ORDER BY <property-name-list> [DESC]\t" }, { "code": null, "e": 2778, "s": 2663, "text": "<node-label-name>.<property1-name>,\n<node-label-name>.<property2-name>, \n.... \n<node-label-name>.<propertyn-name> " }, { "code": null, "e": 2797, "s": 2778, "text": "Syntax Description" }, { "code": null, "e": 2804, "s": 2797, "text": "NOTE -" }, { "code": null, "e": 2873, "s": 2804, "text": "We should use comma(,) operator to separate the property names list." }, { "code": null, "e": 2960, "s": 2873, "text": "This example demonstrates how to use sort results in Ascending order by Employee name." }, { "code": null, "e": 2993, "s": 2960, "text": "Step 1 - Open Neo4j Data Browser" }, { "code": null, "e": 3041, "s": 2993, "text": "Step 2 - Type the below command on Data Browser" }, { "code": null, "e": 3110, "s": 3041, "text": "MATCH (emp:Employee)\nRETURN emp.empid,emp.name,emp.salary,emp.deptno" }, { "code": null, "e": 3170, "s": 3110, "text": "Step 3 - Click on \"Execute\" button and observe the results." }, { "code": null, "e": 3242, "s": 3170, "text": "It returns total number of results available in the database: 4 records" }, { "code": null, "e": 3290, "s": 3242, "text": "Step 4 - Type the below command on Data Browser" }, { "code": null, "e": 3377, "s": 3290, "text": "MATCH (emp:Employee)\nRETURN emp.empid,emp.name,emp.salary,emp.deptno\nORDER BY emp.name" }, { "code": null, "e": 3437, "s": 3377, "text": "Step 5 - Click on \"Execute\" button and observe the results." }, { "code": null, "e": 3524, "s": 3437, "text": "If we observe the results, now records are sorted by Employee.name in ascending order." }, { "code": null, "e": 3612, "s": 3524, "text": "This example demonstrates how to use sort results in Descending order by Employee name." }, { "code": null, "e": 3645, "s": 3612, "text": "Step 1 - Open Neo4j Data Browser" }, { "code": null, "e": 3693, "s": 3645, "text": "Step 2 - Type the below command on Data Browser" }, { "code": null, "e": 3762, "s": 3693, "text": "MATCH (emp:Employee)\nRETURN emp.empid,emp.name,emp.salary,emp.deptno" }, { "code": null, "e": 3822, "s": 3762, "text": "Step 3 - Click on \"Execute\" button and observe the results." }, { "code": null, "e": 3894, "s": 3822, "text": "It returns total number of results available in the database: 4 records" }, { "code": null, "e": 3942, "s": 3894, "text": "Step 4 - Type the below command on Data Browser" }, { "code": null, "e": 4034, "s": 3942, "text": "MATCH (emp:Employee)\nRETURN emp.empid,emp.name,emp.salary,emp.deptno\nORDER BY emp.name DESC" }, { "code": null, "e": 4094, "s": 4034, "text": "Step 5 - Click on \"Execute\" button and observe the results." }, { "code": null, "e": 4182, "s": 4094, "text": "If we observe the results, now records are sorted by Employee.name in Descending order." }, { "code": null, "e": 4189, "s": 4182, "text": " Print" }, { "code": null, "e": 4200, "s": 4189, "text": " Add Notes" } ]
How to Create a Scatterplot with a Regression Line in R? - GeeksforGeeks
17 Feb, 2021 A scatter plot uses dots to represent values for two different numeric variables. Scatter plots are used to observe relationships between variables. A linear regression is a straight line representation of relationship between an independent and dependent variable. In this article, we will discuss how a scatter plot with linear regression can be drafted using R and its libraries. A scatter plot can be used to display all possible results and a linear regression plotted over it can be used to generalize common characteristics or to derive maximum points that follow up a result. Here we will first discuss the method of plotting a scatter plot and then draw a linear regression over it. Used dataset: Salary_Data.xls In R, function used to draw a scatter plot of two variables is plot() function which will return the scatter plot. Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes) Parameters:- x- is the data set whose values are the horizontal coordinates. y- is the data set whose values are the vertical coordinates. main- is the tile of the graph. xlab- is the label on the horizontal axis. ylab- is the label on the vertical axis. xlim- is the limits of the values of x used for plotting. ylim- is the limits of the values of y used for plotting. axes- indicates whether both axes should be drawn on the plot. Return:- A 2-Dimension scatter plot. Program: R library(readxl) # import dataSalary_Data <- read_excel("Salary_Data.xls") # plot scatter plotplot(Salary_Data$YearsExperience,Salary_Data$Salary, main='YearsExperience Vs Salary', xlab='YearsExperience', ylab='Salary') Output: A regression line is a straight line that describes how a response variable y(Dependent variable) changes as an explanatory variable x(Independent)changes. This is used to predict the value of y for a given value of x. For drawing regression line we need two functions: abline() function is used to add one or more straight lines through the current plot Syntax: abline(a=NULL, b=NULL, h=NULL, v=NULL, ...) Parameters:a, b: It specifies the intercept and the slope of the lineh: specifies y-value for horizontal line(s)v: specifies x-value(s) for vertical line(s) Returns: a straight line in the plot lm() function which stands for linear model,” function can be used to create a simple regression model. Syntax: lm(formula,data) Parameters: the formula- is a symbol presenting the relation between x and y. data- is the vector on which the formula will be applied. Returns: The relationship line of x and y. Program: R library(readxl) # import dataSalary_Data <- read_excel("Salary_Data.xls") # plot a scatter plotplot(Salary_Data$YearsExperience,Salary_Data$Salary, main='Regression for YearsExperience and Salary', xlab='YearsExperience',ylab='Salary') # plot a regression lineabline(lm(Salary~YearsExperience,data=Salary_Data),col='red') Output: Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? 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? R - if statement Replace Specific Characters in String in R Time Series Analysis in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n17 Feb, 2021" }, { "code": null, "e": 25626, "s": 25242, "text": "A scatter plot uses dots to represent values for two different numeric variables. Scatter plots are used to observe relationships between variables. A linear regression is a straight line representation of relationship between an independent and dependent variable. In this article, we will discuss how a scatter plot with linear regression can be drafted using R and its libraries. " }, { "code": null, "e": 25935, "s": 25626, "text": "A scatter plot can be used to display all possible results and a linear regression plotted over it can be used to generalize common characteristics or to derive maximum points that follow up a result. Here we will first discuss the method of plotting a scatter plot and then draw a linear regression over it." }, { "code": null, "e": 25965, "s": 25935, "text": "Used dataset: Salary_Data.xls" }, { "code": null, "e": 26080, "s": 25965, "text": "In R, function used to draw a scatter plot of two variables is plot() function which will return the scatter plot." }, { "code": null, "e": 26135, "s": 26080, "text": "Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)" }, { "code": null, "e": 26148, "s": 26135, "text": "Parameters:-" }, { "code": null, "e": 26212, "s": 26148, "text": "x- is the data set whose values are the horizontal coordinates." }, { "code": null, "e": 26274, "s": 26212, "text": "y- is the data set whose values are the vertical coordinates." }, { "code": null, "e": 26306, "s": 26274, "text": "main- is the tile of the graph." }, { "code": null, "e": 26349, "s": 26306, "text": "xlab- is the label on the horizontal axis." }, { "code": null, "e": 26390, "s": 26349, "text": "ylab- is the label on the vertical axis." }, { "code": null, "e": 26448, "s": 26390, "text": "xlim- is the limits of the values of x used for plotting." }, { "code": null, "e": 26506, "s": 26448, "text": "ylim- is the limits of the values of y used for plotting." }, { "code": null, "e": 26569, "s": 26506, "text": "axes- indicates whether both axes should be drawn on the plot." }, { "code": null, "e": 26578, "s": 26569, "text": "Return:-" }, { "code": null, "e": 26606, "s": 26578, "text": "A 2-Dimension scatter plot." }, { "code": null, "e": 26615, "s": 26606, "text": "Program:" }, { "code": null, "e": 26617, "s": 26615, "text": "R" }, { "code": "library(readxl) # import dataSalary_Data <- read_excel(\"Salary_Data.xls\") # plot scatter plotplot(Salary_Data$YearsExperience,Salary_Data$Salary, main='YearsExperience Vs Salary', xlab='YearsExperience', ylab='Salary')", "e": 26846, "s": 26617, "text": null }, { "code": null, "e": 26854, "s": 26846, "text": "Output:" }, { "code": null, "e": 27073, "s": 26854, "text": "A regression line is a straight line that describes how a response variable y(Dependent variable) changes as an explanatory variable x(Independent)changes. This is used to predict the value of y for a given value of x." }, { "code": null, "e": 27124, "s": 27073, "text": "For drawing regression line we need two functions:" }, { "code": null, "e": 27209, "s": 27124, "text": "abline() function is used to add one or more straight lines through the current plot" }, { "code": null, "e": 27261, "s": 27209, "text": "Syntax: abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)" }, { "code": null, "e": 27418, "s": 27261, "text": "Parameters:a, b: It specifies the intercept and the slope of the lineh: specifies y-value for horizontal line(s)v: specifies x-value(s) for vertical line(s)" }, { "code": null, "e": 27455, "s": 27418, "text": "Returns: a straight line in the plot" }, { "code": null, "e": 27559, "s": 27455, "text": "lm() function which stands for linear model,” function can be used to create a simple regression model." }, { "code": null, "e": 27584, "s": 27559, "text": "Syntax: lm(formula,data)" }, { "code": null, "e": 27596, "s": 27584, "text": "Parameters:" }, { "code": null, "e": 27662, "s": 27596, "text": "the formula- is a symbol presenting the relation between x and y." }, { "code": null, "e": 27720, "s": 27662, "text": "data- is the vector on which the formula will be applied." }, { "code": null, "e": 27729, "s": 27720, "text": "Returns:" }, { "code": null, "e": 27763, "s": 27729, "text": "The relationship line of x and y." }, { "code": null, "e": 27772, "s": 27763, "text": "Program:" }, { "code": null, "e": 27774, "s": 27772, "text": "R" }, { "code": "library(readxl) # import dataSalary_Data <- read_excel(\"Salary_Data.xls\") # plot a scatter plotplot(Salary_Data$YearsExperience,Salary_Data$Salary, main='Regression for YearsExperience and Salary', xlab='YearsExperience',ylab='Salary') # plot a regression lineabline(lm(Salary~YearsExperience,data=Salary_Data),col='red')", "e": 28107, "s": 27774, "text": null }, { "code": null, "e": 28115, "s": 28107, "text": "Output:" }, { "code": null, "e": 28122, "s": 28115, "text": "Picked" }, { "code": null, "e": 28131, "s": 28122, "text": "R-Charts" }, { "code": null, "e": 28140, "s": 28131, "text": "R-Graphs" }, { "code": null, "e": 28148, "s": 28140, "text": "R-plots" }, { "code": null, "e": 28159, "s": 28148, "text": "R Language" }, { "code": null, "e": 28257, "s": 28159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28266, "s": 28257, "text": "Comments" }, { "code": null, "e": 28279, "s": 28266, "text": "Old Comments" }, { "code": null, "e": 28331, "s": 28279, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28369, "s": 28331, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28404, "s": 28369, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28462, "s": 28404, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28511, "s": 28462, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28548, "s": 28511, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 28598, "s": 28548, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28615, "s": 28598, "text": "R - if statement" }, { "code": null, "e": 28658, "s": 28615, "text": "Replace Specific Characters in String in R" } ]
Selenium with C Sharp - How to perform Explicit Wait method?
We can perform explicit wait with Selenium webdriver in C#. This is done to achieve synchronization between our tests and the elements on the page. For implementation of explicit wait, we have to take the help of the WebDriverWait and ExpectedCondition classes. We shall create an object of the WebDriverWait class. The webdriver waits tillspecified wait time waiting for the expected condition for an element is satisfied. After the time has elapsed, an exception is raised by Selenium. The explicit waits are dynamic in nature which means if we have an explicit wait of five seconds and the expected condition is met at the third second, then the webdriver shall move to the next step immediately. It does not wait till the entirefive seconds. Some of the expected conditions are − UrlToBe UrlToBe VisibilityOfAllElementsLocatedBy VisibilityOfAllElementsLocatedBy UrlContains UrlContains AlertIsPresent AlertIsPresent AlertState AlertState ElementToBeSelected ElementToBeSelected ElementIsVisible ElementIsVisible ElementExists ElementExists ElementSelectionStateToBe ElementSelectionStateToBe ElementToBeClickable ElementToBeClickable InvisibilityOfElementWithText InvisibilityOfElementWithText InvisibilityOfElementLocated InvisibilityOfElementLocated TextToBePresentInElementLocated TextToBePresentInElementLocated TextToBePresentInElementValue TextToBePresentInElementValue TextToBePresentInElement TextToBePresentInElement StalenessOf StalenessOf TitleContains TitleContains FrameToBeAvailableAndSwitchToIt FrameToBeAvailableAndSwitchToIt PresenceOfAllElementsLocatedBy PresenceOfAllElementsLocatedBy TitleIs TitleIs WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); w.Until(ExpectedConditions.ElementIsVisible(By.TagName("h1"))); Let us try to wait for the text - Team @ Tutorials Point to be visible on the page − using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using System; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace NUnitTestProject2{ public class Tests{ String url = "https://www.tutorialspoint.com/about/about_careers.htm"; IWebDriver driver; [SetUp] public void Setup(){ //creating object of FirefoxDriver driver = new FirefoxDriver(""); } [Test] public void Test2(){ //URL launch driver.Navigate().GoToUrl(url); //identify element then click IWebElement t = driver.FindElement(By.XPath("//*[text()='Team']")); t.Click(); //expected condition of Element visibility WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); w.Until (ExpectedConditions.ElementIsVisible(By.TagName("h1"))); //identify element then obtain text IWebElement n = driver.FindElement(By.TagName("h1")); Console.WriteLine("Text is: " + n.Text); } [TearDown] public void close_Browser(){ driver.Quit(); } } }
[ { "code": null, "e": 1324, "s": 1062, "text": "We can perform explicit wait with Selenium webdriver in C#. This is done to achieve synchronization between our tests and the elements on the page. For implementation of explicit wait, we have to take the help of the WebDriverWait and ExpectedCondition classes." }, { "code": null, "e": 1486, "s": 1324, "text": "We shall create an object of the WebDriverWait class. The webdriver waits tillspecified wait time waiting for the expected condition for an element is satisfied." }, { "code": null, "e": 1550, "s": 1486, "text": "After the time has elapsed, an exception is raised by Selenium." }, { "code": null, "e": 1808, "s": 1550, "text": "The explicit waits are dynamic in nature which means if we have an explicit wait of five seconds and the expected condition is met at the third second, then the webdriver shall move to the next step immediately. It does not wait till the entirefive seconds." }, { "code": null, "e": 1846, "s": 1808, "text": "Some of the expected conditions are −" }, { "code": null, "e": 1854, "s": 1846, "text": "UrlToBe" }, { "code": null, "e": 1862, "s": 1854, "text": "UrlToBe" }, { "code": null, "e": 1895, "s": 1862, "text": "VisibilityOfAllElementsLocatedBy" }, { "code": null, "e": 1928, "s": 1895, "text": "VisibilityOfAllElementsLocatedBy" }, { "code": null, "e": 1940, "s": 1928, "text": "UrlContains" }, { "code": null, "e": 1952, "s": 1940, "text": "UrlContains" }, { "code": null, "e": 1967, "s": 1952, "text": "AlertIsPresent" }, { "code": null, "e": 1982, "s": 1967, "text": "AlertIsPresent" }, { "code": null, "e": 1993, "s": 1982, "text": "AlertState" }, { "code": null, "e": 2004, "s": 1993, "text": "AlertState" }, { "code": null, "e": 2024, "s": 2004, "text": "ElementToBeSelected" }, { "code": null, "e": 2044, "s": 2024, "text": "ElementToBeSelected" }, { "code": null, "e": 2061, "s": 2044, "text": "ElementIsVisible" }, { "code": null, "e": 2078, "s": 2061, "text": "ElementIsVisible" }, { "code": null, "e": 2092, "s": 2078, "text": "ElementExists" }, { "code": null, "e": 2106, "s": 2092, "text": "ElementExists" }, { "code": null, "e": 2132, "s": 2106, "text": "ElementSelectionStateToBe" }, { "code": null, "e": 2158, "s": 2132, "text": "ElementSelectionStateToBe" }, { "code": null, "e": 2179, "s": 2158, "text": "ElementToBeClickable" }, { "code": null, "e": 2200, "s": 2179, "text": "ElementToBeClickable" }, { "code": null, "e": 2230, "s": 2200, "text": "InvisibilityOfElementWithText" }, { "code": null, "e": 2260, "s": 2230, "text": "InvisibilityOfElementWithText" }, { "code": null, "e": 2289, "s": 2260, "text": "InvisibilityOfElementLocated" }, { "code": null, "e": 2318, "s": 2289, "text": "InvisibilityOfElementLocated" }, { "code": null, "e": 2350, "s": 2318, "text": "TextToBePresentInElementLocated" }, { "code": null, "e": 2382, "s": 2350, "text": "TextToBePresentInElementLocated" }, { "code": null, "e": 2412, "s": 2382, "text": "TextToBePresentInElementValue" }, { "code": null, "e": 2442, "s": 2412, "text": "TextToBePresentInElementValue" }, { "code": null, "e": 2467, "s": 2442, "text": "TextToBePresentInElement" }, { "code": null, "e": 2492, "s": 2467, "text": "TextToBePresentInElement" }, { "code": null, "e": 2504, "s": 2492, "text": "StalenessOf" }, { "code": null, "e": 2516, "s": 2504, "text": "StalenessOf" }, { "code": null, "e": 2530, "s": 2516, "text": "TitleContains" }, { "code": null, "e": 2544, "s": 2530, "text": "TitleContains" }, { "code": null, "e": 2576, "s": 2544, "text": "FrameToBeAvailableAndSwitchToIt" }, { "code": null, "e": 2608, "s": 2576, "text": "FrameToBeAvailableAndSwitchToIt" }, { "code": null, "e": 2639, "s": 2608, "text": "PresenceOfAllElementsLocatedBy" }, { "code": null, "e": 2670, "s": 2639, "text": "PresenceOfAllElementsLocatedBy" }, { "code": null, "e": 2678, "s": 2670, "text": "TitleIs" }, { "code": null, "e": 2686, "s": 2678, "text": "TitleIs" }, { "code": null, "e": 2821, "s": 2686, "text": "WebDriverWait w =\nnew WebDriverWait(driver, TimeSpan.FromSeconds(20));\nw.Until(ExpectedConditions.ElementIsVisible(By.TagName(\"h1\")));" }, { "code": null, "e": 2906, "s": 2821, "text": "Let us try to wait for the text - Team @ Tutorials Point to be visible on the page −" }, { "code": null, "e": 4053, "s": 2906, "text": "using NUnit.Framework;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Firefox;\nusing System;\nusing OpenQA.Selenium;\nusing OpenQA.Selenium.Support.UI;\nnamespace NUnitTestProject2{\n public class Tests{\n String url = \"https://www.tutorialspoint.com/about/about_careers.htm\";\n IWebDriver driver;\n [SetUp]\n public void Setup(){\n //creating object of FirefoxDriver\n driver = new FirefoxDriver(\"\");\n }\n [Test]\n public void Test2(){\n //URL launch\n driver.Navigate().GoToUrl(url);\n //identify element then click\n IWebElement t = driver.FindElement(By.XPath(\"//*[text()='Team']\"));\n t.Click();\n //expected condition of Element visibility\n WebDriverWait w = new WebDriverWait(driver, TimeSpan.FromSeconds(20));\n w.Until\n (ExpectedConditions.ElementIsVisible(By.TagName(\"h1\")));\n //identify element then obtain text\n IWebElement n = driver.FindElement(By.TagName(\"h1\"));\n Console.WriteLine(\"Text is: \" + n.Text);\n }\n [TearDown]\n public void close_Browser(){\n driver.Quit();\n }\n }\n}" } ]
egrep command in Linux with examples - GeeksforGeeks
15 May, 2019 egrep is a pattern searching command which belongs to the family of grep functions. It works the same way as grep -E does. It treats the pattern as an extended regular expression and prints out the lines that match the pattern. If there are several files with the matching pattern, it also displays the file names for each line. Syntax: egrep [ options ] 'PATTERN' files Example: Note: The egrep command used mainly due to the fact that it is faster than the grep command. The egrep command treats the meta-characters as they are and do not require to be escaped as is the case with grep. This allows reducing the overhead of replacing these characters while pattern matching making egrep faster than grep or fgrep. Options: Most of the options for this command are same as grep. -c: Used to counts and prints the number of lines that matched the pattern and not the lines. -v: It prints the lines that does not match with the pattern. -i: Ignore the case of the pattern while matching. -l: Prints only the names of the files that matched. It does not mention the matching line numbers or any other information. -L: Prints only the names of the files that did not have the pattern. Opposite of -l flag. -e: Allows to use a ‘-‘ sign in the beginning of the pattern. If not mentioned the shell tries to execute the pattern as an option and returns an error. -w: Prints only those lines that contain the whole words. Word-constituent characters are letters, digits and underscore. The matching substring must be seperated by non-word constituent characters. -x: Prints only those lines that matches an entire line of the file. -m NUMBER: Continue to search for matches till the count reaches NUMBER mentioned as argument. -o: Prints only the matched parts of the line and not the entire line for each match. -n: Prints each matched line along with the respective line numbers. For multiple files, prints the file names along with line numbers. -r: Recursively search for the pattern in all the files of the directory. The last argument is the directory to check. ‘.’ (dot) represents the current directory. linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples echo command in Linux with Examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization Tail command in Linux with examples Compiling with g++ ps command in Linux with Examples
[ { "code": null, "e": 24006, "s": 23978, "text": "\n15 May, 2019" }, { "code": null, "e": 24335, "s": 24006, "text": "egrep is a pattern searching command which belongs to the family of grep functions. It works the same way as grep -E does. It treats the pattern as an extended regular expression and prints out the lines that match the pattern. If there are several files with the matching pattern, it also displays the file names for each line." }, { "code": null, "e": 24343, "s": 24335, "text": "Syntax:" }, { "code": null, "e": 24379, "s": 24343, "text": "egrep [ options ] 'PATTERN' files \n" }, { "code": null, "e": 24388, "s": 24379, "text": "Example:" }, { "code": null, "e": 24724, "s": 24388, "text": "Note: The egrep command used mainly due to the fact that it is faster than the grep command. The egrep command treats the meta-characters as they are and do not require to be escaped as is the case with grep. This allows reducing the overhead of replacing these characters while pattern matching making egrep faster than grep or fgrep." }, { "code": null, "e": 24788, "s": 24724, "text": "Options: Most of the options for this command are same as grep." }, { "code": null, "e": 24882, "s": 24788, "text": "-c: Used to counts and prints the number of lines that matched the pattern and not the lines." }, { "code": null, "e": 24944, "s": 24882, "text": "-v: It prints the lines that does not match with the pattern." }, { "code": null, "e": 24995, "s": 24944, "text": "-i: Ignore the case of the pattern while matching." }, { "code": null, "e": 25120, "s": 24995, "text": "-l: Prints only the names of the files that matched. It does not mention the matching line numbers or any other information." }, { "code": null, "e": 25211, "s": 25120, "text": "-L: Prints only the names of the files that did not have the pattern. Opposite of -l flag." }, { "code": null, "e": 25364, "s": 25211, "text": "-e: Allows to use a ‘-‘ sign in the beginning of the pattern. If not mentioned the shell tries to execute the pattern as an option and returns an error." }, { "code": null, "e": 25563, "s": 25364, "text": "-w: Prints only those lines that contain the whole words. Word-constituent characters are letters, digits and underscore. The matching substring must be seperated by non-word constituent characters." }, { "code": null, "e": 25632, "s": 25563, "text": "-x: Prints only those lines that matches an entire line of the file." }, { "code": null, "e": 25727, "s": 25632, "text": "-m NUMBER: Continue to search for matches till the count reaches NUMBER mentioned as argument." }, { "code": null, "e": 25813, "s": 25727, "text": "-o: Prints only the matched parts of the line and not the entire line for each match." }, { "code": null, "e": 25949, "s": 25813, "text": "-n: Prints each matched line along with the respective line numbers. For multiple files, prints the file names along with line numbers." }, { "code": null, "e": 26112, "s": 25949, "text": "-r: Recursively search for the pattern in all the files of the directory. The last argument is the directory to check. ‘.’ (dot) represents the current directory." }, { "code": null, "e": 26126, "s": 26112, "text": "linux-command" }, { "code": null, "e": 26146, "s": 26126, "text": "Linux-misc-commands" }, { "code": null, "e": 26153, "s": 26146, "text": "Picked" }, { "code": null, "e": 26164, "s": 26153, "text": "Linux-Unix" }, { "code": null, "e": 26262, "s": 26164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26271, "s": 26262, "text": "Comments" }, { "code": null, "e": 26284, "s": 26271, "text": "Old Comments" }, { "code": null, "e": 26319, "s": 26284, "text": "tar command in Linux with examples" }, { "code": null, "e": 26357, "s": 26319, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26395, "s": 26357, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 26430, "s": 26395, "text": "Cat command in Linux with examples" }, { "code": null, "e": 26466, "s": 26430, "text": "echo command in Linux with Examples" }, { "code": null, "e": 26503, "s": 26466, "text": "touch command in Linux with Examples" }, { "code": null, "e": 26547, "s": 26503, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 26583, "s": 26547, "text": "Tail command in Linux with examples" }, { "code": null, "e": 26602, "s": 26583, "text": "Compiling with g++" } ]
AWS Lambda – Additional Example
Till now, we have seen working of AWS Lambda with AWS services. Based on that knowledge, let us create a simple user registration form and post the data using API gateway to AWS Lambda. AWS Lambda will get the data from the event or theAPI gateway trigger and will add those details to DynamoDB table. Let us consider an example and perform the following functionalities on it − Create DynamoDB Table Create DynamoDB Table Create Form for User Registration Create Form for User Registration Create AWS Lambda and API gateway to send message to Phone using AWS SNS service Create AWS Lambda and API gateway to send message to Phone using AWS SNS service Create AWS Lambda and API gateway to POST form data and insert in DynamoDb table Create AWS Lambda and API gateway to POST form data and insert in DynamoDb table Create AWS Lambda and API gateway to read data from Dynamodb table Create AWS Lambda and API gateway to read data from Dynamodb table Final Working of the User Registration Form Final Working of the User Registration Form The data entered will be stored in DynamodDB table. We will use API gateway to share data entered with AWS Lambda and later AWS Lambda will add the details in DynamoDB. You can use the following details to create DynamodDB table in AWS console. First, go to AWS Service and click DynamoDB. Click Table to create the table as shown below − You can use the ARN to create policy for the DynamoDB to be used with AWS Lambda. Go to IAM and select Policies. Click Create policy, choose service as DynamodDB as shown below − Click All DynamoDB actions as shown above. Choose resource and enter the ARN for table as shown below − Now, click Add as shown below. If you click Review policy button at the end of the screen, you can see the following window − Enter name of the policy and click Create policy button at the end of the page. Now, we need to create role to be used with Lambda. We need permissionsforDynamoDB, APIGateway and Lambda. Go to AWS services and select IAM. Select Roles from left side and add the required roles. Enter the role name and click Create role. The role created is roleforlambdaexample. Here is the display of the user registration form to enter and to read the data from the dynamodb table. If you see the user registration form, there is a button validate phone. User is suppose to enter phone number and click on validate phone button to validate the phone number. For this purpose − When a user clicks this button, the API gateway post method which contains the phone details is called and internally AWS Lambda is triggered. Then, AWS Lambda sendsOTP to the phone number entered using AWS SNS service. The user receives the OTP and has to enter thisOTP number. The textbox to enter OTP will appear when the phone number is entered and validate phone button is clicked. The OTP received from AWS Lambda and the OTP entered by the user has to match, to allow the user to submit the user registration form. A simple block diagram that explains the working of phone validation is shown here − The AWS Lambda function created is as shown here − The corresponding AWS Lambda code is as given below − const aws = require("aws-sdk"); const sns = new aws.SNS({ region:'us-east-1' }); exports.handler = function(event, context, callback) { let phoneno = event.mphone; let otp = Math.floor(100000 + Math.random() * 900000); let snsmessage = "Your otp is : "+otp; sns.publish({ Message: snsmessage, PhoneNumber: "+91"+phoneno }, function (err, data) { if (err) { console.log(err); callback(err, null); } else { console.log(data); callback(null, otp); } }); }; Note that we are using SNS service to send the OTP code. This code is used to validate the mobile number entered by the user in the user registration form. The API gateway created for above phone validation is as follows − The Lambda function given is phonevalidationexample. We are taking the mobile phone details here to be used inside AWS Lambda. Then, AWS Lambda will send the OTP code to the given mobile number. For user registration form, all the fields are mandatory. There is anAJAX call made wherein the data entered in the form is posted to the API Gateway URL. A simple block diagram which explains the working of the submit button is shown here − Once the form is filled, the submit button will call the API gateway which will trigger AWS Lambda. AWS Lambda will get the details of the form from event or theAPI Gateway and the data will be inserted in the DynamodDB table. Let us understand the creation of API Gateway and AWS Lambda. First, go to AWS services and click Lambda. The Lambda function created is as shown here − Now, to create an API gateway, go to AWS service and select API Gateway. Click on Create API button shown below. Enter the API name and click on Create API button to add the API. Now, an API is created called as registeruser. Select the API and click Actions dropdown to create Resource. Click Create Resource. Now, let us add the POST method. For this, click on resources created on left side and from Actions dropdown select create method. This will display dropdown as shown below − Select the POST method and add the Lambda function that we created above. Click Save button to add the method. To send the form details to Lambda function lambdaexample we need to add the Integration Request as shown below − To post the form details, you will have to click Integration Request. It will display below details. Click Body Mapping Templates to add the form fields to be posted. Next, click Add mapping template and enter the content type. Here, we have added application/json as the content type. Click it and here you need to enter the field in json format as shown below − Now, click the Save button and deploy the API as shown below − Here is the API created for POST which will use inside our .html file. Please note we need to Enable CORS for the resource created. Will use the api gateway url to make ajax call so the CORS has to enabled. Select the Methods on which you want to enable the CORS. Click on Enable CORS and replace existing CORS headers. It displays the confirmation screen as follows − Click Yes, replace existing values to enable CORS. The AWS Lambda code forPOST API Gateway is as shown here − const aws = require("aws-sdk"); const docClient = new aws.DynamoDB.DocumentClient({ region:'us-east-1' }); exports.handler = function(event, context, callback) { console.log(event); console.log("Entering Data"); var data = { TableName : "registeruser", Item : { first_name:event.fname, last_name:event.lname, emailid:event.emailid, mobile_no : event.mphone, otp:event.otp, username:event.uname, password:event.passwd, confirm_password:event.cpasswd } } docClient.put(data, function(err, value) { if (err) { console.log("Error"); callback(err, null); } else { console.log("data added successfully"); callback(null, value); } }); } The event parameter in AWS Lambda handler will have all the details which are added earlier in POST integration request. The details from event are added to the DynamodDB table as shown in the code. Now, we need to get the service details from AWS-SDK as shown below − const aws = require("aws-sdk"); const docClient = new aws.DynamoDB.DocumentClient({ region:'us-east-1' }); var data = { TableName : "registeruser", Item : { first_name:event.fname, last_name:event.lname, emailid:event.emailid, mobile_no : event.mphone, otp:event.otp, username:event.uname, password:event.passwd, confirm_password:event.cpasswd } } docClient.put(data, function(err, value) { if (err) { console.log("Error"); callback(err, null); } else { console.log("data added successfully"); callback(null, value); } }); Now, we will create AWS Lambda function to read data from DynamoDB table. We will trigger APIGateway to the AWS Lambda function which will send data to the html form. The AWS Lambda function created is as shown below − The corresponding AWS Lambda code is as follows − const aws = require("aws-sdk"); const docClient = new aws.DynamoDB.DocumentClient({ region:'us-east-1' }); exports.handler = function(event, context, callback) { var readdata = { TableName : "registeruser", Limit : 10 } docClient.scan(readdata, function(err, data) { if (err) { console.log("Error"); callback(err, null); } else { console.log("Data is " + data); callback(null, data); } }); } Here the data is read from the DynamoDB table and given to the callback. Now, we will create APIGateway and add AWS Lambda function as the trigger. We will add get method to the API created earlier. Lambda function added is lambdareaddataexample. Click Save to save the method and deploy the api. The final display of the form is as shown below − Now, enter the details as shown above. Note that the submit button is disabled. It will be enabled only when all the details are entered as shown − Now, enter the mobile number and click validate phone button. It will display the alert message saying “OTP is send to the mobile, please enter the OTP to continue”. OTP sent to the mobile number is as follows − Enter the OTP and remaining details and submit the form. The data in DynamoDB registeruser table after submit is as shown here − The code details are as given below − Example1.html <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="formdet.js"></script> <style> input[type=text], input[type=password],button { width: 100%; padding: 5px 5px; margin: 5px 0; box-sizing: border-box; } #maincontainer { width: 80%; margin: auto; padding: 10px; } div#userregistration { width: 60%; float: left; } div#userdisplay { margin-left: 60%; } </style> </head> <body> <div id="maincontainer"> <div id="userregistration"> <h1>User Registration Form</h1> <table border="0"> <tr> <td><b>First Name<span style="color:red;">*</span> : </b></td> <td><input type="text" value="" name="fname" id="fname" /></td> <td id="tdfname" style="display:none;"><span style="color:red;">Enter First Name</span></td> </tr> <tr> <td><b>Last Name<span style="color:red;">*</span> : </b></td> <td><input type="text" value="" name="lname" id="lname" /></td> <td id="tdlname" style="display:none;"><span style="color:red;">Enter Last Name</span></td> </tr> <tr> <td><b>Email Id<span style="color:red;">*</span> : </b></td> <td><input type="text" value="" name="emailid" id="emailid" /></td> <td id="tdemailid" style="display:none;"><span style="color:red;">Enter Email</span></td> </tr> <tr> <td><b>Mobile No<span style="color:red;">*</span> : </b></td> <td><input type="text" name="mphone" id="mphone"/></td> <td id="tdmphone" style="display:none;"><span style="color:red;">Enter Mobile Number</span></td> </tr> <tr> <td></td> <td><button id="validatephone">validate phone</button></td> <td></td> </tr> <tr id="otpdiv" style="display:none;"> <td><b>Enter OTP<span style="color:red;">*</span>:</b></td> <td><input type="text" value="" name="otp" id="otp" /></td> <td id="tdotp" style="display:none;"><span style="color:red;">Enter OTP</span></td> </tr> <tr> <td><b>Username<span style="color:red;">*</span>: </b></td> <td><input type="text" value="" name="uname" id="uname"/></td> <td id="tduname" style="display:none;"><span style="color:red;">Enter Username</span></td> </tr> <tr><td><b>Password<span style="color:red;">*</span> :</b></td> <td><input type="password" value="" name="passwd" id="passwd"/></td> <td id="tdpasswd" style="display:none;"><span style="color:red;">Enter Password</span></td> </tr> <tr><td><b>Confirm Password<span style="color:red;">*</span> :</b></td> <td><input type="password" value="" name="cpasswd" id="cpasswd"/></td> <td id="tdcpasswd" style="display:none;"><span style="color:red;">Enter Confirm Password</span></td> </tr> <tr> <td></td> <td><button name="submit" id="submit" style="display:;" disabled="true">Submit</button></td> <td></td> </tr> </table> </div> <div id="userdisplay"> <h1>User Display</h1> <table id="displaydetails" style="display:block;width:80%;padding:5px;margin:5px; border: 1px solid black;"> <tr> <td></td> <td>FirstName</td> <td>LastName</td> <td>Mobile No</td> <td>EmailID</td> </tr> </table> </div> </div> </body> </html> formdet.js function validateform() { var sError=""; if ($("#fname").val() === "") { $("#tdfname").css("display",""); sError++; } if ($("#lname").val() === "") { $("#tdlname").css("display",""); sError++; } if ($("#emailid").val() === "") { $("#tdemailid").css("display",""); sError++; } if ($("#mphone").val() === "") { $("#tdmphone").css("display",""); sError++; } if ($("#otp").val() === "") { $("#tdotp").css("display",""); sError++; } if ($("#uname").val() === "") { $("#tduname").css("display",""); sError++; } if ($("#passwd").val() === "") { $("#tdpasswd").css("display",""); sError++; } if ($("#cpasswd").val() === "") { $("#tdcpasswd").css("display",""); sError++; } if (sError === "") { return true; } else { return false; } } $("#fname").change(function() { if ($("#fname").val() !== "") { $("#tdfname").css("display","none"); } else { $("#tdfname").css("display",""); } }); $("#lname").change(function() { if ($("#lname").val() !== "") { $("#tdlname").css("display","none"); } else { $("#tdlname").css("display",""); } }); $("#emailid").change(function() { if ($("#emailid").val() !== "") { $("#tdemailid").css("display","none"); } else { $("#tdemailid").css("display",""); } }); $("#mphone").change(function() { if ($("#mphone").val() !== "") { $("#tdmphone").css("display","none"); } else { $("#tdmphone").css("display",""); } }); $("#otp").change(function() { if ($("#otp").val() !== "") { $("#tdotp").css("display","none"); } else { $("#tdotp").css("display",""); } }); $("#uname").change(function() { if ($("#uname").val() !== "") { $("#tduname").css("display","none"); } else { $("#tduname").css("display",""); } }); $("#passwd").change(function() { if ($("#passwd").val() !== "") { $("#tdpasswd").css("display","none"); } else { $("#tdpasswd").css("display",""); } }); $("#cpasswd").change(function() { if ($("#cpasswd").val() !== "") { $("#tdcpasswd").css("display","none"); } else { $("#tdcpasswd").css("display",""); } }); var posturl = "https://4rvwimysc1.execute-api.us-east-1.amazonaws.com/prod/adduser"; var phonevalidationurl = "https://wnvt01y6nc.execute-api.us-east-1.amazonaws.com/prod/validate"; var otpsend = ""; function getdata() { var a = 0; $.ajax({ type:'GET', url:posturl, success: function(data) { $("#displaydetails").html(''); $("#displaydetails").css("display", ""); console.log(data); $("#displaydetails").append('<tr style="padding:5px;margin:5px;background-color:gray;"><td>Name</td><td>Mobile No</td><td>EmailID</td></tr>'); data.Items.forEach(function(registeruser) { var clr = (a%2 === 0) ? "#eee": "white"; a++; $("#displaydetails").append('<tr style="padding:5px;margin:5px;background-color:'+clr+'"><td>'+registeruser.first_name+'-'+registeruser.last_name+'</td><td>'+registeruser.mobile_no+'</td><td>'+registeruser.emailid+'</td></tr>'); }); }, error: function(err) { console.log(err); } }); } $(document).ready(function() { $("#otp").on("change", function() { var otpentered = $("#otp").val(); if (otpsend == otpentered) { document.getElementById("submit").disabled = false; } else { alert("OTP is not valid.Please enter the valid one or validate phone again to continue!"); document.getElementById("submit").disabled = true; } }); $("#validatephone").on("click", function() { $.ajax({ type:'POST', url:phonevalidationurl, data:JSON.stringify({ "mphone":$("#mphone").val() }), success: function(data) { $("#otpdiv").css("display", ""); alert("OTP is send to the mobile, please enter to continue"); console.log(data); otpsend = data; }, error : function(err) { $("#otpdiv").css("display", "none"); alert("Invalid mobile no."); } }); }); $("#submit").on("click", function() { if (validateform()) { $.ajax({ type:'POST', url:posturl, data:JSON.stringify({ "fname": $("#fname").val(), "lname": $("#lname").val(), "emailid":$("#emailid").val(), "mphone":$("#mphone").val(), "otp":$("#otp").val(), "uname":$("#uname").val(), "passwd":$("#passwd").val(), "cpasswd":$("#cpasswd").val() }), success: function(data) { alert("Data added successfully"); console.log(data); getdata(); } }); } }); getdata(); }); Till now, we have done AJAX call to the API created and posted the data as shown above. The AJAX call to add the data to the table is as follows − var posturl = "https://4rvwimysc1.execute-api.us-east-1.amazonaws.com/prod/adduser"; $(document).ready(function() { $("#submit").on("click", function() { if (validateform()) { $.ajax({ type:'POST', url:posturl, data:JSON.stringify({ "fname": $("#fname").val(), "lname": $("#lname").val(), "emailid":$("#emailid").val(), "mphone":$("#mphone").val(), "otp":$("#otp").val(), "uname":$("#uname").val(), "passwd":$("#passwd").val(), "cpasswd":$("#cpasswd").val() }), success: function(data) { alert("Data added successfully"); console.log(data); getdata(); } }); } }); }); Note that to read the data, a function is called, whose code is given below − function getdata() { var a = 0; $.ajax({ type:'GET', url:posturl, success: function(data) { $("#displaydetails").html(''); $("#displaydetails").css("display", ""); console.log(data); $("#displaydetails").append('<tr style="padding:5px;margin:5px;background-color:gray;"><td>Name</td><td>Mobile No</td><td>EmailID</td></tr>'); data.Items.forEach(function(registeruser) { var clr = (a%2 === 0) ? "#eee": "white"; a++; $("#displaydetails").append('<tr style="padding:5px;margin:5px;background-color:'+clr+'"><td>'+registeruser.first_name+'-'+registeruser.last_name+'</td><td>'+registeruser.mobile_no+'</td><td>'+registeruser.emailid+'</td></tr>'); }); }, error: function(err) { console.log(err); } }); } When you click mobile number validate button, the following code is called and sends the mobile number − var phonevalidationurl = "https://wnvt01y6nc.execute-api.us-east-1.amazonaws.com/prod/validate"; var otpsend = ""; $("#validatephone").on("click", function() { $.ajax({ type:'POST', url:phonevalidationurl, data:JSON.stringify({ "mphone":$("#mphone").val() }), success: function(data) { $("#otpdiv").css("display", ""); alert("OTP is send to the mobile, please enter the OTP to continue"); console.log(data); otpsend = data; }, error : function(err) { $("#otpdiv").css("display", "none"); alert("Invalid mobile no."); } }); }); // Validate otp $("#otp").on("change", function() { var otpentered = $("#otp").val(); if (otpsend == otpentered) { document.getElementById("submit").disabled = false; } else { alert("OTP is not valid.Please enter the valid one or validate phone again to continue!"); document.getElementById("submit").disabled = true; } } 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2406, "text": "Till now, we have seen working of AWS Lambda with AWS services. Based on that knowledge, let us create a simple user registration form and post the data using API gateway to AWS Lambda. AWS Lambda will get the data from the event or theAPI gateway trigger and will add those details to DynamoDB table." }, { "code": null, "e": 2785, "s": 2708, "text": "Let us consider an example and perform the following functionalities on it −" }, { "code": null, "e": 2807, "s": 2785, "text": "Create DynamoDB Table" }, { "code": null, "e": 2829, "s": 2807, "text": "Create DynamoDB Table" }, { "code": null, "e": 2863, "s": 2829, "text": "Create Form for User Registration" }, { "code": null, "e": 2897, "s": 2863, "text": "Create Form for User Registration" }, { "code": null, "e": 2978, "s": 2897, "text": "Create AWS Lambda and API gateway to send message to Phone using AWS SNS service" }, { "code": null, "e": 3059, "s": 2978, "text": "Create AWS Lambda and API gateway to send message to Phone using AWS SNS service" }, { "code": null, "e": 3140, "s": 3059, "text": "Create AWS Lambda and API gateway to POST form data and insert in DynamoDb table" }, { "code": null, "e": 3221, "s": 3140, "text": "Create AWS Lambda and API gateway to POST form data and insert in DynamoDb table" }, { "code": null, "e": 3288, "s": 3221, "text": "Create AWS Lambda and API gateway to read data from Dynamodb table" }, { "code": null, "e": 3355, "s": 3288, "text": "Create AWS Lambda and API gateway to read data from Dynamodb table" }, { "code": null, "e": 3399, "s": 3355, "text": "Final Working of the User Registration Form" }, { "code": null, "e": 3443, "s": 3399, "text": "Final Working of the User Registration Form" }, { "code": null, "e": 3612, "s": 3443, "text": "The data entered will be stored in DynamodDB table. We will use API gateway to share data entered with AWS Lambda and later AWS Lambda will add the details in DynamoDB." }, { "code": null, "e": 3782, "s": 3612, "text": "You can use the following details to create DynamodDB table in AWS console. First, go to AWS Service and click DynamoDB. Click Table to create the table as shown below −" }, { "code": null, "e": 3864, "s": 3782, "text": "You can use the ARN to create policy for the DynamoDB to be used with AWS Lambda." }, { "code": null, "e": 3961, "s": 3864, "text": "Go to IAM and select Policies. Click Create policy, choose service as DynamodDB as shown below −" }, { "code": null, "e": 4065, "s": 3961, "text": "Click All DynamoDB actions as shown above. Choose resource and enter the ARN for table as shown below −" }, { "code": null, "e": 4096, "s": 4065, "text": "Now, click Add as shown below." }, { "code": null, "e": 4191, "s": 4096, "text": "If you click Review policy button at the end of the screen, you can see the following window −" }, { "code": null, "e": 4378, "s": 4191, "text": "Enter name of the policy and click Create policy button at the end of the page. Now, we need to create role to be used with Lambda. We need permissionsforDynamoDB, APIGateway and Lambda." }, { "code": null, "e": 4469, "s": 4378, "text": "Go to AWS services and select IAM. Select Roles from left side and add the required roles." }, { "code": null, "e": 4554, "s": 4469, "text": "Enter the role name and click Create role. The role created is roleforlambdaexample." }, { "code": null, "e": 4659, "s": 4554, "text": "Here is the display of the user registration form to enter and to read the data from the dynamodb table." }, { "code": null, "e": 4835, "s": 4659, "text": "If you see the user registration form, there is a button validate phone. User is suppose to enter phone number and click on validate phone button to validate the phone number." }, { "code": null, "e": 4854, "s": 4835, "text": "For this purpose −" }, { "code": null, "e": 4997, "s": 4854, "text": "When a user clicks this button, the API gateway post method which contains the phone details is called and internally AWS Lambda is triggered." }, { "code": null, "e": 5074, "s": 4997, "text": "Then, AWS Lambda sendsOTP to the phone number entered using AWS SNS service." }, { "code": null, "e": 5133, "s": 5074, "text": "The user receives the OTP and has to enter thisOTP number." }, { "code": null, "e": 5241, "s": 5133, "text": "The textbox to enter OTP will appear when the phone number is entered and validate phone button is clicked." }, { "code": null, "e": 5376, "s": 5241, "text": "The OTP received from AWS Lambda and the OTP entered by the user has to match, to allow the user to submit the user registration form." }, { "code": null, "e": 5461, "s": 5376, "text": "A simple block diagram that explains the working of phone validation is shown here −" }, { "code": null, "e": 5512, "s": 5461, "text": "The AWS Lambda function created is as shown here −" }, { "code": null, "e": 5566, "s": 5512, "text": "The corresponding AWS Lambda code is as given below −" }, { "code": null, "e": 6109, "s": 5566, "text": "const aws = require(\"aws-sdk\");\nconst sns = new aws.SNS({\n region:'us-east-1'\n});\nexports.handler = function(event, context, callback) {\n let phoneno = event.mphone;\n let otp = Math.floor(100000 + Math.random() * 900000);\n let snsmessage = \"Your otp is : \"+otp;\n sns.publish({\n Message: snsmessage,\n PhoneNumber: \"+91\"+phoneno\n }, function (err, data) {\n if (err) {\n console.log(err);\n callback(err, null);\n } else {\n console.log(data);\n callback(null, otp);\n }\t\n });\n};" }, { "code": null, "e": 6332, "s": 6109, "text": "Note that we are using SNS service to send the OTP code. This code is used to validate the mobile number entered by the user in the user registration form. The API gateway created for above phone validation is as follows −" }, { "code": null, "e": 6527, "s": 6332, "text": "The Lambda function given is phonevalidationexample. We are taking the mobile phone details here to be used inside AWS Lambda. Then, AWS Lambda will send the OTP code to the given mobile number." }, { "code": null, "e": 6682, "s": 6527, "text": "For user registration form, all the fields are mandatory. There is anAJAX call made wherein the data entered in the form is posted to the API Gateway URL." }, { "code": null, "e": 6769, "s": 6682, "text": "A simple block diagram which explains the working of the submit button is shown here −" }, { "code": null, "e": 6996, "s": 6769, "text": "Once the form is filled, the submit button will call the API gateway which will trigger AWS Lambda. AWS Lambda will get the details of the form from event or theAPI Gateway and the data will be inserted in the DynamodDB table." }, { "code": null, "e": 7058, "s": 6996, "text": "Let us understand the creation of API Gateway and AWS Lambda." }, { "code": null, "e": 7149, "s": 7058, "text": "First, go to AWS services and click Lambda. The Lambda function created is as shown here −" }, { "code": null, "e": 7262, "s": 7149, "text": "Now, to create an API gateway, go to AWS service and select API Gateway. Click on Create API button shown below." }, { "code": null, "e": 7328, "s": 7262, "text": "Enter the API name and click on Create API button to add the API." }, { "code": null, "e": 7437, "s": 7328, "text": "Now, an API is created called as registeruser. Select the API and click Actions dropdown to create Resource." }, { "code": null, "e": 7635, "s": 7437, "text": "Click Create Resource. Now, let us add the POST method. For this, click on resources created on left side and from Actions dropdown select create method. This will display dropdown as shown below −" }, { "code": null, "e": 7709, "s": 7635, "text": "Select the POST method and add the Lambda function that we created above." }, { "code": null, "e": 7860, "s": 7709, "text": "Click Save button to add the method. To send the form details to Lambda function lambdaexample we need to add the Integration Request as shown below −" }, { "code": null, "e": 7961, "s": 7860, "text": "To post the form details, you will have to click Integration Request. It will display below details." }, { "code": null, "e": 8027, "s": 7961, "text": "Click Body Mapping Templates to add the form fields to be posted." }, { "code": null, "e": 8224, "s": 8027, "text": "Next, click Add mapping template and enter the content type. Here, we have added application/json as the content type. Click it and here you need to enter the field in json format as shown below −" }, { "code": null, "e": 8287, "s": 8224, "text": "Now, click the Save button and deploy the API as shown below −" }, { "code": null, "e": 8494, "s": 8287, "text": "Here is the API created for POST which will use inside our .html file. Please note we need to Enable CORS for the resource created. Will use the api gateway url to make ajax call so the CORS has to enabled." }, { "code": null, "e": 8607, "s": 8494, "text": "Select the Methods on which you want to enable the CORS. Click on Enable CORS and replace existing CORS headers." }, { "code": null, "e": 8656, "s": 8607, "text": "It displays the confirmation screen as follows −" }, { "code": null, "e": 8707, "s": 8656, "text": "Click Yes, replace existing values to enable CORS." }, { "code": null, "e": 8766, "s": 8707, "text": "The AWS Lambda code forPOST API Gateway is as shown here −" }, { "code": null, "e": 9565, "s": 8766, "text": "const aws = require(\"aws-sdk\");\nconst docClient = new aws.DynamoDB.DocumentClient({\n region:'us-east-1'\n});\nexports.handler = function(event, context, callback) {\n console.log(event);\n console.log(\"Entering Data\");\n var data = {\n TableName : \"registeruser\",\n Item : {\n first_name:event.fname,\n last_name:event.lname,\n emailid:event.emailid,\t \n mobile_no : event.mphone,\n otp:event.otp,\n username:event.uname,\n password:event.passwd,\n confirm_password:event.cpasswd\n }\n }\n docClient.put(data, function(err, value) {\n if (err) {\n console.log(\"Error\");\n callback(err, null);\n } else {\n console.log(\"data added successfully\");\n callback(null, value);\n }\n });\n}" }, { "code": null, "e": 9764, "s": 9565, "text": "The event parameter in AWS Lambda handler will have all the details which are added earlier in POST integration request. The details from event are added to the DynamodDB table as shown in the code." }, { "code": null, "e": 9834, "s": 9764, "text": "Now, we need to get the service details from AWS-SDK as shown below −" }, { "code": null, "e": 10448, "s": 9834, "text": "const aws = require(\"aws-sdk\");\nconst docClient = new aws.DynamoDB.DocumentClient({\n region:'us-east-1'\n});\nvar data = {\n TableName : \"registeruser\",\n Item : {\n first_name:event.fname,\n last_name:event.lname,\t\n emailid:event.emailid,\n mobile_no : event.mphone,\n otp:event.otp,\n username:event.uname,\n password:event.passwd,\n confirm_password:event.cpasswd\n }\n}\ndocClient.put(data, function(err, value) {\n if (err) {\n\t\tconsole.log(\"Error\");\n callback(err, null);\n } else {\n console.log(\"data added successfully\");\n callback(null, value);\n }\n});" }, { "code": null, "e": 10615, "s": 10448, "text": "Now, we will create AWS Lambda function to read data from DynamoDB table. We will trigger APIGateway to the AWS Lambda function which will send data to the html form." }, { "code": null, "e": 10667, "s": 10615, "text": "The AWS Lambda function created is as shown below −" }, { "code": null, "e": 10717, "s": 10667, "text": "The corresponding AWS Lambda code is as follows −" }, { "code": null, "e": 11191, "s": 10717, "text": "const aws = require(\"aws-sdk\");\nconst docClient = new aws.DynamoDB.DocumentClient({\n region:'us-east-1'\n});\nexports.handler = function(event, context, callback) {\n var readdata = {\n TableName : \"registeruser\",\n Limit : 10\n }\n docClient.scan(readdata, function(err, data) {\n if (err) {\n console.log(\"Error\");\n callback(err, null);\n } else {\n console.log(\"Data is \" + data);\n callback(null, data);\n }\n });\n}" }, { "code": null, "e": 11339, "s": 11191, "text": "Here the data is read from the DynamoDB table and given to the callback. Now, we will create APIGateway and add AWS Lambda function as the trigger." }, { "code": null, "e": 11390, "s": 11339, "text": "We will add get method to the API created earlier." }, { "code": null, "e": 11488, "s": 11390, "text": "Lambda function added is lambdareaddataexample. Click Save to save the method and deploy the api." }, { "code": null, "e": 11538, "s": 11488, "text": "The final display of the form is as shown below −" }, { "code": null, "e": 11686, "s": 11538, "text": "Now, enter the details as shown above. Note that the submit button is disabled. It will be enabled only when all the details are entered as shown −" }, { "code": null, "e": 11898, "s": 11686, "text": "Now, enter the mobile number and click validate phone button. It will display the alert message saying “OTP is send to the mobile, please enter the OTP to continue”. OTP sent to the mobile number is as follows −" }, { "code": null, "e": 11955, "s": 11898, "text": "Enter the OTP and remaining details and submit the form." }, { "code": null, "e": 12027, "s": 11955, "text": "The data in DynamoDB registeruser table after submit is as shown here −" }, { "code": null, "e": 12065, "s": 12027, "text": "The code details are as given below −" }, { "code": null, "e": 12079, "s": 12065, "text": "Example1.html" }, { "code": null, "e": 16333, "s": 12079, "text": "<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script type=\"text/javascript\" src=\"formdet.js\"></script>\n <style>\n input[type=text], input[type=password],button {\n width: 100%;\n padding: 5px 5px;\n margin: 5px 0;\n box-sizing: border-box;\n }\n #maincontainer {\n width: 80%;\n margin: auto;\n padding: 10px;\n }\n div#userregistration {\n width: 60%;\n float: left;\n }\n div#userdisplay {\n margin-left: 60%; \n }\n </style>\n </head>\n \n <body>\n <div id=\"maincontainer\">\n <div id=\"userregistration\">\n <h1>User Registration Form</h1>\n <table border=\"0\">\n <tr>\n <td><b>First Name<span style=\"color:red;\">*</span> : </b></td>\n <td><input type=\"text\" value=\"\" name=\"fname\" id=\"fname\" /></td>\n <td id=\"tdfname\" style=\"display:none;\"><span style=\"color:red;\">Enter First Name</span></td>\n </tr>\n <tr>\n <td><b>Last Name<span style=\"color:red;\">*</span> : </b></td>\n <td><input type=\"text\" value=\"\" name=\"lname\" id=\"lname\" /></td>\n <td id=\"tdlname\" style=\"display:none;\"><span style=\"color:red;\">Enter Last Name</span></td>\n </tr>\n <tr>\n <td><b>Email Id<span style=\"color:red;\">*</span> : </b></td>\n <td><input type=\"text\" value=\"\" name=\"emailid\" id=\"emailid\" /></td>\n <td id=\"tdemailid\" style=\"display:none;\"><span style=\"color:red;\">Enter Email</span></td>\n </tr>\n <tr>\n <td><b>Mobile No<span style=\"color:red;\">*</span> : </b></td>\n <td><input type=\"text\" name=\"mphone\" id=\"mphone\"/></td>\n <td id=\"tdmphone\" style=\"display:none;\"><span style=\"color:red;\">Enter Mobile Number</span></td>\n </tr> \n <tr>\n <td></td>\n <td><button id=\"validatephone\">validate phone</button></td>\t \n <td></td>\n </tr>\n <tr id=\"otpdiv\" style=\"display:none;\">\n <td><b>Enter OTP<span style=\"color:red;\">*</span>:</b></td>\n <td><input type=\"text\" value=\"\" name=\"otp\" id=\"otp\" /></td>\n <td id=\"tdotp\" style=\"display:none;\"><span style=\"color:red;\">Enter OTP</span></td>\n </tr>\n <tr>\n <td><b>Username<span style=\"color:red;\">*</span>: </b></td>\n <td><input type=\"text\" value=\"\" name=\"uname\" id=\"uname\"/></td>\n <td id=\"tduname\" style=\"display:none;\"><span style=\"color:red;\">Enter Username</span></td>\n </tr>\n <tr><td><b>Password<span style=\"color:red;\">*</span> :</b></td>\n <td><input type=\"password\" value=\"\" name=\"passwd\" id=\"passwd\"/></td>\n <td id=\"tdpasswd\" style=\"display:none;\"><span style=\"color:red;\">Enter Password</span></td>\n </tr>\n <tr><td><b>Confirm Password<span style=\"color:red;\">*</span> :</b></td>\n <td><input type=\"password\" value=\"\" name=\"cpasswd\" id=\"cpasswd\"/></td>\n <td id=\"tdcpasswd\" style=\"display:none;\"><span style=\"color:red;\">Enter Confirm Password</span></td>\n </tr>\n <tr>\n <td></td>\n <td><button name=\"submit\" id=\"submit\" style=\"display:;\" disabled=\"true\">Submit</button></td>\n <td></td>\n </tr>\n </table>\n </div>\n \n <div id=\"userdisplay\">\n <h1>User Display</h1>\n <table id=\"displaydetails\" style=\"display:block;width:80%;padding:5px;margin:5px; border: 1px solid black;\">\n <tr>\n <td></td>\n <td>FirstName</td>\n <td>LastName</td>\n <td>Mobile No</td>\n <td>EmailID</td>\n </tr>\n </table>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 16344, "s": 16333, "text": "formdet.js" }, { "code": null, "e": 21431, "s": 16344, "text": "function validateform() {\n var sError=\"\";\n if ($(\"#fname\").val() === \"\") {\n $(\"#tdfname\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#lname\").val() === \"\") {\n $(\"#tdlname\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#emailid\").val() === \"\") {\n $(\"#tdemailid\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#mphone\").val() === \"\") {\n $(\"#tdmphone\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#otp\").val() === \"\") {\n $(\"#tdotp\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#uname\").val() === \"\") {\n $(\"#tduname\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#passwd\").val() === \"\") {\n $(\"#tdpasswd\").css(\"display\",\"\");\n sError++;\n }\n if ($(\"#cpasswd\").val() === \"\") {\n $(\"#tdcpasswd\").css(\"display\",\"\");\n sError++;\n }\n if (sError === \"\") {\n return true;\n } else {\n return false;\n }\n}\n$(\"#fname\").change(function() {\n if ($(\"#fname\").val() !== \"\") {\n $(\"#tdfname\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdfname\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#lname\").change(function() {\n if ($(\"#lname\").val() !== \"\") {\n $(\"#tdlname\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdlname\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#emailid\").change(function() {\n if ($(\"#emailid\").val() !== \"\") {\n $(\"#tdemailid\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdemailid\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#mphone\").change(function() {\n if ($(\"#mphone\").val() !== \"\") {\n $(\"#tdmphone\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdmphone\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#otp\").change(function() {\n if ($(\"#otp\").val() !== \"\") {\n $(\"#tdotp\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdotp\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#uname\").change(function() {\n if ($(\"#uname\").val() !== \"\") {\n $(\"#tduname\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tduname\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#passwd\").change(function() {\n if ($(\"#passwd\").val() !== \"\") {\n $(\"#tdpasswd\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdpasswd\").css(\"display\",\"\");\t\t\t\n }\n});\n$(\"#cpasswd\").change(function() {\n if ($(\"#cpasswd\").val() !== \"\") {\n $(\"#tdcpasswd\").css(\"display\",\"none\");\t\t\t\n } else {\n $(\"#tdcpasswd\").css(\"display\",\"\");\t\t\t\n }\n});\n\nvar posturl = \"https://4rvwimysc1.execute-api.us-east-1.amazonaws.com/prod/adduser\";\nvar phonevalidationurl = \"https://wnvt01y6nc.execute-api.us-east-1.amazonaws.com/prod/validate\";\nvar otpsend = \"\";\nfunction getdata() {\n var a = 0;\n $.ajax({\n type:'GET',\n url:posturl,\t\t\t\t\n success: function(data) {\n $(\"#displaydetails\").html('');\n $(\"#displaydetails\").css(\"display\", \"\");\n console.log(data);\n $(\"#displaydetails\").append('<tr style=\"padding:5px;margin:5px;background-color:gray;\"><td>Name</td><td>Mobile No</td><td>EmailID</td></tr>');\n data.Items.forEach(function(registeruser) {\n var clr = (a%2 === 0) ? \"#eee\": \"white\";\n a++;\n $(\"#displaydetails\").append('<tr style=\"padding:5px;margin:5px;background-color:'+clr+'\"><td>'+registeruser.first_name+'-'+registeruser.last_name+'</td><td>'+registeruser.mobile_no+'</td><td>'+registeruser.emailid+'</td></tr>');\n });\n },\n error: function(err) {\n console.log(err);\n }\n });\n}\n\n$(document).ready(function() {\n $(\"#otp\").on(\"change\", function() {\n var otpentered = $(\"#otp\").val();\n if (otpsend == otpentered) {\n document.getElementById(\"submit\").disabled = false;\n } else {\n alert(\"OTP is not valid.Please enter the valid one or validate phone again to continue!\");\n document.getElementById(\"submit\").disabled = true;\n }\n });\n $(\"#validatephone\").on(\"click\", function() {\n $.ajax({\n type:'POST',\n url:phonevalidationurl,\n data:JSON.stringify({\n \"mphone\":$(\"#mphone\").val()\t\t\t\t\t\n }),\n success: function(data) {\n $(\"#otpdiv\").css(\"display\", \"\");\n alert(\"OTP is send to the mobile, please enter to continue\");\n console.log(data);\n otpsend = data;\n },\n error : function(err) {\n $(\"#otpdiv\").css(\"display\", \"none\");\n alert(\"Invalid mobile no.\");\n }\n });\n });\n $(\"#submit\").on(\"click\", function() {\n if (validateform()) {\n $.ajax({\n type:'POST',\n url:posturl,\n data:JSON.stringify({\n \"fname\": $(\"#fname\").val(),\n \"lname\": $(\"#lname\").val(),\n \"emailid\":$(\"#emailid\").val(),\n \"mphone\":$(\"#mphone\").val(),\n \"otp\":$(\"#otp\").val(),\n \"uname\":$(\"#uname\").val(),\n \"passwd\":$(\"#passwd\").val(),\n \"cpasswd\":$(\"#cpasswd\").val()\n }),\n success: function(data) {\n alert(\"Data added successfully\");\n console.log(data);\n getdata();\n }\n });\n }\n });\n getdata();\n});" }, { "code": null, "e": 21519, "s": 21431, "text": "Till now, we have done AJAX call to the API created and posted the data as shown above." }, { "code": null, "e": 21578, "s": 21519, "text": "The AJAX call to add the data to the table is as follows −" }, { "code": null, "e": 22419, "s": 21578, "text": "var posturl = \"https://4rvwimysc1.execute-api.us-east-1.amazonaws.com/prod/adduser\";\n$(document).ready(function() {\n $(\"#submit\").on(\"click\", function() {\n if (validateform()) {\n $.ajax({\n type:'POST',\n url:posturl,\n data:JSON.stringify({\n \"fname\": $(\"#fname\").val(),\n \"lname\": $(\"#lname\").val(),\n \"emailid\":$(\"#emailid\").val(),\n \"mphone\":$(\"#mphone\").val(),\n \"otp\":$(\"#otp\").val(),\n \"uname\":$(\"#uname\").val(),\n \"passwd\":$(\"#passwd\").val(),\n \"cpasswd\":$(\"#cpasswd\").val()\n }),\n success: function(data) {\n alert(\"Data added successfully\");\n console.log(data);\n getdata();\n }\n });\n }\n });\n});" }, { "code": null, "e": 22497, "s": 22419, "text": "Note that to read the data, a function is called, whose code is given below −" }, { "code": null, "e": 23346, "s": 22497, "text": "function getdata() {\n var a = 0;\n $.ajax({\n type:'GET',\n url:posturl,\t\t\t\t\n success: function(data) {\n $(\"#displaydetails\").html('');\n $(\"#displaydetails\").css(\"display\", \"\");\n console.log(data);\n $(\"#displaydetails\").append('<tr style=\"padding:5px;margin:5px;background-color:gray;\"><td>Name</td><td>Mobile No</td><td>EmailID</td></tr>');\n data.Items.forEach(function(registeruser) {\n var clr = (a%2 === 0) ? \"#eee\": \"white\";\n a++;\n $(\"#displaydetails\").append('<tr style=\"padding:5px;margin:5px;background-color:'+clr+'\"><td>'+registeruser.first_name+'-'+registeruser.last_name+'</td><td>'+registeruser.mobile_no+'</td><td>'+registeruser.emailid+'</td></tr>');\n });\n },\n error: function(err) {\n console.log(err);\n }\n });\n}" }, { "code": null, "e": 23451, "s": 23346, "text": "When you click mobile number validate button, the following code is called and sends the mobile number −" }, { "code": null, "e": 24455, "s": 23451, "text": " \nvar phonevalidationurl = \"https://wnvt01y6nc.execute-api.us-east-1.amazonaws.com/prod/validate\";\nvar otpsend = \"\";\n$(\"#validatephone\").on(\"click\", function() {\n $.ajax({\n type:'POST',\n url:phonevalidationurl,\n data:JSON.stringify({\n \"mphone\":$(\"#mphone\").val()\t\t\t\t\t\n }),\n success: function(data) {\n $(\"#otpdiv\").css(\"display\", \"\");\n alert(\"OTP is send to the mobile, please enter the OTP to continue\");\n console.log(data);\n otpsend = data;\n },\n error : function(err) {\n $(\"#otpdiv\").css(\"display\", \"none\");\n alert(\"Invalid mobile no.\");\n }\n });\n});\n\n// Validate otp\n$(\"#otp\").on(\"change\", function() {\n var otpentered = $(\"#otp\").val();\n if (otpsend == otpentered) {\n document.getElementById(\"submit\").disabled = false;\n } else {\n alert(\"OTP is not valid.Please enter the valid one or validate phone again to continue!\");\n document.getElementById(\"submit\").disabled = true;\n }\n}" }, { "code": null, "e": 24490, "s": 24455, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 24514, "s": 24490, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 24549, "s": 24514, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 24569, "s": 24549, "text": " Priyanka Choudhary" }, { "code": null, "e": 24604, "s": 24569, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 24632, "s": 24604, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 24665, "s": 24632, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 24681, "s": 24665, "text": " Manuj Aggarwal" }, { "code": null, "e": 24714, "s": 24681, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 24726, "s": 24714, "text": " AR Shankar" }, { "code": null, "e": 24759, "s": 24726, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 24772, "s": 24759, "text": " Zach Miller" }, { "code": null, "e": 24779, "s": 24772, "text": " Print" }, { "code": null, "e": 24790, "s": 24779, "text": " Add Notes" } ]
MySQL query to subtract date records with week day and display the weekday with records
For this, you can use DATE_FORMAT(). Let us first create a table − mysql> create table DemoTable1820 ( AdmissionDate varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1820 values('20/10/2019'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1820 values('19/12/2018'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1820 values('16/04/2017'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1820; This will produce the following output − +---------------+ | AdmissionDate | +---------------+ | 20/10/2019 | | 19/12/2018 | | 16/04/2017 | +---------------+ 3 rows in set (0.00 sec) Here is the query to subtract date records with week day and display week day name along with records − mysql> select DATE_FORMAT(SUBDATE(STR_TO_DATE(AdmissionDate,'%d/%m/%y'), WEEKDAY(STR_TO_DATE(AdmissionDate,'%d/%m/%y'))), '%a %d %b') from DemoTable1820; This will produce the following output − +-------------------------------------------------------------------------------------------------------------------------+ | DATE_FORMAT(SUBDATE(STR_TO_DATE(AdmissionDate,'%d/%m/%y'), WEEKDAY(STR_TO_DATE(AdmissionDate,'%d/%m/%y'))), '%a %d %b') | +-------------------------------------------------------------------------------------------------------------------------+ | Mon 19 Oct | | Mon 14 Dec | | Mon 13 Apr | +-------------------------------------------------------------------------------------------------------------------------+ 3 rows in set, 6 warnings (0.00 sec)
[ { "code": null, "e": 1129, "s": 1062, "text": "For this, you can use DATE_FORMAT(). Let us first create a table −" }, { "code": null, "e": 1246, "s": 1129, "text": "mysql> create table DemoTable1820\n (\n AdmissionDate varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1302, "s": 1246, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1575, "s": 1302, "text": "mysql> insert into DemoTable1820 values('20/10/2019');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1820 values('19/12/2018');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1820 values('16/04/2017');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1635, "s": 1575, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1671, "s": 1635, "text": "mysql> select * from DemoTable1820;" }, { "code": null, "e": 1712, "s": 1671, "text": "This will produce the following output −" }, { "code": null, "e": 1863, "s": 1712, "text": "+---------------+\n| AdmissionDate |\n+---------------+\n| 20/10/2019 |\n| 19/12/2018 |\n| 16/04/2017 |\n+---------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1967, "s": 1863, "text": "Here is the query to subtract date records with week day and display week day name along with records −" }, { "code": null, "e": 2121, "s": 1967, "text": "mysql> select DATE_FORMAT(SUBDATE(STR_TO_DATE(AdmissionDate,'%d/%m/%y'), WEEKDAY(STR_TO_DATE(AdmissionDate,'%d/%m/%y'))), '%a %d %b') from DemoTable1820;" }, { "code": null, "e": 2162, "s": 2121, "text": "This will produce the following output −" }, { "code": null, "e": 3067, "s": 2162, "text": "+-------------------------------------------------------------------------------------------------------------------------+\n| DATE_FORMAT(SUBDATE(STR_TO_DATE(AdmissionDate,'%d/%m/%y'), WEEKDAY(STR_TO_DATE(AdmissionDate,'%d/%m/%y'))), '%a %d %b') |\n+-------------------------------------------------------------------------------------------------------------------------+\n| Mon 19 Oct |\n| Mon 14 Dec |\n| Mon 13 Apr |\n+-------------------------------------------------------------------------------------------------------------------------+\n3 rows in set, 6 warnings (0.00 sec)" } ]
Deploy your Machine Learning Python Codes with Azure Functions | by lalitha raghavan | Towards Data Science
Azure Functions are code triggered events that scale well owing to their serverless capabilities. The triggering mechanisms are diverse — time based (CRON functions), http, storage triggers (blob, queue) etc. Functions are also unique in that they can be coded in a variety of languages like C#, Python, Javascript etc. In this article, I will be demonstrating a simple ML python script that is triggered using Azure functions using VS code. You can check my git repo here. Requirements: VS Code with Azure extensions loaded Azure subscription (free credits available) Azure function CLI installed. Please follow https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash A pickled ML model. Here I have picked a simple model that uses a regression algorithm to predict the price of a piece of real estate based on factors like age of the building, the distance from the city, the number of stores around the place, latitude and longitude. The focus has been on the implementation of the model in Azure functions and not the accuracy of the model itself. Place the python code and pkl files in a separate folder. Recommended to use a virtual environment for installing the necessary files. Freeze the requirements file in the same folder. Launch VS code. Fire up the function app from the extension, choose http trigger as the trigger and choose Anonymous as the trigger type. Launch the workspace and folder to where the python code and the pkl files are stored — requirements file is automatically created. The necessary files needed for running the code are further added, which include the packages necessary for running the pkl file. Launching the function automatically creates an init.py and a function.json file apart from other helpers. Let’s dig a little deeper into what the init.py file is actually doing — in this basic code, the init.py file is the script that contains the main code for the function app, that triggers the http and has the post and get requests. Results of the json dump are returned as a numpy array after the prediction on the model has been performed. The function.json file is simply a binder (that would change based on the trigger used) that points to the init.py file. Please note the anonymous authentication level used. Based on your requirement, you can change these settings. In case you are accessing based on a file change to your blob, for example, make sure you have your secure SAS keys in place. That’s about it, really. Now it’s time to test your own function app. In the command prompt initialize the function with: func initfunc host start You should be able to see some ascii characters. You will be directed to a link on the local. Allow it to be. This shows that the function app is actually working without flaws until now. Open up git bash and run the following command: curl -w '\n' 'http://localhost:7071/api/real_estate?Age=25&Dist=251&Num_stores=5&Lat=24.9756&Long=121.5521' You can of course change the values for age, dist etc. On running this bash command, a success in the python terminal should be shown along with the predicted value in the bash terminal. Deploying it to Azure via the vscode is the easiest way. This is pretty straightforward — use the deployment commands as prompted from the Functions extension. Your app should be ready. Use the weblink as deployed and add the same parts to the http link (?Age=25&Dist=251&Num_stores=5&Lat=24.9756&Long=121.5521). You should see the same response in your weblink as well. Alright, that’s pretty much it!!! — this is now an end to end pipeline to trigger a python script using vscode and azure functions. Azure functions are pretty versatile and can be put up in a pipeline with datafactory for more complex works.
[ { "code": null, "e": 646, "s": 172, "text": "Azure Functions are code triggered events that scale well owing to their serverless capabilities. The triggering mechanisms are diverse — time based (CRON functions), http, storage triggers (blob, queue) etc. Functions are also unique in that they can be coded in a variety of languages like C#, Python, Javascript etc. In this article, I will be demonstrating a simple ML python script that is triggered using Azure functions using VS code. You can check my git repo here." }, { "code": null, "e": 660, "s": 646, "text": "Requirements:" }, { "code": null, "e": 697, "s": 660, "text": "VS Code with Azure extensions loaded" }, { "code": null, "e": 741, "s": 697, "text": "Azure subscription (free credits available)" }, { "code": null, "e": 889, "s": 741, "text": "Azure function CLI installed. Please follow https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash" }, { "code": null, "e": 1272, "s": 889, "text": "A pickled ML model. Here I have picked a simple model that uses a regression algorithm to predict the price of a piece of real estate based on factors like age of the building, the distance from the city, the number of stores around the place, latitude and longitude. The focus has been on the implementation of the model in Azure functions and not the accuracy of the model itself." }, { "code": null, "e": 1456, "s": 1272, "text": "Place the python code and pkl files in a separate folder. Recommended to use a virtual environment for installing the necessary files. Freeze the requirements file in the same folder." }, { "code": null, "e": 1963, "s": 1456, "text": "Launch VS code. Fire up the function app from the extension, choose http trigger as the trigger and choose Anonymous as the trigger type. Launch the workspace and folder to where the python code and the pkl files are stored — requirements file is automatically created. The necessary files needed for running the code are further added, which include the packages necessary for running the pkl file. Launching the function automatically creates an init.py and a function.json file apart from other helpers." }, { "code": null, "e": 2478, "s": 1963, "text": "Let’s dig a little deeper into what the init.py file is actually doing — in this basic code, the init.py file is the script that contains the main code for the function app, that triggers the http and has the post and get requests. Results of the json dump are returned as a numpy array after the prediction on the model has been performed. The function.json file is simply a binder (that would change based on the trigger used) that points to the init.py file. Please note the anonymous authentication level used." }, { "code": null, "e": 2662, "s": 2478, "text": "Based on your requirement, you can change these settings. In case you are accessing based on a file change to your blob, for example, make sure you have your secure SAS keys in place." }, { "code": null, "e": 2784, "s": 2662, "text": "That’s about it, really. Now it’s time to test your own function app. In the command prompt initialize the function with:" }, { "code": null, "e": 2809, "s": 2784, "text": "func initfunc host start" }, { "code": null, "e": 2997, "s": 2809, "text": "You should be able to see some ascii characters. You will be directed to a link on the local. Allow it to be. This shows that the function app is actually working without flaws until now." }, { "code": null, "e": 3045, "s": 2997, "text": "Open up git bash and run the following command:" }, { "code": null, "e": 3153, "s": 3045, "text": "curl -w '\\n' 'http://localhost:7071/api/real_estate?Age=25&Dist=251&Num_stores=5&Lat=24.9756&Long=121.5521'" }, { "code": null, "e": 3340, "s": 3153, "text": "You can of course change the values for age, dist etc. On running this bash command, a success in the python terminal should be shown along with the predicted value in the bash terminal." }, { "code": null, "e": 3653, "s": 3340, "text": "Deploying it to Azure via the vscode is the easiest way. This is pretty straightforward — use the deployment commands as prompted from the Functions extension. Your app should be ready. Use the weblink as deployed and add the same parts to the http link (?Age=25&Dist=251&Num_stores=5&Lat=24.9756&Long=121.5521)." }, { "code": null, "e": 3711, "s": 3653, "text": "You should see the same response in your weblink as well." } ]
Perl readline Function
This function reads a line from the filehandle referred to by EXPR, returning the result. If you want to use a FILEHANDLE directly, it must be passed as a typeglob. Simply readline function is equvivalent to <>. Following is the simple syntax for this function − readline EXPR This function returns only one line in a scalar context and in a list context, a list of line up to end-of-file is returned Following is the example code showing its basic usage − #!/usr/bin/perl -w my($buffer) = ""; open(FILE, "/etc/services") or die("Error reading file, stopped"); $buffer = <FILE>; print("$buffer"); $buffer = readline( *FILE ); print("$buffer"); close(FILE); When above code is executed, it produces the following result − # /etc/services: # $Id: services,v 1.33 2003/03/14 16:41:47 notting Exp $ 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2385, "s": 2220, "text": "This function reads a line from the filehandle referred to by EXPR, returning the result. If you want to use a FILEHANDLE directly, it must be passed as a typeglob." }, { "code": null, "e": 2432, "s": 2385, "text": "Simply readline function is equvivalent to <>." }, { "code": null, "e": 2483, "s": 2432, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2498, "s": 2483, "text": "readline EXPR\n" }, { "code": null, "e": 2622, "s": 2498, "text": "This function returns only one line in a scalar context and in a list context, a list of line up to end-of-file is returned" }, { "code": null, "e": 2678, "s": 2622, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2885, "s": 2678, "text": "#!/usr/bin/perl -w\n\nmy($buffer) = \"\";\nopen(FILE, \"/etc/services\") or\n die(\"Error reading file, stopped\");\n\n$buffer = <FILE>;\nprint(\"$buffer\");\n\n$buffer = readline( *FILE );\nprint(\"$buffer\");\n\nclose(FILE);" }, { "code": null, "e": 2949, "s": 2885, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 3024, "s": 2949, "text": "# /etc/services:\n# $Id: services,v 1.33 2003/03/14 16:41:47 notting Exp $\n" }, { "code": null, "e": 3059, "s": 3024, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3073, "s": 3059, "text": " Devi Killada" }, { "code": null, "e": 3108, "s": 3073, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3128, "s": 3108, "text": " Harshit Srivastava" }, { "code": null, "e": 3161, "s": 3128, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3177, "s": 3161, "text": " TELCOMA Global" }, { "code": null, "e": 3210, "s": 3177, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3227, "s": 3210, "text": " Mohammad Nauman" }, { "code": null, "e": 3260, "s": 3227, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3283, "s": 3260, "text": " Stone River ELearning" }, { "code": null, "e": 3318, "s": 3283, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3341, "s": 3318, "text": " Stone River ELearning" }, { "code": null, "e": 3348, "s": 3341, "text": " Print" }, { "code": null, "e": 3359, "s": 3348, "text": " Add Notes" } ]
How to convert dictionary into list of JavaScript objects?
Following is the code to convert dictionary into list of JavaScript objects − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample{ font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Convert dictionary into list of JavaScript objects</h1> <div class="sample"> { A: { 1: "Apple", 2: "Apricot" }, B: { 1: "Ball", 2: "Bull" }, C: { 1: "Cat", 2: "Cow" }, D: { 1: "Dog", 2: "Drill" }, } </div> <button class="Btn">CLICK HERE</button> <h3>Click the above button to convert the above dictionary into list of object</h3> <script> let BtnEle = document.querySelector(".Btn"); let arr; const obj = { A: { 1: "Apple", 2: "Apricot" }, B: { 1: "Ball", 2: "Bull" }, C: { 1: "Cat", 2: "Cow" }, D: { 1: "Dog", 2: "Drill" }, }; BtnEle.addEventListener("click", () => { arr = Object.values(obj); console.log(arr); }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button and looking at the output in console −
[ { "code": null, "e": 1140, "s": 1062, "text": "Following is the code to convert dictionary into list of JavaScript objects −" }, { "code": null, "e": 1151, "s": 1140, "text": " Live Demo" }, { "code": null, "e": 2221, "s": 1151, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample{\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Convert dictionary into list of JavaScript objects</h1>\n<div class=\"sample\">\n{ A: { 1: \"Apple\", 2: \"Apricot\" }, B: { 1: \"Ball\", 2: \"Bull\" }, C: { 1:\n\"Cat\", 2: \"Cow\" }, D: { 1: \"Dog\", 2: \"Drill\" }, }\n</div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click the above button to convert the above dictionary into list of object</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let arr;\n const obj = {\n A: { 1: \"Apple\", 2: \"Apricot\" },\n B: { 1: \"Ball\", 2: \"Bull\" },\n C: { 1: \"Cat\", 2: \"Cow\" },\n D: { 1: \"Dog\", 2: \"Drill\" },\n };\n BtnEle.addEventListener(\"click\", () => {\n arr = Object.values(obj);\n console.log(arr);\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2272, "s": 2221, "text": "The above code will produce the following output −" }, { "code": null, "e": 2347, "s": 2272, "text": "On clicking the ‘CLICK HERE’ button and looking at the output in console −" } ]
Tryit Editor v3.7
Tryit: Ordered HTML list
[]
How to combine multiple graphs in Python
Matplotlib allows to add more than one plot in the same graph. In this tutorial, I will show you how to present data in the same plot, on two different axes. 1. Install matplotlib by opening up the python command prompt and firing pip install matplotlib. import matplotlib.pyplot as plt 2. Prepare the data to be displayed. import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),) 3. Split the data into arrays for each company company's mobile units. # data prep - splitting the data Years, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold) # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2 4. Create the first subplot. plt.subplot(2, 1, 1) <matplotlib.axes._subplots.AxesSubplot at 0x214185d4e50> 5. Create a bar graph with information about IPhone_Sales. Iphone = plt.bar(Position, IPhone_Sales,color='green') plt.ylabel('IPhone Sales') plt.xticks(Position, Years) ([<matplotlib.axis.XTick at 0x214186115e0>, <matplotlib.axis.XTick at 0x21418611580>, <matplotlib.axis.XTick at 0x2141861fc40>, <matplotlib.axis.XTick at 0x21418654e20>, <matplotlib.axis.XTick at 0x2141865f370>], [Text(0, 0, '2016'), Text(0, 0, '2017'), Text(0, 0, '2018'), Text(0, 0, '2019'), Text(0, 0, '2020')]) 6. Now create another y axis to add information about Samsung Galaxy sales. plt.twinx() Galaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue') plt.ylabel('Galaxy Sales') plt.xticks(Position, Years) ([<matplotlib.axis.XTick at 0x214186b4c40>, <matplotlib.axis.XTick at 0x214186b4c10>, <matplotlib.axis.XTick at 0x21418682ac0>, <matplotlib.axis.XTick at 0x214186dd8e0>, <matplotlib.axis.XTick at 0x214186dddf0>], [Text(0, 0, '2016'), Text(0, 0, '2017'), Text(0, 0, '2018'), Text(0, 0, '2019'), Text(0, 0, '2020')]) 7. We will now plot the final Google Pixel Sales. plt.subplot(2, 1, 2) plt.plot(Position, Pixel_Sales, color='yellow') plt.gca().set_ylim(ymin=0) plt.xticks(Position, Years) ([<matplotlib.axis.XTick at 0x2141870f9a0>, <matplotlib.axis.XTick at 0x2141870f580>, <matplotlib.axis.XTick at 0x2141870a730>, <matplotlib.axis.XTick at 0x2141873c9d0>, <matplotlib.axis.XTick at 0x2141873cee0>], [Text(0, 0, '2016'), Text(0, 0, '2017'), Text(0, 0, '2018'), Text(0, 0, '2019'), Text(0, 0, '2020')]) plt.show() 8.Putting it alltogether and saving the chart. import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),) # data prep - splitting the data Years, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold) # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2 plt.subplot(2, 1, 1) Iphone = plt.bar(Position, IPhone_Sales,color='green') plt.ylabel('IPhone Sales') plt.xticks(Position, Years) plt.twinx() Galaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue') plt.ylabel('Galaxy Sales') plt.xticks(Position, Years) plt.subplot(2, 1, 2) plt.plot(Position, Pixel_Sales, color='yellow') plt.ylabel('Pixel Sales') plt.gca().set_ylim(ymin=0) plt.xticks(Position, Years) # plt.show() plt.savefig('CombiningGraphs.png', dpi=72)
[ { "code": null, "e": 1220, "s": 1062, "text": "Matplotlib allows to add more than one plot in the same graph. In this tutorial, I will show you how to present data in the same plot, on two different axes." }, { "code": null, "e": 1317, "s": 1220, "text": "1.\nInstall matplotlib by opening up the python command prompt and firing pip install matplotlib." }, { "code": null, "e": 1349, "s": 1317, "text": "import matplotlib.pyplot as plt" }, { "code": null, "e": 1386, "s": 1349, "text": "2.\nPrepare the data to be displayed." }, { "code": null, "e": 1676, "s": 1386, "text": "import matplotlib.pyplot as plt\n\n# data prep (I made up data no accuracy in these stats)\nmobile = ['Iphone','Galaxy','Pixel']\n\n# Data for the mobile units sold for 4 Quaters in Million\nunits_sold = (('2016',12,8,6),\n('2017',14,10,7),\n('2018',16,12,8),\n('2019',18,14,10),\n('2020',20,16,5),)" }, { "code": null, "e": 1747, "s": 1676, "text": "3.\nSplit the data into arrays for each company company's mobile units." }, { "code": null, "e": 1935, "s": 1747, "text": "# data prep - splitting the data\nYears, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold)\n\n# set the position\nPosition = list(range(len(units_sold)))\n\n# set the width\nWidth = 0.2" }, { "code": null, "e": 1964, "s": 1935, "text": "4.\nCreate the first subplot." }, { "code": null, "e": 1985, "s": 1964, "text": "plt.subplot(2, 1, 1)" }, { "code": null, "e": 2042, "s": 1985, "text": "<matplotlib.axes._subplots.AxesSubplot at 0x214185d4e50>" }, { "code": null, "e": 2101, "s": 2042, "text": "5.\nCreate a bar graph with information about IPhone_Sales." }, { "code": null, "e": 2211, "s": 2101, "text": "Iphone = plt.bar(Position, IPhone_Sales,color='green')\nplt.ylabel('IPhone Sales')\nplt.xticks(Position, Years)" }, { "code": null, "e": 2526, "s": 2211, "text": "([<matplotlib.axis.XTick at 0x214186115e0>,\n<matplotlib.axis.XTick at 0x21418611580>,\n<matplotlib.axis.XTick at 0x2141861fc40>,\n<matplotlib.axis.XTick at 0x21418654e20>,\n<matplotlib.axis.XTick at 0x2141865f370>],\n[Text(0, 0, '2016'),\nText(0, 0, '2017'),\nText(0, 0, '2018'),\nText(0, 0, '2019'),\nText(0, 0, '2020')])" }, { "code": null, "e": 2602, "s": 2526, "text": "6.\nNow create another y axis to add information about Samsung Galaxy sales." }, { "code": null, "e": 2731, "s": 2602, "text": "plt.twinx()\nGalaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue')\nplt.ylabel('Galaxy Sales')\nplt.xticks(Position, Years)" }, { "code": null, "e": 3046, "s": 2731, "text": "([<matplotlib.axis.XTick at 0x214186b4c40>,\n<matplotlib.axis.XTick at 0x214186b4c10>,\n<matplotlib.axis.XTick at 0x21418682ac0>,\n<matplotlib.axis.XTick at 0x214186dd8e0>,\n<matplotlib.axis.XTick at 0x214186dddf0>],\n[Text(0, 0, '2016'),\nText(0, 0, '2017'),\nText(0, 0, '2018'),\nText(0, 0, '2019'),\nText(0, 0, '2020')])" }, { "code": null, "e": 3096, "s": 3046, "text": "7.\nWe will now plot the final Google Pixel Sales." }, { "code": null, "e": 3220, "s": 3096, "text": "plt.subplot(2, 1, 2)\nplt.plot(Position, Pixel_Sales, color='yellow')\nplt.gca().set_ylim(ymin=0)\nplt.xticks(Position, Years)" }, { "code": null, "e": 3535, "s": 3220, "text": "([<matplotlib.axis.XTick at 0x2141870f9a0>,\n<matplotlib.axis.XTick at 0x2141870f580>,\n<matplotlib.axis.XTick at 0x2141870a730>,\n<matplotlib.axis.XTick at 0x2141873c9d0>,\n<matplotlib.axis.XTick at 0x2141873cee0>],\n[Text(0, 0, '2016'),\nText(0, 0, '2017'),\nText(0, 0, '2018'),\nText(0, 0, '2019'),\nText(0, 0, '2020')])" }, { "code": null, "e": 3546, "s": 3535, "text": "plt.show()" }, { "code": null, "e": 3593, "s": 3546, "text": "8.Putting it alltogether and saving the chart." }, { "code": null, "e": 4541, "s": 3593, "text": "import matplotlib.pyplot as plt\n\n# data prep (I made up data no accuracy in these stats)\nmobile = ['Iphone','Galaxy','Pixel']\n\n# Data for the mobile units sold for 4 Quaters in Million\nunits_sold = (('2016',12,8,6),\n('2017',14,10,7),\n('2018',16,12,8),\n('2019',18,14,10),\n('2020',20,16,5),)\n# data prep - splitting the data\nYears, IPhone_Sales, Galaxy_Sales, Pixel_Sales = zip(*units_sold)\n\n# set the position\nPosition = list(range(len(units_sold)))\n\n# set the width\nWidth = 0.2\n\nplt.subplot(2, 1, 1)\nIphone = plt.bar(Position, IPhone_Sales,color='green')\nplt.ylabel('IPhone Sales')\nplt.xticks(Position, Years)\n\nplt.twinx()\nGalaxy = plt.plot(Position, Galaxy_Sales, 'o-', color='blue')\nplt.ylabel('Galaxy Sales')\nplt.xticks(Position, Years)\n\nplt.subplot(2, 1, 2)\nplt.plot(Position, Pixel_Sales, color='yellow')\nplt.ylabel('Pixel Sales')\nplt.gca().set_ylim(ymin=0)\nplt.xticks(Position, Years)\n\n# plt.show()\nplt.savefig('CombiningGraphs.png', dpi=72)" } ]
How to get the maximum file name length limit using Python?
On some platforms, the maximum filename length varies according to the location on the disk. If you run UNIX with different filesystems mounted in various locations on your directory tree, you might see the following values for the maximum filename length in those locations: >>> import statvfs, os >>> os.statvfs('/')[statvfs.F_NAMEMAX] 4032 >>> os.statvfs('/boot')[statvfs.F_NAMEMAX] 255
[ { "code": null, "e": 1338, "s": 1062, "text": "On some platforms, the maximum filename length varies according to the location on the disk. If you run UNIX with different filesystems mounted in various locations on your directory tree, you might see the following values for the maximum filename length in those locations:" }, { "code": null, "e": 1452, "s": 1338, "text": ">>> import statvfs, os\n>>> os.statvfs('/')[statvfs.F_NAMEMAX]\n4032\n>>> os.statvfs('/boot')[statvfs.F_NAMEMAX]\n255" } ]
SciPy - CSGraph
CSGraph stands for Compressed Sparse Graph, which focuses on Fast graph algorithms based on sparse matrix representations. To begin with, let us understand what a sparse graph is and how it helps in graph representations. A graph is just a collection of nodes, which have links between them. Graphs can represent nearly anything − social network connections, where each node is a person and is connected to acquaintances; images, where each node is a pixel and is connected to neighboring pixels; points in a high-dimensional distribution, where each node is connected to its nearest neighbors; and practically anything else you can imagine. One very efficient way to represent graph data is in a sparse matrix: let us call it G. The matrix G is of size N x N, and G[i, j] gives the value of the connection between node ‘i' and node ‘j’. A sparse graph contains mostly zeros − that is, most nodes have only a few connections. This property turns out to be true in most cases of interest. The creation of the sparse graph submodule was motivated by several algorithms used in scikit-learn that included the following − Isomap − A manifold learning algorithm, which requires finding the shortest paths in a graph. Isomap − A manifold learning algorithm, which requires finding the shortest paths in a graph. Hierarchical clustering − A clustering algorithm based on a minimum spanning tree. Hierarchical clustering − A clustering algorithm based on a minimum spanning tree. Spectral Decomposition − A projection algorithm based on sparse graph laplacians. Spectral Decomposition − A projection algorithm based on sparse graph laplacians. As a concrete example, imagine that we would like to represent the following undirected graph − This graph has three nodes, where node 0 and 1 are connected by an edge of weight 2, and nodes 0 and 2 are connected by an edge of weight 1. We can construct the dense, masked and sparse representations as shown in the following example, keeping in mind that an undirected graph is represented by a symmetric matrix. G_dense = np.array([ [0, 2, 1], [2, 0, 0], [1, 0, 0] ]) G_masked = np.ma.masked_values(G_dense, 0) from scipy.sparse import csr_matrix G_sparse = csr_matrix(G_dense) print G_sparse.data The above program will generate the following output. array([2, 1, 2, 1]) This is identical to the previous graph, except nodes 0 and 2 are connected by an edge of zero weight. In this case, the dense representation above leads to ambiguities − how can non-edges be represented, if zero is a meaningful value. In this case, either a masked or a sparse representation must be used to eliminate the ambiguity. Let us consider the following example. from scipy.sparse.csgraph import csgraph_from_dense G2_data = np.array ([ [np.inf, 2, 0 ], [2, np.inf, np.inf], [0, np.inf, np.inf] ]) G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf) print G2_sparse.data The above program will generate the following output. array([ 2., 0., 2., 0.]) Word ladders is a game invented by Lewis Carroll, in which words are linked by changing a single letter at each step. For example − APE → APT → AIT → BIT → BIG → BAG → MAG → MAN Here, we have gone from "APE" to "MAN" in seven steps, changing one letter each time. The question is - Can we find a shorter path between these words using the same rule? This problem is naturally expressed as a sparse graph problem. The nodes will correspond to individual words, and we will create connections between words that differ by at the most – one letter. First, of course, we must obtain a list of valid words. I am running Mac, and Mac has a word dictionary at the location given in the following code block. If you are on a different architecture, you may have to search a bit to find your system dictionary. wordlist = open('/usr/share/dict/words').read().split() print len(wordlist) The above program will generate the following output. 235886 We now want to look at words of length 3, so let us select just those words of the correct length. We will also eliminate words, which start with upper case (proper nouns) or contain non-alpha-numeric characters such as apostrophes and hyphens. Finally, we will make sure everything is in lower case for a comparison later on. word_list = [word for word in word_list if len(word) == 3] word_list = [word for word in word_list if word[0].islower()] word_list = [word for word in word_list if word.isalpha()] word_list = map(str.lower, word_list) print len(word_list) The above program will generate the following output. 1135 Now, we have a list of 1135 valid three-letter words (the exact number may change depending on the particular list used). Each of these words will become a node in our graph, and we will create edges connecting the nodes associated with each pair of words, which differs by only one letter. import numpy as np word_list = np.asarray(word_list) word_list.dtype word_list.sort() word_bytes = np.ndarray((word_list.size, word_list.itemsize), dtype = 'int8', buffer = word_list.data) print word_bytes.shape The above program will generate the following output. (1135, 3) We will use the Hamming distance between each point to determine, which pairs of words are connected. The Hamming distance measures the fraction of entries between two vectors, which differ: any two words with a hamming distance equal to 1/N1/N, where NN is the number of letters, which are connected in the word ladder. from scipy.spatial.distance import pdist, squareform from scipy.sparse import csr_matrix hamming_dist = pdist(word_bytes, metric = 'hamming') graph = csr_matrix(squareform(hamming_dist < 1.5 / word_list.itemsize)) When comparing the distances, we do not use equality because this can be unstable for floating point values. The inequality produces the desired result as long as no two entries of the word list are identical. Now, that our graph is set up, we will use the shortest path search to find the path between any two words in the graph. i1 = word_list.searchsorted('ape') i2 = word_list.searchsorted('man') print word_list[i1],word_list[i2] The above program will generate the following output. ape, man We need to check that these match, because if the words are not in the list there will be an error in the output. Now, all we need is to find the shortest path between these two indices in the graph. We will use dijkstra’s algorithm, because it allows us to find the path for just one node. from scipy.sparse.csgraph import dijkstra distances, predecessors = dijkstra(graph, indices = i1, return_predecessors = True) print distances[i2] The above program will generate the following output. 5.0 Thus, we see that the shortest path between ‘ape’ and ‘man’ contains only five steps. We can use the predecessors returned by the algorithm to reconstruct this path. path = [] i = i2 while i != i1: path.append(word_list[i]) i = predecessors[i] path.append(word_list[i1]) print path[::-1]i2] The above program will generate the following output. ['ape', 'ope', 'opt', 'oat', 'mat', 'man'] Print Add Notes Bookmark this page
[ { "code": null, "e": 2010, "s": 1887, "text": "CSGraph stands for Compressed Sparse Graph, which focuses on Fast graph algorithms based on sparse matrix representations." }, { "code": null, "e": 2109, "s": 2010, "text": "To begin with, let us understand what a sparse graph is and how it helps in graph representations." }, { "code": null, "e": 2529, "s": 2109, "text": "A graph is just a collection of nodes, which have links between them. Graphs can represent nearly anything − social network connections, where each node is a person and is connected to acquaintances; images, where each node is a pixel and is connected to neighboring pixels; points in a high-dimensional distribution, where each node is connected to its nearest neighbors; and practically anything else you can imagine." }, { "code": null, "e": 2875, "s": 2529, "text": "One very efficient way to represent graph data is in a sparse matrix: let us call it G. The matrix G is of size N x N, and G[i, j] gives the value of the connection between node ‘i' and node ‘j’. A sparse graph contains mostly zeros − that is, most nodes have only a few connections. This property turns out to be true in most cases of interest." }, { "code": null, "e": 3005, "s": 2875, "text": "The creation of the sparse graph submodule was motivated by several algorithms used in scikit-learn that included the following −" }, { "code": null, "e": 3099, "s": 3005, "text": "Isomap − A manifold learning algorithm, which requires finding the shortest paths in a graph." }, { "code": null, "e": 3193, "s": 3099, "text": "Isomap − A manifold learning algorithm, which requires finding the shortest paths in a graph." }, { "code": null, "e": 3276, "s": 3193, "text": "Hierarchical clustering − A clustering algorithm based on a minimum spanning tree." }, { "code": null, "e": 3359, "s": 3276, "text": "Hierarchical clustering − A clustering algorithm based on a minimum spanning tree." }, { "code": null, "e": 3441, "s": 3359, "text": "Spectral Decomposition − A projection algorithm based on sparse graph laplacians." }, { "code": null, "e": 3523, "s": 3441, "text": "Spectral Decomposition − A projection algorithm based on sparse graph laplacians." }, { "code": null, "e": 3619, "s": 3523, "text": "As a concrete example, imagine that we would like to represent the following undirected graph −" }, { "code": null, "e": 3936, "s": 3619, "text": "This graph has three nodes, where node 0 and 1 are connected by an edge of weight 2, and nodes 0 and 2 are connected by an edge of weight 1. We can construct the dense, masked and sparse representations as shown in the following example, keeping in mind that an undirected graph is represented by a symmetric matrix." }, { "code": null, "e": 4187, "s": 3936, "text": "G_dense = np.array([ [0, 2, 1],\n [2, 0, 0],\n [1, 0, 0] ])\n \nG_masked = np.ma.masked_values(G_dense, 0)\nfrom scipy.sparse import csr_matrix\n\nG_sparse = csr_matrix(G_dense)\nprint G_sparse.data" }, { "code": null, "e": 4241, "s": 4187, "text": "The above program will generate the following output." }, { "code": null, "e": 4262, "s": 4241, "text": "array([2, 1, 2, 1])\n" }, { "code": null, "e": 4596, "s": 4262, "text": "This is identical to the previous graph, except nodes 0 and 2 are connected by an edge of zero weight. In this case, the dense representation above leads to ambiguities − how can non-edges be represented, if zero is a meaningful value. In this case, either a masked or a sparse representation must be used to eliminate the ambiguity." }, { "code": null, "e": 4635, "s": 4596, "text": "Let us consider the following example." }, { "code": null, "e": 4859, "s": 4635, "text": "from scipy.sparse.csgraph import csgraph_from_dense\nG2_data = np.array\n([\n [np.inf, 2, 0 ],\n [2, np.inf, np.inf],\n [0, np.inf, np.inf]\n])\nG2_sparse = csgraph_from_dense(G2_data, null_value=np.inf)\nprint G2_sparse.data" }, { "code": null, "e": 4913, "s": 4859, "text": "The above program will generate the following output." }, { "code": null, "e": 4939, "s": 4913, "text": "array([ 2., 0., 2., 0.])\n" }, { "code": null, "e": 5071, "s": 4939, "text": "Word ladders is a game invented by Lewis Carroll, in which words are linked by changing a single letter at each step. For example −" }, { "code": null, "e": 5117, "s": 5071, "text": "APE → APT → AIT → BIT → BIG → BAG → MAG → MAN" }, { "code": null, "e": 5485, "s": 5117, "text": "Here, we have gone from \"APE\" to \"MAN\" in seven steps, changing one letter each time. The question is - Can we find a shorter path between these words using the same rule? This problem is naturally expressed as a sparse graph problem. The nodes will correspond to individual words, and we will create connections between words that differ by at the most – one letter." }, { "code": null, "e": 5741, "s": 5485, "text": "First, of course, we must obtain a list of valid words. I am running Mac, and Mac has a word dictionary at the location given in the following code block. If you are on a different architecture, you may have to search a bit to find your system dictionary." }, { "code": null, "e": 5817, "s": 5741, "text": "wordlist = open('/usr/share/dict/words').read().split()\nprint len(wordlist)" }, { "code": null, "e": 5871, "s": 5817, "text": "The above program will generate the following output." }, { "code": null, "e": 5879, "s": 5871, "text": "235886\n" }, { "code": null, "e": 6206, "s": 5879, "text": "We now want to look at words of length 3, so let us select just those words of the correct length. We will also eliminate words, which start with upper case (proper nouns) or contain non-alpha-numeric characters such as apostrophes and hyphens. Finally, we will make sure everything is in lower case for a comparison later on." }, { "code": null, "e": 6445, "s": 6206, "text": "word_list = [word for word in word_list if len(word) == 3]\nword_list = [word for word in word_list if word[0].islower()]\nword_list = [word for word in word_list if word.isalpha()]\nword_list = map(str.lower, word_list)\nprint len(word_list)" }, { "code": null, "e": 6499, "s": 6445, "text": "The above program will generate the following output." }, { "code": null, "e": 6505, "s": 6499, "text": "1135\n" }, { "code": null, "e": 6796, "s": 6505, "text": "Now, we have a list of 1135 valid three-letter words (the exact number may change depending on the particular list used). Each of these words will become a node in our graph, and we will create edges connecting the nodes associated with each pair of words, which differs by only one letter." }, { "code": null, "e": 7016, "s": 6796, "text": "import numpy as np\nword_list = np.asarray(word_list)\n\nword_list.dtype\nword_list.sort()\n\nword_bytes = np.ndarray((word_list.size, word_list.itemsize),\n dtype = 'int8',\n buffer = word_list.data)\nprint word_bytes.shape" }, { "code": null, "e": 7070, "s": 7016, "text": "The above program will generate the following output." }, { "code": null, "e": 7081, "s": 7070, "text": "(1135, 3)\n" }, { "code": null, "e": 7402, "s": 7081, "text": "We will use the Hamming distance between each point to determine, which pairs of words are connected. The Hamming distance measures the fraction of entries between two vectors, which differ: any two words with a hamming distance equal to 1/N1/N, where NN is the number of letters, which are connected in the word ladder." }, { "code": null, "e": 7617, "s": 7402, "text": "from scipy.spatial.distance import pdist, squareform\nfrom scipy.sparse import csr_matrix\nhamming_dist = pdist(word_bytes, metric = 'hamming')\ngraph = csr_matrix(squareform(hamming_dist < 1.5 / word_list.itemsize))\n" }, { "code": null, "e": 7948, "s": 7617, "text": "When comparing the distances, we do not use equality because this can be unstable for floating point values. The inequality produces the desired result as long as no two entries of the word list are identical. Now, that our graph is set up, we will use the shortest path search to find the path between any two words in the graph." }, { "code": null, "e": 8052, "s": 7948, "text": "i1 = word_list.searchsorted('ape')\ni2 = word_list.searchsorted('man')\nprint word_list[i1],word_list[i2]" }, { "code": null, "e": 8106, "s": 8052, "text": "The above program will generate the following output." }, { "code": null, "e": 8116, "s": 8106, "text": "ape, man\n" }, { "code": null, "e": 8407, "s": 8116, "text": "We need to check that these match, because if the words are not in the list there will be an error in the output. Now, all we need is to find the shortest path between these two indices in the graph. We will use dijkstra’s algorithm, because it allows us to find the path for just one node." }, { "code": null, "e": 8553, "s": 8407, "text": "from scipy.sparse.csgraph import dijkstra\ndistances, predecessors = dijkstra(graph, indices = i1, return_predecessors = True)\nprint distances[i2]" }, { "code": null, "e": 8607, "s": 8553, "text": "The above program will generate the following output." }, { "code": null, "e": 8612, "s": 8607, "text": "5.0\n" }, { "code": null, "e": 8778, "s": 8612, "text": "Thus, we see that the shortest path between ‘ape’ and ‘man’ contains only five steps. We can use the predecessors returned by the algorithm to reconstruct this path." }, { "code": null, "e": 8914, "s": 8778, "text": "path = []\ni = i2\n\nwhile i != i1:\n path.append(word_list[i])\n i = predecessors[i]\n \npath.append(word_list[i1])\nprint path[::-1]i2]" }, { "code": null, "e": 8968, "s": 8914, "text": "The above program will generate the following output." }, { "code": null, "e": 9012, "s": 8968, "text": "['ape', 'ope', 'opt', 'oat', 'mat', 'man']\n" }, { "code": null, "e": 9019, "s": 9012, "text": " Print" }, { "code": null, "e": 9030, "s": 9019, "text": " Add Notes" } ]
C++ program to find minimum vertex cover size of a graph using binary search
In this article, we will be discussing a program to find the minimum vertex cover size of a given graph using binary search. Minimum vertex cover is a set of vertices of the given graph such that every edge in the graph is incident of either of the vertices in that set. For example, take the graph 2 ---- 4 ---- 6 | | | | | | 3 ---- 5 Here, the minimum vertex cover involves vertices 3 and 4. All the edges of the graphs are incident on either 3 or 4 vertice of the graph. Live Demo #include<bits/stdc++.h> using namespace std; #define max 15 //array to store graph bool arr[max][max]; //check if minimum vertex cover exists bool check_cover(int V, int k, int E) { int set = (1 << k) - 1; int limit = (1 << V); //to mark the edges of size 'k' bool vis[max][max]; while (set < limit) { //resetting the vertex cover for each iteration memset(vis, 0, sizeof vis); int count = 0; //checking the values which has a high value for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) { if (set & j) { //marking the edges visited for (int k = 1 ; k <= V ; k++) { if (arr[v][k] && !vis[v][k]) { vis[v][k] = 1; vis[k][v] = 1; count++; } } } } //if all the edges are covered if (count == E) return true; int c = set & -set; int r = set + c; set = (((r^set) >> 2) / c) | r; } return false; } //to find minimum vertex cover int find_cover(int n, int m) { //performing binary search int left = 1, right = n; while (right > left){ int mid = (left + right) >> 1; if (check_cover(n, mid, m) == false) left = mid + 1; else right = mid; } return left; } //inserting edge in the graph void add_edge(int u, int v) { arr[u][v] = 1; arr[v][u] = 1; } int main() { memset(arr, 0, sizeof arr); int V = 6, E = 5; add_edge(2, 3); add_edge(2, 4); add_edge(3, 5); add_edge(4, 5); add_edge(4, 6); cout << "Size of Minimum Vertex Cover : " << find_cover(V, E) << endl; return 0; } Size of Minimum Vertex Cover : 2
[ { "code": null, "e": 1187, "s": 1062, "text": "In this article, we will be discussing a program to find the minimum vertex cover size of a given graph using binary search." }, { "code": null, "e": 1333, "s": 1187, "text": "Minimum vertex cover is a set of vertices of the given graph such that every edge in the graph is incident of either of the vertices in that set." }, { "code": null, "e": 1361, "s": 1333, "text": "For example, take the graph" }, { "code": null, "e": 1410, "s": 1361, "text": "2 ---- 4 ---- 6\n| |\n| |\n| |\n3 ---- 5" }, { "code": null, "e": 1548, "s": 1410, "text": "Here, the minimum vertex cover involves vertices 3 and 4. All the edges of the graphs are incident on either 3 or 4 vertice of the graph." }, { "code": null, "e": 1559, "s": 1548, "text": " Live Demo" }, { "code": null, "e": 3240, "s": 1559, "text": "#include<bits/stdc++.h>\nusing namespace std;\n#define max 15\n//array to store graph\nbool arr[max][max];\n//check if minimum vertex cover exists\nbool check_cover(int V, int k, int E) {\n int set = (1 << k) - 1;\n int limit = (1 << V);\n //to mark the edges of size 'k'\n bool vis[max][max];\n while (set < limit) {\n //resetting the vertex cover for each iteration\n memset(vis, 0, sizeof vis);\n int count = 0;\n //checking the values which has a high value\n for (int j = 1, v = 1 ; j < limit ; j = j << 1, v++) {\n if (set & j) {\n //marking the edges visited\n for (int k = 1 ; k <= V ; k++) {\n if (arr[v][k] && !vis[v][k]) {\n vis[v][k] = 1;\n vis[k][v] = 1;\n count++;\n }\n }\n }\n }\n //if all the edges are covered\n if (count == E)\n return true;\n int c = set & -set;\n int r = set + c;\n set = (((r^set) >> 2) / c) | r;\n }\n return false;\n}\n//to find minimum vertex cover\nint find_cover(int n, int m) {\n //performing binary search\n int left = 1, right = n;\n while (right > left){\n int mid = (left + right) >> 1;\n if (check_cover(n, mid, m) == false)\n left = mid + 1;\n else\n right = mid;\n }\n return left;\n}\n//inserting edge in the graph\nvoid add_edge(int u, int v) {\n arr[u][v] = 1;\n arr[v][u] = 1;\n}\nint main() {\n memset(arr, 0, sizeof arr);\n int V = 6, E = 5;\n add_edge(2, 3);\n add_edge(2, 4);\n add_edge(3, 5);\n add_edge(4, 5);\n add_edge(4, 6);\n cout << \"Size of Minimum Vertex Cover : \" << find_cover(V, E) << endl;\n return 0;\n}" }, { "code": null, "e": 3273, "s": 3240, "text": "Size of Minimum Vertex Cover : 2" } ]
Flashback Queries - GeeksforGeeks
24 May, 2020 Flashback Query allows users to see the view of past data, If in case some data or table is being deleted by the user, then the flashback query provides us an opportunity to view that data again and perform manipulations over it. In flashback queries we have an concept of flash area, in flash area we store the deleted data which can be viewed if needed in future. To use the feature of flashback query, our server must be configured according to automatic undo management.If our system supports the traditional approach of rollback then we can not perform flashback query on such systems. We can enable the flashback query using the package DBMS_FLASHBACK. This package enables us to view the data in past by specifying the System change number or the exact time in the past. How to use DBMS_FLASHBACK : EXECUTE Dbms_Flashback.Enable_At_System_Change_Number(647392649); EXECUTE Dbms_Flashback.Enable_At_Time('19-APR-2020 11:00:00); Example of Flashback Query :If we want to view a past data which is being deleted by mistake.The data consists of students table and it is being deleted at 11:05 AM on 19-APR-2020.To access the data we can use flashback query either by giving exact time or by mentioning the system change number. Limitations Flashback Query : Flashback query only works on those systems which supports automatic undo management.Systems having traditional approach of rollback does not supports flashback query.We can not use DDL (Data Definition Language) or DML (Data Manipulation Language) while performing flashback query.Flashback query does not reverse the DDL(Data Definition Language) commands.Flashback query can perform manipulations in DDL(Data Definition Language) commands.We can not apply flashback queries on functions, Packages, Procedures and triggers. Flashback query only works on those systems which supports automatic undo management. Systems having traditional approach of rollback does not supports flashback query. We can not use DDL (Data Definition Language) or DML (Data Manipulation Language) while performing flashback query. Flashback query does not reverse the DDL(Data Definition Language) commands. Flashback query can perform manipulations in DDL(Data Definition Language) commands. We can not apply flashback queries on functions, Packages, Procedures and triggers. DBMS-SQL DBMS SQL Write From Home DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS What is Temporary Table in SQL? Conflict Serializability in DBMS KDD Process in Data Mining SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 25549, "s": 25521, "text": "\n24 May, 2020" }, { "code": null, "e": 25779, "s": 25549, "text": "Flashback Query allows users to see the view of past data, If in case some data or table is being deleted by the user, then the flashback query provides us an opportunity to view that data again and perform manipulations over it." }, { "code": null, "e": 25915, "s": 25779, "text": "In flashback queries we have an concept of flash area, in flash area we store the deleted data which can be viewed if needed in future." }, { "code": null, "e": 26140, "s": 25915, "text": "To use the feature of flashback query, our server must be configured according to automatic undo management.If our system supports the traditional approach of rollback then we can not perform flashback query on such systems." }, { "code": null, "e": 26327, "s": 26140, "text": "We can enable the flashback query using the package DBMS_FLASHBACK. This package enables us to view the data in past by specifying the System change number or the exact time in the past." }, { "code": null, "e": 26355, "s": 26327, "text": "How to use DBMS_FLASHBACK :" }, { "code": null, "e": 26484, "s": 26355, "text": "EXECUTE Dbms_Flashback.Enable_At_System_Change_Number(647392649);\nEXECUTE Dbms_Flashback.Enable_At_Time('19-APR-2020 11:00:00); " }, { "code": null, "e": 26781, "s": 26484, "text": "Example of Flashback Query :If we want to view a past data which is being deleted by mistake.The data consists of students table and it is being deleted at 11:05 AM on 19-APR-2020.To access the data we can use flashback query either by giving exact time or by mentioning the system change number." }, { "code": null, "e": 26811, "s": 26781, "text": "Limitations Flashback Query :" }, { "code": null, "e": 27337, "s": 26811, "text": "Flashback query only works on those systems which supports automatic undo management.Systems having traditional approach of rollback does not supports flashback query.We can not use DDL (Data Definition Language) or DML (Data Manipulation Language) while performing flashback query.Flashback query does not reverse the DDL(Data Definition Language) commands.Flashback query can perform manipulations in DDL(Data Definition Language) commands.We can not apply flashback queries on functions, Packages, Procedures and triggers." }, { "code": null, "e": 27423, "s": 27337, "text": "Flashback query only works on those systems which supports automatic undo management." }, { "code": null, "e": 27506, "s": 27423, "text": "Systems having traditional approach of rollback does not supports flashback query." }, { "code": null, "e": 27622, "s": 27506, "text": "We can not use DDL (Data Definition Language) or DML (Data Manipulation Language) while performing flashback query." }, { "code": null, "e": 27699, "s": 27622, "text": "Flashback query does not reverse the DDL(Data Definition Language) commands." }, { "code": null, "e": 27784, "s": 27699, "text": "Flashback query can perform manipulations in DDL(Data Definition Language) commands." }, { "code": null, "e": 27868, "s": 27784, "text": "We can not apply flashback queries on functions, Packages, Procedures and triggers." }, { "code": null, "e": 27877, "s": 27868, "text": "DBMS-SQL" }, { "code": null, "e": 27882, "s": 27877, "text": "DBMS" }, { "code": null, "e": 27886, "s": 27882, "text": "SQL" }, { "code": null, "e": 27902, "s": 27886, "text": "Write From Home" }, { "code": null, "e": 27907, "s": 27902, "text": "DBMS" }, { "code": null, "e": 27911, "s": 27907, "text": "SQL" }, { "code": null, "e": 28009, "s": 27911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28026, "s": 28009, "text": "Deadlock in DBMS" }, { "code": null, "e": 28067, "s": 28026, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 28099, "s": 28067, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28132, "s": 28099, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 28159, "s": 28132, "text": "KDD Process in Data Mining" }, { "code": null, "e": 28201, "s": 28159, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 28245, "s": 28201, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 28266, "s": 28245, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 28332, "s": 28266, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Detecting Disaster from Tweets (Classical ML and LSTM Approach) | by Mazi Boustani | Towards Data Science
In this article, I am going to apply two different approaches to the classification task. I will first apply a classic machine learning classification algorithm using Gradient Boosting Classifier. Later in the code, I will use the LSTM technique to train an RNN model. As we are dealing with tweets then this is an NLP task and I will share some techniques so you will get more familiar with some common steps in most NLP projects. I will use the data from the Kaggle challenge called “Natural Language Processing with Disaster Tweets”. You can find the “train.csv” file under the “Data” section of the link below. www.kaggle.com Dataset has 5 columns. Column “target” is the label column which means I am going to train a model that can predict the value of column “target” using other columns such as “text”, “location” and “keyword”. Now first let’s understand what each column means: id - a unique identifier for each tweet text - the text of the tweet location - the location the tweet was sent from (may be blank) keyword - a particular keyword from the tweet (may be blank) target - in train.csv only, this denotes whether a tweet is about a real disaster (1) or not (0) For this task, I will be using libraries such as Sklearn and Keras for training classifier models. Sklearn is being used for training a model using Gradient Boosting Classifier and Keras is being used for training an LSTM model. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport reimport nltk nltk.download('stopwords')from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize from nltk.stem import SnowballStemmerfrom sklearn import model_selection, metrics, preprocessing, ensemble, model_selection, metricsfrom sklearn.feature_extraction.text import CountVectorizerimport tensorflow as tffrom tensorflow.keras.models import Modelfrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom tensorflow.keras.layers import Conv1D, Bidirectional, LSTM, Dense, Dropout, Inputfrom tensorflow.keras.optimizers import Adam For this task, we only use ‘train.csv’ and will break it down into two parts of the train and the test dataset. I am going to load the data to Pandas Dataframe and take a look at the first couple of rows. # Rreading train datasetfile_path = "./train.csv"raw_data = pd.read_csv(file_path)print("Data points count: ", raw_data['id'].count())raw_data.head() First, I would like to get more familiar with datasets to understand the features (columns). Column “target” is a column that our model is going to learn to predict. As it has only two unique values of 0 and 1 therefore this is a binary classification task. I would like to know the radio of the tweets labeled as 0 vs 1 so let’s plot data based on column “target”. As you can see there are more data points with the label 0 meaning tweets that are not disaster tweets and fewer data points with the label 1 which is tweets that are related to a disaster. Usually, for data that has some skewed labels, it is recommended to use an F-score instead of accuracy for model evaluation, we will address that at the end of this article. Next, I would like to know how is the missing data points in our dataset for each column. The heatmap below shows that the column “keyword” has very few missing data points and I will fill the missing data points and use this column as a feature. Column “location” has very missing data and the quality of data is very bad. It has values that are not related to location. So I decided not to use this column and drop it. Column “text” which is the main column that has the actual tweet needs to be processed and get cleaned. It has no missing data. I have also noticed that there are some tweets that contain less than 3 words and I think two words sentences might not be able to transfer the knowledge very well. So to get a sense of the number of words sentences are made of I want to look at the histogram of word count per sentence. As we can see the majority of tweets are between 11 to 19 words, so I have decided to remove tweets with less than 2 words. I believe sentences with 3 words can say enough about the tweet. It might be a good idea to also remove tweets with more than 25–30 words as they might slow down the training time. Common steps for data cleaning on the NLP task dealing with tweets are removing special characters, removing stop words, removing URLs, removing numbers, and doing word stemming. But let’s first get more familiar with some NLP data preprocessing concepts: Vectorization: Word vectorization is a technique of mapping words to real numbers, or better say vector of real numbers. I have used vectorization from both Sklearn and Keras libraries. Tokenization: Tokenization is the task of breaking a phrase which can be anything such as a sentence, a paragraph, or just a text into smaller sections such as a series of words, a series of characters, or a series of subwords, and they are called tokens. One use of tokenization is to generate tokens from a text and later convert tokens to numbers (vectorization). Padding: Neural network models require to have inputs to have the same shape and same size, meaning all tweets that are inputted into the model one by one has to have exact same length, that is what padding is useful here. Every tweet in the dataset has a different number of words, we will set a maximum number of words for each tweet, if a tweet is longer then we can drop some words if the tweet has fewer words than the max we can fill either beginning or end of the tweet with fix value such as ‘0’. Stemming: The task of stemming is to reduce extra characters from a word to its root or base of a word. For example, stemming both words “working” and “worked” becomes “work”. I used Snowball Stemmer which is a stemming algorithm (also known as the Porter2 stemming algorithm). It is a better version of the Porter Stemmer since some issues were fixed in this stemmer. Word Embedding: A word embedding is a learned representation for text where words that have the same meaning have a similar representation. Each word is mapped to one vector and the vector values are learned in a way that resembles a neural network. Now let’s look at the entire data cleaning code: def clean_text(each_text): # remove URL from text each_text_no_url = re.sub(r"http\S+", "", each_text) # remove numbers from text text_no_num = re.sub(r'\d+', '', each_text_no_url) # tokenize each text word_tokens = word_tokenize(text_no_num) # remove sptial character clean_text = [] for word in word_tokens: clean_text.append("".join([e for e in word if e.isalnum()])) # remove stop words and lower text_with_no_stop_word = [w.lower() for w in clean_text if not w in stop_words] # do stemming stemmed_text = [stemmer.stem(w) for w in text_with_no_stop_word] return " ".join(" ".join(stemmed_text).split())raw_data['clean_text'] = raw_data['text'].apply(lambda x: clean_text(x) )raw_data['keyword'] = raw_data['keyword'].fillna("none")raw_data['clean_keyword'] = raw_data['keyword'].apply(lambda x: clean_text(x) ) To be able to use both “text” and “keyword” columns there are various approaches to apply but one simple approach that I have applied was to combine both of these two features into a new feature called “keyword_text” # Combine column 'clean_keyword' and 'clean_text' into oneraw_data['keyword_text'] = raw_data['clean_keyword'] + " " + raw_data["clean_text"] I have used Sklearn's “train_test_split” function to do a train and test split with data shuffling. feature = "keyword_text"label = "target"# split train and testX_train, X_test,y_train, y_test = model_selection.train_test_split(raw_data[feature],raw_data[label],test_size=0.3,random_state=0,shuffle=True) As I already mentioned about vectorization we have to convert text to numbers as machine learning models can only work with a number so we use “Countervectorize” here. We do fit and transform on train data and only transform on test data. Make sure there is no fitting happens on test data. # Vectorize textvectorizer = CountVectorizer()X_train_GBC = vectorizer.fit_transform(X_train_GBC)x_test_GBC = vectorizer.transform(x_test_GBC) Gradient Boosting Classifier is a machine learning algorithm that combines many weak learning models such as decision trees together to create a strong predictive model. model = ensemble.GradientBoostingClassifier(learning_rate=0.1, n_estimators=2000, max_depth=9, min_samples_split=6, min_samples_leaf=2, max_features=8, subsample=0.9)model.fit(X_train_GBC, y_train) A good metric to evaluate the performance of our model is F-score. Before calculating F-score let’s get familiar with Precision and Recall. Precision: Out of data points we correctly labeled positive, how many we labeled positive correctly. Recall: Out of data points we correctly labeled positive, how many actually are positive. F-score: is the harmonic mean of the recall and precision. # Evaluate the modelpredicted_prob = model.predict_proba(x_test_GBC)[:,1]predicted = model.predict(x_test_GBC)accuracy = metrics.accuracy_score(predicted, y_test)print("Test accuracy: ", accuracy)print(metrics.classification_report(y_test, predicted, target_names=["0", "1"]))print("Test F-scoare: ", metrics.f1_score(y_test, predicted))Test accuracy: 0.7986784140969163 precision recall f1-score support 0 0.79 0.88 0.83 1309 1 0.81 0.69 0.74 961 accuracy 0.80 2270 macro avg 0.80 0.78 0.79 2270weighted avg 0.80 0.80 0.80 2270Test F-scoare: 0.7439775910364146 A confusion matrix is a table that shows the performance of the classification model in comparison to two classes. As we can see in the plot our model had a better performance on detecting target value “0” than target value “1”. LSTM stands for Long Short Term Memory network is a kind of RNN (Recurrent Neural Network) that is capable of learning long-term dependencies and they can remember information for a long period of time as designed with an internal memory system. I have talked about word embedding above now it is time to use that for our LSTM approach. I have used GloVe embedding from Stanford which you can download from here. After we read the GloVe embedding file then we create an embedding layer using Keras. # Read word embeddingsembeddings_index = {}with open(path_to_glove_file) as f: for line in f: word, coefs = line.split(maxsplit=1) coefs = np.fromstring(coefs, "f", sep=" ") embeddings_index[word] = coefsprint("Found %s word vectors." % len(embeddings_index))# Define embedding layer in Kerasembedding_matrix = np.zeros((vocab_size, embedding_dim))for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector embedding_layer = tf.keras.layers.Embedding(vocab_size,embedding_dim,weights[embedding_matrix],input_length=sequence_len,trainable=False) For the LSTM model, I have started with an embedding layer to generate an embedding vector for each input sequence. Then I used a convolution model to lower the number of features followed by a bidirectional LSTM layer. The last layer is a dense layer. Because it is a binary classification we use sigmoid as an activation function. # Define model architecturesequence_input = Input(shape=(sequence_len, ), dtype='int32')embedding_sequences = embedding_layer(sequence_input)x = Conv1D(128, 5, activation='relu')(embedding_sequences)x = Bidirectional(LSTM(128, dropout=0.5, recurrent_dropout=0.2))(x)x = Dense(512, activation='relu')(x)x = Dropout(0.5)(x)x = Dense(512, activation='relu')(x)outputs = Dense(1, activation='sigmoid')(x)model = Model(sequence_input, outputs)model.summary() For model optimization, I have used the Adam optimization with binary_crossentropy as a loss function. # Optimize the modelmodel.compile(optimizer=Adam(learning_rate=learning_rate), loss='binary_crossentropy', metrics=['accuracy']) After the model training is done I wanted to see the Learning Curve of train accuracy and loss. The plot shows as model accuracy is increasing and the loss is decreasing as expected over each epoch. Now I have trained the model so it is time to evaluate its performance of the model. I will get the model accuracy and F-score for test data. Because the prediction value is a float between 0 and 1, I used 0.5 as a threshold to separate “0” and “1”. #Evaluate the modelpredicted = model.predict(X_test, verbose=1, batch_size=10000)y_predicted = [1 if each > 0.5 else 0 for each in predicted]score, test_accuracy = model.evaluate(X_test, y_test, batch_size=10000)print("Test Accuracy: ", test_accuracy)print(metrics.classification_report(list(y_test), y_predicted))Test Accuracy: 0.7726872 precision recall f1-score support 0 0.78 0.84 0.81 1309 1 0.76 0.68 0.72 961 accuracy 0.77 2270 macro avg 0.77 0.76 0.76 2270weighted avg 0.77 0.77 0.77 2270 As we can see in the Confusion matrix the RNN approach performed very similarly to the Gradient Boosting Classifier approach. The model did a better job at detecting “0” than detecting “1”. As you can see the output of both approaches were very close to each other. Gradient Boosting classifier trained much faster than an LSTM model. There are many ways to improve the model's performance such as modifying input data, applying different training approaches, or using hyperparameter search algorithms such as GridSearch or RandomizedSearch to find the best values for hyperparameters. You can find the entire code here:
[ { "code": null, "e": 603, "s": 171, "text": "In this article, I am going to apply two different approaches to the classification task. I will first apply a classic machine learning classification algorithm using Gradient Boosting Classifier. Later in the code, I will use the LSTM technique to train an RNN model. As we are dealing with tweets then this is an NLP task and I will share some techniques so you will get more familiar with some common steps in most NLP projects." }, { "code": null, "e": 786, "s": 603, "text": "I will use the data from the Kaggle challenge called “Natural Language Processing with Disaster Tweets”. You can find the “train.csv” file under the “Data” section of the link below." }, { "code": null, "e": 801, "s": 786, "text": "www.kaggle.com" }, { "code": null, "e": 1059, "s": 801, "text": "Dataset has 5 columns. Column “target” is the label column which means I am going to train a model that can predict the value of column “target” using other columns such as “text”, “location” and “keyword”. Now first let’s understand what each column means:" }, { "code": null, "e": 1099, "s": 1059, "text": "id - a unique identifier for each tweet" }, { "code": null, "e": 1128, "s": 1099, "text": "text - the text of the tweet" }, { "code": null, "e": 1191, "s": 1128, "text": "location - the location the tweet was sent from (may be blank)" }, { "code": null, "e": 1252, "s": 1191, "text": "keyword - a particular keyword from the tweet (may be blank)" }, { "code": null, "e": 1349, "s": 1252, "text": "target - in train.csv only, this denotes whether a tweet is about a real disaster (1) or not (0)" }, { "code": null, "e": 1578, "s": 1349, "text": "For this task, I will be using libraries such as Sklearn and Keras for training classifier models. Sklearn is being used for training a model using Gradient Boosting Classifier and Keras is being used for training an LSTM model." }, { "code": null, "e": 2295, "s": 1578, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport reimport nltk nltk.download('stopwords')from nltk.corpus import stopwordsfrom nltk.tokenize import word_tokenize from nltk.stem import SnowballStemmerfrom sklearn import model_selection, metrics, preprocessing, ensemble, model_selection, metricsfrom sklearn.feature_extraction.text import CountVectorizerimport tensorflow as tffrom tensorflow.keras.models import Modelfrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom tensorflow.keras.layers import Conv1D, Bidirectional, LSTM, Dense, Dropout, Inputfrom tensorflow.keras.optimizers import Adam" }, { "code": null, "e": 2500, "s": 2295, "text": "For this task, we only use ‘train.csv’ and will break it down into two parts of the train and the test dataset. I am going to load the data to Pandas Dataframe and take a look at the first couple of rows." }, { "code": null, "e": 2650, "s": 2500, "text": "# Rreading train datasetfile_path = \"./train.csv\"raw_data = pd.read_csv(file_path)print(\"Data points count: \", raw_data['id'].count())raw_data.head()" }, { "code": null, "e": 3016, "s": 2650, "text": "First, I would like to get more familiar with datasets to understand the features (columns). Column “target” is a column that our model is going to learn to predict. As it has only two unique values of 0 and 1 therefore this is a binary classification task. I would like to know the radio of the tweets labeled as 0 vs 1 so let’s plot data based on column “target”." }, { "code": null, "e": 3380, "s": 3016, "text": "As you can see there are more data points with the label 0 meaning tweets that are not disaster tweets and fewer data points with the label 1 which is tweets that are related to a disaster. Usually, for data that has some skewed labels, it is recommended to use an F-score instead of accuracy for model evaluation, we will address that at the end of this article." }, { "code": null, "e": 3929, "s": 3380, "text": "Next, I would like to know how is the missing data points in our dataset for each column. The heatmap below shows that the column “keyword” has very few missing data points and I will fill the missing data points and use this column as a feature. Column “location” has very missing data and the quality of data is very bad. It has values that are not related to location. So I decided not to use this column and drop it. Column “text” which is the main column that has the actual tweet needs to be processed and get cleaned. It has no missing data." }, { "code": null, "e": 4217, "s": 3929, "text": "I have also noticed that there are some tweets that contain less than 3 words and I think two words sentences might not be able to transfer the knowledge very well. So to get a sense of the number of words sentences are made of I want to look at the histogram of word count per sentence." }, { "code": null, "e": 4522, "s": 4217, "text": "As we can see the majority of tweets are between 11 to 19 words, so I have decided to remove tweets with less than 2 words. I believe sentences with 3 words can say enough about the tweet. It might be a good idea to also remove tweets with more than 25–30 words as they might slow down the training time." }, { "code": null, "e": 4778, "s": 4522, "text": "Common steps for data cleaning on the NLP task dealing with tweets are removing special characters, removing stop words, removing URLs, removing numbers, and doing word stemming. But let’s first get more familiar with some NLP data preprocessing concepts:" }, { "code": null, "e": 4793, "s": 4778, "text": "Vectorization:" }, { "code": null, "e": 4964, "s": 4793, "text": "Word vectorization is a technique of mapping words to real numbers, or better say vector of real numbers. I have used vectorization from both Sklearn and Keras libraries." }, { "code": null, "e": 4978, "s": 4964, "text": "Tokenization:" }, { "code": null, "e": 5331, "s": 4978, "text": "Tokenization is the task of breaking a phrase which can be anything such as a sentence, a paragraph, or just a text into smaller sections such as a series of words, a series of characters, or a series of subwords, and they are called tokens. One use of tokenization is to generate tokens from a text and later convert tokens to numbers (vectorization)." }, { "code": null, "e": 5340, "s": 5331, "text": "Padding:" }, { "code": null, "e": 5836, "s": 5340, "text": "Neural network models require to have inputs to have the same shape and same size, meaning all tweets that are inputted into the model one by one has to have exact same length, that is what padding is useful here. Every tweet in the dataset has a different number of words, we will set a maximum number of words for each tweet, if a tweet is longer then we can drop some words if the tweet has fewer words than the max we can fill either beginning or end of the tweet with fix value such as ‘0’." }, { "code": null, "e": 5846, "s": 5836, "text": "Stemming:" }, { "code": null, "e": 6012, "s": 5846, "text": "The task of stemming is to reduce extra characters from a word to its root or base of a word. For example, stemming both words “working” and “worked” becomes “work”." }, { "code": null, "e": 6205, "s": 6012, "text": "I used Snowball Stemmer which is a stemming algorithm (also known as the Porter2 stemming algorithm). It is a better version of the Porter Stemmer since some issues were fixed in this stemmer." }, { "code": null, "e": 6221, "s": 6205, "text": "Word Embedding:" }, { "code": null, "e": 6455, "s": 6221, "text": "A word embedding is a learned representation for text where words that have the same meaning have a similar representation. Each word is mapped to one vector and the vector values are learned in a way that resembles a neural network." }, { "code": null, "e": 6504, "s": 6455, "text": "Now let’s look at the entire data cleaning code:" }, { "code": null, "e": 7383, "s": 6504, "text": "def clean_text(each_text): # remove URL from text each_text_no_url = re.sub(r\"http\\S+\", \"\", each_text) # remove numbers from text text_no_num = re.sub(r'\\d+', '', each_text_no_url) # tokenize each text word_tokens = word_tokenize(text_no_num) # remove sptial character clean_text = [] for word in word_tokens: clean_text.append(\"\".join([e for e in word if e.isalnum()])) # remove stop words and lower text_with_no_stop_word = [w.lower() for w in clean_text if not w in stop_words] # do stemming stemmed_text = [stemmer.stem(w) for w in text_with_no_stop_word] return \" \".join(\" \".join(stemmed_text).split())raw_data['clean_text'] = raw_data['text'].apply(lambda x: clean_text(x) )raw_data['keyword'] = raw_data['keyword'].fillna(\"none\")raw_data['clean_keyword'] = raw_data['keyword'].apply(lambda x: clean_text(x) )" }, { "code": null, "e": 7600, "s": 7383, "text": "To be able to use both “text” and “keyword” columns there are various approaches to apply but one simple approach that I have applied was to combine both of these two features into a new feature called “keyword_text”" }, { "code": null, "e": 7742, "s": 7600, "text": "# Combine column 'clean_keyword' and 'clean_text' into oneraw_data['keyword_text'] = raw_data['clean_keyword'] + \" \" + raw_data[\"clean_text\"]" }, { "code": null, "e": 7842, "s": 7742, "text": "I have used Sklearn's “train_test_split” function to do a train and test split with data shuffling." }, { "code": null, "e": 8048, "s": 7842, "text": "feature = \"keyword_text\"label = \"target\"# split train and testX_train, X_test,y_train, y_test = model_selection.train_test_split(raw_data[feature],raw_data[label],test_size=0.3,random_state=0,shuffle=True)" }, { "code": null, "e": 8339, "s": 8048, "text": "As I already mentioned about vectorization we have to convert text to numbers as machine learning models can only work with a number so we use “Countervectorize” here. We do fit and transform on train data and only transform on test data. Make sure there is no fitting happens on test data." }, { "code": null, "e": 8482, "s": 8339, "text": "# Vectorize textvectorizer = CountVectorizer()X_train_GBC = vectorizer.fit_transform(X_train_GBC)x_test_GBC = vectorizer.transform(x_test_GBC)" }, { "code": null, "e": 8652, "s": 8482, "text": "Gradient Boosting Classifier is a machine learning algorithm that combines many weak learning models such as decision trees together to create a strong predictive model." }, { "code": null, "e": 9152, "s": 8652, "text": "model = ensemble.GradientBoostingClassifier(learning_rate=0.1, n_estimators=2000, max_depth=9, min_samples_split=6, min_samples_leaf=2, max_features=8, subsample=0.9)model.fit(X_train_GBC, y_train)" }, { "code": null, "e": 9292, "s": 9152, "text": "A good metric to evaluate the performance of our model is F-score. Before calculating F-score let’s get familiar with Precision and Recall." }, { "code": null, "e": 9393, "s": 9292, "text": "Precision: Out of data points we correctly labeled positive, how many we labeled positive correctly." }, { "code": null, "e": 9483, "s": 9393, "text": "Recall: Out of data points we correctly labeled positive, how many actually are positive." }, { "code": null, "e": 9542, "s": 9483, "text": "F-score: is the harmonic mean of the recall and precision." }, { "code": null, "e": 10266, "s": 9542, "text": "# Evaluate the modelpredicted_prob = model.predict_proba(x_test_GBC)[:,1]predicted = model.predict(x_test_GBC)accuracy = metrics.accuracy_score(predicted, y_test)print(\"Test accuracy: \", accuracy)print(metrics.classification_report(y_test, predicted, target_names=[\"0\", \"1\"]))print(\"Test F-scoare: \", metrics.f1_score(y_test, predicted))Test accuracy: 0.7986784140969163 precision recall f1-score support 0 0.79 0.88 0.83 1309 1 0.81 0.69 0.74 961 accuracy 0.80 2270 macro avg 0.80 0.78 0.79 2270weighted avg 0.80 0.80 0.80 2270Test F-scoare: 0.7439775910364146" }, { "code": null, "e": 10495, "s": 10266, "text": "A confusion matrix is a table that shows the performance of the classification model in comparison to two classes. As we can see in the plot our model had a better performance on detecting target value “0” than target value “1”." }, { "code": null, "e": 10741, "s": 10495, "text": "LSTM stands for Long Short Term Memory network is a kind of RNN (Recurrent Neural Network) that is capable of learning long-term dependencies and they can remember information for a long period of time as designed with an internal memory system." }, { "code": null, "e": 10994, "s": 10741, "text": "I have talked about word embedding above now it is time to use that for our LSTM approach. I have used GloVe embedding from Stanford which you can download from here. After we read the GloVe embedding file then we create an embedding layer using Keras." }, { "code": null, "e": 11677, "s": 10994, "text": "# Read word embeddingsembeddings_index = {}with open(path_to_glove_file) as f: for line in f: word, coefs = line.split(maxsplit=1) coefs = np.fromstring(coefs, \"f\", sep=\" \") embeddings_index[word] = coefsprint(\"Found %s word vectors.\" % len(embeddings_index))# Define embedding layer in Kerasembedding_matrix = np.zeros((vocab_size, embedding_dim))for word, i in word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector embedding_layer = tf.keras.layers.Embedding(vocab_size,embedding_dim,weights[embedding_matrix],input_length=sequence_len,trainable=False)" }, { "code": null, "e": 12010, "s": 11677, "text": "For the LSTM model, I have started with an embedding layer to generate an embedding vector for each input sequence. Then I used a convolution model to lower the number of features followed by a bidirectional LSTM layer. The last layer is a dense layer. Because it is a binary classification we use sigmoid as an activation function." }, { "code": null, "e": 12464, "s": 12010, "text": "# Define model architecturesequence_input = Input(shape=(sequence_len, ), dtype='int32')embedding_sequences = embedding_layer(sequence_input)x = Conv1D(128, 5, activation='relu')(embedding_sequences)x = Bidirectional(LSTM(128, dropout=0.5, recurrent_dropout=0.2))(x)x = Dense(512, activation='relu')(x)x = Dropout(0.5)(x)x = Dense(512, activation='relu')(x)outputs = Dense(1, activation='sigmoid')(x)model = Model(sequence_input, outputs)model.summary()" }, { "code": null, "e": 12567, "s": 12464, "text": "For model optimization, I have used the Adam optimization with binary_crossentropy as a loss function." }, { "code": null, "e": 12696, "s": 12567, "text": "# Optimize the modelmodel.compile(optimizer=Adam(learning_rate=learning_rate), loss='binary_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 12895, "s": 12696, "text": "After the model training is done I wanted to see the Learning Curve of train accuracy and loss. The plot shows as model accuracy is increasing and the loss is decreasing as expected over each epoch." }, { "code": null, "e": 13145, "s": 12895, "text": "Now I have trained the model so it is time to evaluate its performance of the model. I will get the model accuracy and F-score for test data. Because the prediction value is a float between 0 and 1, I used 0.5 as a threshold to separate “0” and “1”." }, { "code": null, "e": 13803, "s": 13145, "text": "#Evaluate the modelpredicted = model.predict(X_test, verbose=1, batch_size=10000)y_predicted = [1 if each > 0.5 else 0 for each in predicted]score, test_accuracy = model.evaluate(X_test, y_test, batch_size=10000)print(\"Test Accuracy: \", test_accuracy)print(metrics.classification_report(list(y_test), y_predicted))Test Accuracy: 0.7726872 precision recall f1-score support 0 0.78 0.84 0.81 1309 1 0.76 0.68 0.72 961 accuracy 0.77 2270 macro avg 0.77 0.76 0.76 2270weighted avg 0.77 0.77 0.77 2270" }, { "code": null, "e": 13993, "s": 13803, "text": "As we can see in the Confusion matrix the RNN approach performed very similarly to the Gradient Boosting Classifier approach. The model did a better job at detecting “0” than detecting “1”." }, { "code": null, "e": 14138, "s": 13993, "text": "As you can see the output of both approaches were very close to each other. Gradient Boosting classifier trained much faster than an LSTM model." }, { "code": null, "e": 14389, "s": 14138, "text": "There are many ways to improve the model's performance such as modifying input data, applying different training approaches, or using hyperparameter search algorithms such as GridSearch or RandomizedSearch to find the best values for hyperparameters." } ]
Tryit Editor v3.6 - Show Node.js Command Prompt
var events = require('events'); var eventEmitter = new events.EventEmitter(); ​ //Create an event handler: var myEventHandler = function () { console.log('I hear a scream!'); } ​ //Assign the eventhandler to an event:
[ { "code": null, "e": 32, "s": 0, "text": "var events = require('events');" }, { "code": null, "e": 78, "s": 32, "text": "var eventEmitter = new events.EventEmitter();" }, { "code": null, "e": 80, "s": 78, "text": "​" }, { "code": null, "e": 107, "s": 80, "text": "//Create an event handler:" }, { "code": null, "e": 142, "s": 107, "text": "var myEventHandler = function () {" }, { "code": null, "e": 177, "s": 142, "text": " console.log('I hear a scream!');" }, { "code": null, "e": 179, "s": 177, "text": "}" }, { "code": null, "e": 181, "s": 179, "text": "​" } ]
Why Final Class used in Java?
The final keyword is used with a class to create a final class. The final class cannot be inherited and so the final keyword is commonly used with a class to prevent inheritance. A program that demonstrates a final class in Java is given as follows: Live Demo final class A { private int a = 9; public void printA() { System.out.println("Value of a = " + a); } } public class Demo { public static void main(String args[]) { A obj = new A(); obj.printA(); } } Value of a = 9 Now let us understand the above program. The class A is a final class. This means that it cannot be inherited. It has a private data member a and a method printA() that displays the value of a. A code snippet which demonstrates this is as follows: final class A { private int a = 9; public void printA() { System.out.println("Value of a = " + a); } } In the main() method in class Demo, an object obj of final class A is created. Then printA() method is called. A code snippet which demonstrates this is as follows: public class Demo { public static void main(String args[]) { A obj = new A(); obj.printA(); } }
[ { "code": null, "e": 1241, "s": 1062, "text": "The final keyword is used with a class to create a final class. The final class cannot be inherited and so the final keyword is commonly used with a class to prevent inheritance." }, { "code": null, "e": 1312, "s": 1241, "text": "A program that demonstrates a final class in Java is given as follows:" }, { "code": null, "e": 1323, "s": 1312, "text": " Live Demo" }, { "code": null, "e": 1555, "s": 1323, "text": "final class A {\n private int a = 9;\n public void printA() {\n System.out.println(\"Value of a = \" + a);\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n A obj = new A();\n obj.printA();\n }\n}" }, { "code": null, "e": 1570, "s": 1555, "text": "Value of a = 9" }, { "code": null, "e": 1611, "s": 1570, "text": "Now let us understand the above program." }, { "code": null, "e": 1818, "s": 1611, "text": "The class A is a final class. This means that it cannot be inherited. It has a private data member a and a method printA() that displays the value of a. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 1936, "s": 1818, "text": "final class A {\n private int a = 9;\n public void printA() {\n System.out.println(\"Value of a = \" + a);\n }\n}" }, { "code": null, "e": 2101, "s": 1936, "text": "In the main() method in class Demo, an object obj of final class A is created. Then printA() method is called. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2215, "s": 2101, "text": "public class Demo {\n public static void main(String args[]) {\n A obj = new A();\n obj.printA();\n }\n}" } ]
Project: Modeling & Predicting of Churning Customers (in R) | by Jarar Zaidi | Towards Data Science
Table of Contents 1. Introduction 2. Data Wrangling 3. Exploratory Data Analysis 4. Modeling 5. References You have just been hired as a Data Scientist. A manager at the bank is disturbed with an alarming number of customers leaving their credit card services. You have been hired as a data scientist to predict who is gonna get leave their company so they can proactively go to the customer to provide them better services and turn customers’ decisions in the opposite direction. A data collector hands you this data to perform Data Analysis and wants you to examine trends & correlations within our data. We would like to do model & predict who will leave our companyNote: Exit Flag is the discrete target variable here for which we have to create the predictive model, but we will also use Credit Limit for another modeling example walkthrough for a continuous predictor. Prevent the loss of potential customer churn/turnover/attrition, by catching these features early; we can prevent further damage from being done Predict whether a customer will churn the company. This is a binary outcome. Positive (+) = 1, customer stays in companyNegative (-) = 0, customer exits the company Experiment with Classification Models & see which yields greatest accuracy. Examine trends & correlations within our data Determine which features are most important for a churning customer come up with a model that will best fit our data CLIENTNUM — (Feature, dbl,continuous) Client NumberCustomer_Age — (Feature, int,continuous) Age of the CustomerGender — (Feature, chr, discrete) Sex of the CustomerDependent_count — (Feature, int, continuous) number of dependents a user has. That is, how many people are dependent on a credit card user for financial support. A higher count tells us that the expenditures can be high.Education_Level — (Feature, char, discrete) Education Level of the CustomerMarital_Status — (Feature, char, discrete) Martial Status of the CustomerIncome_Category — (Feature, char, discrete) Income Category of CustomerCard_Category — (Feature, char, discrete) Card Category of CustomerCredit_Limit — (Feature, dbl,continuous) Client NumberAttrition_Flag — (Predictor, discrete, binary): Exited (customer exits the company) or Current (customer stays in company) CLIENTNUM — (Feature, dbl,continuous) Client Number Customer_Age — (Feature, int,continuous) Age of the Customer Gender — (Feature, chr, discrete) Sex of the Customer Dependent_count — (Feature, int, continuous) number of dependents a user has. That is, how many people are dependent on a credit card user for financial support. A higher count tells us that the expenditures can be high. Education_Level — (Feature, char, discrete) Education Level of the Customer Marital_Status — (Feature, char, discrete) Martial Status of the Customer Income_Category — (Feature, char, discrete) Income Category of Customer Card_Category — (Feature, char, discrete) Card Category of Customer Credit_Limit — (Feature, dbl,continuous) Client Number Attrition_Flag — (Predictor, discrete, binary): Exited (customer exits the company) or Current (customer stays in company) In Part 1 of 3 of Data Wrangling, we read in our data file & install all required libraries/packages for our project. We also examine if there are any problems with our dataset, & hence see that there are no issues. ```{r DataWrangling1}library(tidyverse)library(plyr)library(readr)library(dplyr)cc1 <- read_csv("BankChurners.csv") # original dataset#----------------------------#----------------------------problems(cc1) # no problems with cc1head(cc1)dim(cc1) # # returns dimensions;10127 rows 23 colcc1 %>% filter(!is.na(Income_Category))(is.na(cc1))glimpse(cc1)``` In Part 2 of 3 of Data Wrangling, we manipulate the data to get only the columns we want & to remove NA & Unknown values in our data. We also examine the dimensions & unique values for our discrete variables. 6 distinct discrete types for Income_Category :$60K — $80K, Less than $40K ,$80K — $120K ,$40K — $60K ,$120K + , Unknown 4 distinct discrete types for Marital_Status: Married, Single, Divorced, Unknown 4 distinct discrete types for Card_Category: Blue, Gold, Siler, Platinum Note: We will also remove any rows/entries with a “Unknown”/NA value. We see here we initally have 10,127 rows & 23 columns, but we truncate that too 8348 rows by 9 columns. ```{r DataWrangling2}# selected the columns we care aboutcc2 <- cc1 %>% select(Customer_Age,Gender,Dependent_count,Education_Level,Marital_Status,Income_Category,Card_Category,Credit_Limit, Attrition_Flag) %>% filter( !is.na(.))# see the head of ithead(cc2)dim(cc2) #dimensions 10127 rows 9 columns#(cc2 <- na.omit(cc2) ) # EXACt SAME as : %>% filter( !is.na(.))#----------------------------cc2 %>% group_by(Income_Category,Marital_Status)#----------------------------# Lets see which distinct types there are(distinct(cc2, Income_Category)) # 6 types:$60K - $80K, Less than $40K ,$80K - $120K ,$40K - $60K ,$120K + ,Unknown (distinct(cc2, Marital_Status)) # 4 types: Married, Single, Divorced, Unknown (distinct(cc2, Card_Category)) # 4 types: Blue, Gold, Siler, Platinum#----------------------------# Drop all the "unknown" rows from Marital_Status & Income_Category# 82x9, 82 rows must remove these rowscc3 <- cc2 %>% select(Customer_Age,Gender,Dependent_count,Education_Level,Marital_Status,Income_Category,Card_Category,Credit_Limit, Attrition_Flag) %>% filter(Marital_Status != "Unknown" , Income_Category != "Unknown",Education_Level !="Unknown")#----------------------------head(cc3)dim(cc3) #8348 rows by 9 cols#----------------------------``` In Part 3 of 3 Data Wrangling, we rename our predictor Column Attrition_Flag to Exited_Flag. We also rename the binary output values for this predictor from Existing Customer/Attrited Customer to Current/Exited, respectivley. We lastly, also see the cout of each discrete feature with our discrete predictor. ```{r DataWrangling3}#----------------------------#----------------------------#install.packages("dplyr")library(dplyr)# Rename Label Colum to Exited_FlagdataCC4 <- cc3 %>% rename(Exited_Flag = Attrition_Flag)#----------------------------#----------------------------dataCC4 <- cc3#Rename values dataCC4 $Attrition_Flag[dataCC4 $Attrition_Flag == "Existing Customer"] <- "Current"dataCC4 $Attrition_Flag[dataCC4 $Attrition_Flag == "Attrited Customer"] <- "Exited"#----------------------------#----------------------------(dataCC4 %>% group_by(Attrition_Flag) %>% summarize(meanAge= mean(Customer_Age), meanDepdent= mean(Dependent_count), meanCreditLim= mean(Credit_Limit)))#AKA: summarise_mean <- function(data, vars) { data %>% summarise(n = n(), across({{ vars }}, mean))}#dataCC4 %>% #group_by(Attrition_Flag) %>% # summarise_mean(where(is.numeric))#----------------------------#----------------------------#see the count of each(dataCC4 %>% select(Gender,Attrition_Flag) %>% group_by(Gender) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Education_Level) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Marital_Status) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Income_Category) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Card_Category) %>% count(Attrition_Flag) ) summary(dataCC4)``` Above, we can evidently see that Current Customers had higher mean credit limits than did churning customers. In part 1 of 2 in EDA, we reorder the Factor levels of certain discrete variables, because we want them to display in order in our graphs. We have 2 discrete variables plotted against each other, with 1 of the variables being a fill. We examine the count of each visually. ```{r EDA1}# 2 discrete var, but using 1 as a fill. # Count, with Y being Income Category, Fill is our ggplot(dataCC4 , aes(y = Income_Category)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) +theme(legend.position = "top") + theme_classic() + xlab("Count") + ylab("Income Category") + ggtitle(" Customer Status by Income" )+ labs(fill = "Customer Status")#----------------------------# RE-ODER factor levelsdataCC4$Education_Level <- factor(dataaa$Education_Level, levels = c("Uneducated","High School", "College", "Graduate", "Post-Graduate","Doctorate"))ggplot(dataCC4 , aes(y = Education_Level)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = "top") + theme_classic() + xlab("Count") + ylab("Education Level") + ggtitle("Customer Status by Education Level" ) + labs(fill = "Customer Status")#----------------------------ggplot(dataCC4 , aes(y = Marital_Status)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = "top") + theme_classic() + xlab("Count") + ylab("Martial Status") + ggtitle("Customer Status by Martial Status" )+ labs(fill = "Customer Status")#----------------------------ggplot(dataCC4 , aes(y = Card_Category)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = "top") + theme_classic() + xlab("Count") + ylab("Card Category") + ggtitle("Customer Status by Card Category" )+ labs(fill = "Customer Status")#----------------------------ggplot(dataCC4 , aes(y = Gender)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = "top") + theme_classic() + xlab("Count") + ylab("Gender") + ggtitle("Customer Status by Gender" )+ labs(fill = "Customer Status")#There are more samples of females in our dataset compared to males but the percentage of difference is not that significant so we can say that genders are uniformly distributed.#----------------------------``` In part 2 of 2 in EDA, we explore 2 violin plots with quantiles, a visualization for 2 discrete variables, & area distribution plot. ```{r EDA2}#----------------------------# Discrete X, Continous Y, Violin Plotsggplot(dataCC4 , aes(Attrition_Flag,Credit_Limit,color= Credit_Limit)) + geom_violin(draw_quantiles = c(0.25,0.5,0.75),colour="red",size=1.4) + theme_classic() +xlab("Income Category") + ylab("Credit Limit") + ggtitle("Customer Status by Credit Limit" ) + labs(fill = "Customer Status")# RE-ODER factor levelsdataCC4 $Income_Category <- factor(dataCC4 $Income_Category, levels = c("Less than $40K","$40K - $60K","$60K - $80K","$80K - $120K","$120K +"))ggplot(dataCC4 , aes(Income_Category,Credit_Limit,color= Credit_Limit)) + geom_violin(draw_quantiles = c(0.25,0.5,0.75),colour="blue",size=1) + theme_classic() +xlab("Income Category") + ylab("Credit Limit") + ggtitle("Income Category by Credit Limit" )#----------------------------# 2 discrete variables x,y#need to specify which group the proportion is to be calculated over.ggplot(dataCC4 , aes(Income_Category,Attrition_Flag, colour= after_stat(prop), size = after_stat(prop), group = Income_Category)) + geom_count() + scale_size_area() + theme_classic() +xlab("Income Category") + ylab("Status of Customer") + ggtitle("Customer Status by Income Proportion" )#----------------------------##library(plyr)#mu <- ddply(dataaa, "Exited_Flag", summarise, grp.mean=mean(Credit_Limit))#head(mu)#ggplot(dataCC4, aes(x=Credit_Limit, fill=Attrition_Flag)) + geom_area(stat ="bin") + xlab("Credit Limit")+ylab("Count") +ggtitle("Customer Status by Credit Limit " ) + labs(fill = "Customer Status")``` Quantiles can tell us a wide array of information. The 1st horizontal line tells us the 1st quantile, or the 25th percentile- the number that separates the lowest 25% of the group from the highest 75% of the credit limit. Next, the 2nd line is the Median, or 50th percentile — the number in the middle of the credit limit. Lastly, the 3rd line is the 3rd quartile, Q3, or 75th percentile — the number that separates the lowest 75% of the group from the highest 25% of the group. Quantiles are shown both in the violin plots above & below. We have only 16.07% of customers who have churned. Hence, it’s a bit difficult to train our model to predict churning customers. We will do our best with the data given, as with any model. Our goal in modeling is to provide a simple low-dimensional summary of a dataset.We use models to partition data into patterns and residuals. Fitted model is just the closest model from a family of models. Classification models are models that predict a categorical label. It will be interesting to study which characteristic(s) discriminates each category and to what extent. Predicting whether a customer will a customer will exit or stay with the company. Below we will use a logistic regression algorithm. First we must convert the non numeric variables (discrete variables) into factors. Factors are the data objects which are used to categorize the data and store it as levels. ```{r Modeling1}library(tidyverse)library(modelr)library(plyr)library(readr)library(dplyr)library(caret)# glimpse is from dplyr# output shows that the dataset has glimpse(dataCC4)# convert the non numeric into factors.names <- c(2,5,7,9) # col numbers that are charsdataCC4[,names] <- lapply(dataCC4[,names] , factor)``` ```{r Modeling2}#----------------------------# DATA PARTITIONING#----------------------------#build our model on the Train dataset & evaluate its performance on #the Test dataset# aka. holdout-validation approach to evaluating model performance.set.seed(100) # sets random seed for reproducibility of resultslibrary(caTools) # for data partioning# create the training and test datasets. The train dataset contains # 70 percent of the data (420 observations of 10 variables) while #the #test data contains the remaining 30 percent (180 observations #of 10 variables).spl = sample.split(dataCC4$Attrition_Flag, SplitRatio = 0.7)train = subset(dataCC4, spl==TRUE)test = subset(dataCC4, spl==FALSE)print(dim(train)) # 4957 rows/obs 9 cols/variablesprint(dim(test)) # 2124 rows/obs 9 cols/variables``` We fit the logistic regression model. The first step is to instantiate the algorithm. We declare binomial because 2 possible outcomes: exit/current. ```{r Modeling3}#----------------------------#BUILD, PREDICT & EVALUATE the Model#----------------------------# BUILD#----------------------------model_glm = glm(Attrition_Flag ~ . , family="binomial",data = train)summary(model_glm)# Baseline Accuracy #Let's evaluate the model further, # Since the majority class of the target (Y) variable has a #proportion of 0.84, the baseline accuracy is 84 percent.prop.table(table(train$Attrition_Flag))#Let's now evaluate the model performance on the training and test data, which should ideally be better than the baseline accuracy.# PREDICTIONS on the TRAIN setpredictTrain = predict(model_glm, data = train, type = "response")# confusion matrix w/ threshold of 0.5, #which means that for probability predictions >= 0.5, the #algorithm will predict the Current response for the Y #variable. table(train$Attrition_Flag, predictTrain >= 0.1) Evaluate:#prints the accuracy of the model on the training data, using the #confusion matrix, and the accuracy comes out to be 0 percent.(50+774)/nrow(test) #Accuracy - 84% (50+774)/2124-------------------------------------------------------------#We then repeat this process on the TEST data, and the accuracy #comes out to be 84 percent.# PREDICTIONS on the TEST setpredictTest = predict(model_glm, newdata = test, type = "response") Evaluate:# Confusion matrix on test settable(test$Attrition_Flag, predictTest >= 0.5)1790/nrow(test) #Accuracy - 84%``` The significance code ‘***’ in the above below output shows the relative importance of the feature variablesAIC estimates the relative amount of information lost by a given model:the less information a model loses, the higher the quality of that model. Lower AIC values indicate a better-fit model, You have learned techniques of building a classification model in R using the powerful logistic regression algorithm. The baseline accuracy for the training & test data was 84 percent. Overall, the logistic regression model is beating the baseline accuracy by a big margin on both the train and test datasets, and the results are very good. Below I will show you another way to model this, using SVM (Support Vector Machine). ```{r ModelAgain}unique(dataCC5$Attrition_Flag) #Levels: Current Exited# Encoding the target feature as factordataCC5$Attrition_Flag = factor(dataCC5$Attrition_Flag, levels = c(0, 1))# spliting datast into Train & Test Setinstall.packages('caTools')library(caTools) # for data partioningset.seed(123) #SEED#SPLITsplit = sample.split(dataCC5$Attrition_Flag, SplitRatio = 0.75)train_set = subset(dataCC5,split==TRUE) #TRAINtest_set = subset(dataCC5,split==FALSE) #TEST#FEATURE SCALING: agelibrary(caret)train_set[-9] = scale(train_set[-9])test_set[-9] = scale(test_set[-9])install.packages('e1071')library(e1071)model_glm = glm(Attrition_Flag ~ . , family="binomial",data = train)classifier = svm(formula= Attrition_Flag ~ ., data= train_set, type= 'C-classification', kernel = 'radial')# predicting Test Set Resultsy_pred = predict(classifier, newdata = train_set[-9])# making confusion matrixcm = table(test_set[, 3],y_pred)``` Confidence intervals are of interest in modeling because they are often used in model validation. Next, we consider the 95% confidence interval of Credit Limit.As the Credit Limit is greater than 0, we narrow the confidence interval.There are 91.75% data locates within the confidence interval. We will keep the corresponding records and store the rest in another variable rest.data for latter analysis. ```{r CI}mean.Credit_Limit <- mean(dataCC5$Credit_Limit)std.Credit_Limit <- sqrt(var(dataCC5$Credit_Limit))df = dim(dataCC5)[1] - 9conf.Credit_Limit <- mean.Credit_Limit + c(-1, 1) * qt(0.975, df) * std.Credit_Limit# As the CreditLimit is greater than 0, we narrow the confidence intervalconf.Credit_Limit[1] <- 0conf.Credit_Limit#There are 91.75% data locates within the confidence interval. We will keep the corresponding records and store the rest in another variable rest.data for later analysis.sum(dataCC5$Credit_Limit <= conf.Credit_Limit[2]) / dim(dataCC5)[1]#----------------------------##----------------------------rest.data <- dataCC5 %>% filter(Credit_Limit > conf.Credit_Limit[2])dataCC5 <- dataCC5 %>% filter(Credit_Limit <= conf.Credit_Limit[2]) %>% filter(Credit_Limit != 0)#We recall the historgrams of Credit Limitboxplot_credLim <- dataCC5 %>% ggplot() + geom_boxplot(aes(Credit_Limit))(boxplot_credLim)histplot <- dataCC5 %>% ggplot() + geom_histogram(aes(Credit_Limit))(histplot)#----------------------------##----------------------------#We consider a log-transofrmation to convert the distribution of the histogram to normal distribution. Right-skew.histplot <- dataCC5 %>% ggplot() + geom_histogram(aes(log(Credit_Limit)))(histplot)qqplot <- dataCC5 %>% ggplot() + geom_qq(aes(sample = log(Credit_Limit)))(qqplot)#It seems that normality exists. Great! There are 6 types of categorical variables.# Distrubution of Income Categoryp1 <- dataCC5 %>% ggplot() + geom_histogram(aes(Income_Category, fill = Income_Category), stat = "count")(p1)# Box Plots of Depdent count & Income Categoryp2 <- dataCC5 %>% ggplot() + geom_boxplot(aes(x = Dependent_count, y = Income_Category, color = Income_Category))(p2)``` #The following aims to build a model to predict the price. ## Evaluation We will use MSE as the criteria to measure the model performance. We Split 20% as test dataset and 80% as training dataset. ```{r RMSE}#Train and test split#Split 20% as test dataset and 80% as training dataset.### convert character to factordataCC5$Gender <-as.factor(dataCC5$Gender)# Splitset.seed(100)train.index <- sample(nrow(dataCC5), 0.7*nrow(dataCC5), replace = FALSE)train.set <- dataCC5[train.index, ]test.set <- dataCC5[-train.index, ]# build a model to predict the price. ## Evaluation: We will use MSE as the criteria to measure the model performance.RMSE <- function(true, pred){ residuals <- true - pred res <- sqrt(mean(residuals^2)) return(res)}----------#----------------------------#Linear regression#Linear regressoin is a kind of simple regression methods. It is easy to be conducted while it has some strict assumptions. The following code will perform the modeling process with check some assumptions. ### Multicolinearity#library(corrplot)#cor <- cor(dataCC5)#corrplot::corrplot(cor, method = 'ellipse', type = 'lower')#cor(dataCC5$Credit_Limit, dataCC5$Dependent_count)# IF data had more numeric values use this for # correlation plot: #M <- cor(dataCC5)#corrplot(cor(dataCC5), method = "circle")``` To recal: AIC estimates the relative amount of information lost by a given model: The less information a model loses, the higher the quality of that model. Thus, the lower AIC values indicate a better-fit model, ```{r AIC}AICs <- c()models <- c()start.model <- lm(Credit_Limit ~ Customer_Age, data = train.set)# summary(start.model) models <- append(models, as.character(start.model$call)[2])AICs <- append(AICs, AIC(start.model))# Add next varaibleupdate.model <- update(start.model, . ~ . + Gender)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add next varupdate.model <- update(update.model, . ~ . + Dependent_count)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add next varupdate.model <- update(update.model, . ~ . + Education_Level)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add next variableupdate.model <- update(update.model, . ~ . + Marital_Status)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add calculated_host_listings_countupdate.model <- update(update.model, . ~ . + Income_Category)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add last varupdate.model <- update(update.model, . ~ . + Card_Category)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))res <- data.frame( Model = models, AIC = AICs)knitr::kable(res)#----------------------------#----------------------------par(mfrow = c(3,1))plot(update.model, 1)plot(update.model, 2)plot(update.model, 3)``` The AIC table shows the best model is Credit_Limit ~ Customer_Age + Gender + Dependent_count + Education_Level + Marital_Status + Income_Category + Card_CategoryWith a AIC of 72870.02, we want the lowest AIC. ```{r LogLinearRegression}log.lm <- lm(log(Credit_Limit) ~ Customer_Age + Gender + Dependent_count + Education_Level + Marital_Status + Income_Category + Card_Category, data = dataCC5)summary(log.lm)``` Gender Male, Income Categories, and Silver Card Card Categories were highly significant with respect to our predictor of Credit Limit. Here is access to the data set & code from my GitHub page: https://github.com/jararzaidi/ModelingChurningCustomersR https://www.kaggle.com/sakshigoyal7/credit-card-customers Recommendations & comments are welcomed!
[ { "code": null, "e": 190, "s": 172, "text": "Table of Contents" }, { "code": null, "e": 206, "s": 190, "text": "1. Introduction" }, { "code": null, "e": 224, "s": 206, "text": "2. Data Wrangling" }, { "code": null, "e": 253, "s": 224, "text": "3. Exploratory Data Analysis" }, { "code": null, "e": 265, "s": 253, "text": "4. Modeling" }, { "code": null, "e": 279, "s": 265, "text": "5. References" }, { "code": null, "e": 1047, "s": 279, "text": "You have just been hired as a Data Scientist. A manager at the bank is disturbed with an alarming number of customers leaving their credit card services. You have been hired as a data scientist to predict who is gonna get leave their company so they can proactively go to the customer to provide them better services and turn customers’ decisions in the opposite direction. A data collector hands you this data to perform Data Analysis and wants you to examine trends & correlations within our data. We would like to do model & predict who will leave our companyNote: Exit Flag is the discrete target variable here for which we have to create the predictive model, but we will also use Credit Limit for another modeling example walkthrough for a continuous predictor." }, { "code": null, "e": 1192, "s": 1047, "text": "Prevent the loss of potential customer churn/turnover/attrition, by catching these features early; we can prevent further damage from being done" }, { "code": null, "e": 1357, "s": 1192, "text": "Predict whether a customer will churn the company. This is a binary outcome. Positive (+) = 1, customer stays in companyNegative (-) = 0, customer exits the company" }, { "code": null, "e": 1433, "s": 1357, "text": "Experiment with Classification Models & see which yields greatest accuracy." }, { "code": null, "e": 1479, "s": 1433, "text": "Examine trends & correlations within our data" }, { "code": null, "e": 1547, "s": 1479, "text": "Determine which features are most important for a churning customer" }, { "code": null, "e": 1596, "s": 1547, "text": "come up with a model that will best fit our data" }, { "code": null, "e": 2443, "s": 1596, "text": "CLIENTNUM — (Feature, dbl,continuous) Client NumberCustomer_Age — (Feature, int,continuous) Age of the CustomerGender — (Feature, chr, discrete) Sex of the CustomerDependent_count — (Feature, int, continuous) number of dependents a user has. That is, how many people are dependent on a credit card user for financial support. A higher count tells us that the expenditures can be high.Education_Level — (Feature, char, discrete) Education Level of the CustomerMarital_Status — (Feature, char, discrete) Martial Status of the CustomerIncome_Category — (Feature, char, discrete) Income Category of CustomerCard_Category — (Feature, char, discrete) Card Category of CustomerCredit_Limit — (Feature, dbl,continuous) Client NumberAttrition_Flag — (Predictor, discrete, binary): Exited (customer exits the company) or Current (customer stays in company)" }, { "code": null, "e": 2495, "s": 2443, "text": "CLIENTNUM — (Feature, dbl,continuous) Client Number" }, { "code": null, "e": 2556, "s": 2495, "text": "Customer_Age — (Feature, int,continuous) Age of the Customer" }, { "code": null, "e": 2610, "s": 2556, "text": "Gender — (Feature, chr, discrete) Sex of the Customer" }, { "code": null, "e": 2831, "s": 2610, "text": "Dependent_count — (Feature, int, continuous) number of dependents a user has. That is, how many people are dependent on a credit card user for financial support. A higher count tells us that the expenditures can be high." }, { "code": null, "e": 2907, "s": 2831, "text": "Education_Level — (Feature, char, discrete) Education Level of the Customer" }, { "code": null, "e": 2981, "s": 2907, "text": "Marital_Status — (Feature, char, discrete) Martial Status of the Customer" }, { "code": null, "e": 3053, "s": 2981, "text": "Income_Category — (Feature, char, discrete) Income Category of Customer" }, { "code": null, "e": 3121, "s": 3053, "text": "Card_Category — (Feature, char, discrete) Card Category of Customer" }, { "code": null, "e": 3176, "s": 3121, "text": "Credit_Limit — (Feature, dbl,continuous) Client Number" }, { "code": null, "e": 3299, "s": 3176, "text": "Attrition_Flag — (Predictor, discrete, binary): Exited (customer exits the company) or Current (customer stays in company)" }, { "code": null, "e": 3515, "s": 3299, "text": "In Part 1 of 3 of Data Wrangling, we read in our data file & install all required libraries/packages for our project. We also examine if there are any problems with our dataset, & hence see that there are no issues." }, { "code": null, "e": 3870, "s": 3515, "text": "```{r DataWrangling1}library(tidyverse)library(plyr)library(readr)library(dplyr)cc1 <- read_csv(\"BankChurners.csv\") # original dataset#----------------------------#----------------------------problems(cc1) # no problems with cc1head(cc1)dim(cc1) # # returns dimensions;10127 rows 23 colcc1 %>% filter(!is.na(Income_Category))(is.na(cc1))glimpse(cc1)```" }, { "code": null, "e": 4079, "s": 3870, "text": "In Part 2 of 3 of Data Wrangling, we manipulate the data to get only the columns we want & to remove NA & Unknown values in our data. We also examine the dimensions & unique values for our discrete variables." }, { "code": null, "e": 4355, "s": 4079, "text": "6 distinct discrete types for Income_Category :$60K — $80K, Less than $40K ,$80K — $120K ,$40K — $60K ,$120K + , Unknown 4 distinct discrete types for Marital_Status: Married, Single, Divorced, Unknown 4 distinct discrete types for Card_Category: Blue, Gold, Siler, Platinum" }, { "code": null, "e": 4425, "s": 4355, "text": "Note: We will also remove any rows/entries with a “Unknown”/NA value." }, { "code": null, "e": 4529, "s": 4425, "text": "We see here we initally have 10,127 rows & 23 columns, but we truncate that too 8348 rows by 9 columns." }, { "code": null, "e": 5789, "s": 4529, "text": "```{r DataWrangling2}# selected the columns we care aboutcc2 <- cc1 %>% select(Customer_Age,Gender,Dependent_count,Education_Level,Marital_Status,Income_Category,Card_Category,Credit_Limit, Attrition_Flag) %>% filter( !is.na(.))# see the head of ithead(cc2)dim(cc2) #dimensions 10127 rows 9 columns#(cc2 <- na.omit(cc2) ) # EXACt SAME as : %>% filter( !is.na(.))#----------------------------cc2 %>% group_by(Income_Category,Marital_Status)#----------------------------# Lets see which distinct types there are(distinct(cc2, Income_Category)) # 6 types:$60K - $80K, Less than $40K ,$80K - $120K ,$40K - $60K ,$120K + ,Unknown (distinct(cc2, Marital_Status)) # 4 types: Married, Single, Divorced, Unknown (distinct(cc2, Card_Category)) # 4 types: Blue, Gold, Siler, Platinum#----------------------------# Drop all the \"unknown\" rows from Marital_Status & Income_Category# 82x9, 82 rows must remove these rowscc3 <- cc2 %>% select(Customer_Age,Gender,Dependent_count,Education_Level,Marital_Status,Income_Category,Card_Category,Credit_Limit, Attrition_Flag) %>% filter(Marital_Status != \"Unknown\" , Income_Category != \"Unknown\",Education_Level !=\"Unknown\")#----------------------------head(cc3)dim(cc3) #8348 rows by 9 cols#----------------------------```" }, { "code": null, "e": 6098, "s": 5789, "text": "In Part 3 of 3 Data Wrangling, we rename our predictor Column Attrition_Flag to Exited_Flag. We also rename the binary output values for this predictor from Existing Customer/Attrited Customer to Current/Exited, respectivley. We lastly, also see the cout of each discrete feature with our discrete predictor." }, { "code": null, "e": 7423, "s": 6098, "text": "```{r DataWrangling3}#----------------------------#----------------------------#install.packages(\"dplyr\")library(dplyr)# Rename Label Colum to Exited_FlagdataCC4 <- cc3 %>% rename(Exited_Flag = Attrition_Flag)#----------------------------#----------------------------dataCC4 <- cc3#Rename values dataCC4 $Attrition_Flag[dataCC4 $Attrition_Flag == \"Existing Customer\"] <- \"Current\"dataCC4 $Attrition_Flag[dataCC4 $Attrition_Flag == \"Attrited Customer\"] <- \"Exited\"#----------------------------#----------------------------(dataCC4 %>% group_by(Attrition_Flag) %>% summarize(meanAge= mean(Customer_Age), meanDepdent= mean(Dependent_count), meanCreditLim= mean(Credit_Limit)))#AKA: summarise_mean <- function(data, vars) { data %>% summarise(n = n(), across({{ vars }}, mean))}#dataCC4 %>% #group_by(Attrition_Flag) %>% # summarise_mean(where(is.numeric))#----------------------------#----------------------------#see the count of each(dataCC4 %>% select(Gender,Attrition_Flag) %>% group_by(Gender) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Education_Level) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Marital_Status) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Income_Category) %>% count(Attrition_Flag) ) (dataCC4 %>% group_by(Card_Category) %>% count(Attrition_Flag) ) summary(dataCC4)```" }, { "code": null, "e": 7533, "s": 7423, "text": "Above, we can evidently see that Current Customers had higher mean credit limits than did churning customers." }, { "code": null, "e": 7806, "s": 7533, "text": "In part 1 of 2 in EDA, we reorder the Factor levels of certain discrete variables, because we want them to display in order in our graphs. We have 2 discrete variables plotted against each other, with 1 of the variables being a fill. We examine the count of each visually." }, { "code": null, "e": 10067, "s": 7806, "text": "```{r EDA1}# 2 discrete var, but using 1 as a fill. # Count, with Y being Income Category, Fill is our ggplot(dataCC4 , aes(y = Income_Category)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) +theme(legend.position = \"top\") + theme_classic() + xlab(\"Count\") + ylab(\"Income Category\") + ggtitle(\" Customer Status by Income\" )+ labs(fill = \"Customer Status\")#----------------------------# RE-ODER factor levelsdataCC4$Education_Level <- factor(dataaa$Education_Level, levels = c(\"Uneducated\",\"High School\", \"College\", \"Graduate\", \"Post-Graduate\",\"Doctorate\"))ggplot(dataCC4 , aes(y = Education_Level)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = \"top\") + theme_classic() + xlab(\"Count\") + ylab(\"Education Level\") + ggtitle(\"Customer Status by Education Level\" ) + labs(fill = \"Customer Status\")#----------------------------ggplot(dataCC4 , aes(y = Marital_Status)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = \"top\") + theme_classic() + xlab(\"Count\") + ylab(\"Martial Status\") + ggtitle(\"Customer Status by Martial Status\" )+ labs(fill = \"Customer Status\")#----------------------------ggplot(dataCC4 , aes(y = Card_Category)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = \"top\") + theme_classic() + xlab(\"Count\") + ylab(\"Card Category\") + ggtitle(\"Customer Status by Card Category\" )+ labs(fill = \"Customer Status\")#----------------------------ggplot(dataCC4 , aes(y = Gender)) + geom_bar(aes(fill = Attrition_Flag), position = position_stack(reverse = FALSE)) + theme(legend.position = \"top\") + theme_classic() + xlab(\"Count\") + ylab(\"Gender\") + ggtitle(\"Customer Status by Gender\" )+ labs(fill = \"Customer Status\")#There are more samples of females in our dataset compared to males but the percentage of difference is not that significant so we can say that genders are uniformly distributed.#----------------------------```" }, { "code": null, "e": 10200, "s": 10067, "text": "In part 2 of 2 in EDA, we explore 2 violin plots with quantiles, a visualization for 2 discrete variables, & area distribution plot." }, { "code": null, "e": 11732, "s": 10200, "text": "```{r EDA2}#----------------------------# Discrete X, Continous Y, Violin Plotsggplot(dataCC4 , aes(Attrition_Flag,Credit_Limit,color= Credit_Limit)) + geom_violin(draw_quantiles = c(0.25,0.5,0.75),colour=\"red\",size=1.4) + theme_classic() +xlab(\"Income Category\") + ylab(\"Credit Limit\") + ggtitle(\"Customer Status by Credit Limit\" ) + labs(fill = \"Customer Status\")# RE-ODER factor levelsdataCC4 $Income_Category <- factor(dataCC4 $Income_Category, levels = c(\"Less than $40K\",\"$40K - $60K\",\"$60K - $80K\",\"$80K - $120K\",\"$120K +\"))ggplot(dataCC4 , aes(Income_Category,Credit_Limit,color= Credit_Limit)) + geom_violin(draw_quantiles = c(0.25,0.5,0.75),colour=\"blue\",size=1) + theme_classic() +xlab(\"Income Category\") + ylab(\"Credit Limit\") + ggtitle(\"Income Category by Credit Limit\" )#----------------------------# 2 discrete variables x,y#need to specify which group the proportion is to be calculated over.ggplot(dataCC4 , aes(Income_Category,Attrition_Flag, colour= after_stat(prop), size = after_stat(prop), group = Income_Category)) + geom_count() + scale_size_area() + theme_classic() +xlab(\"Income Category\") + ylab(\"Status of Customer\") + ggtitle(\"Customer Status by Income Proportion\" )#----------------------------##library(plyr)#mu <- ddply(dataaa, \"Exited_Flag\", summarise, grp.mean=mean(Credit_Limit))#head(mu)#ggplot(dataCC4, aes(x=Credit_Limit, fill=Attrition_Flag)) + geom_area(stat =\"bin\") + xlab(\"Credit Limit\")+ylab(\"Count\") +ggtitle(\"Customer Status by Credit Limit \" ) + labs(fill = \"Customer Status\")```" }, { "code": null, "e": 11783, "s": 11732, "text": "Quantiles can tell us a wide array of information." }, { "code": null, "e": 11954, "s": 11783, "text": "The 1st horizontal line tells us the 1st quantile, or the 25th percentile- the number that separates the lowest 25% of the group from the highest 75% of the credit limit." }, { "code": null, "e": 12055, "s": 11954, "text": "Next, the 2nd line is the Median, or 50th percentile — the number in the middle of the credit limit." }, { "code": null, "e": 12211, "s": 12055, "text": "Lastly, the 3rd line is the 3rd quartile, Q3, or 75th percentile — the number that separates the lowest 75% of the group from the highest 25% of the group." }, { "code": null, "e": 12271, "s": 12211, "text": "Quantiles are shown both in the violin plots above & below." }, { "code": null, "e": 12460, "s": 12271, "text": "We have only 16.07% of customers who have churned. Hence, it’s a bit difficult to train our model to predict churning customers. We will do our best with the data given, as with any model." }, { "code": null, "e": 12666, "s": 12460, "text": "Our goal in modeling is to provide a simple low-dimensional summary of a dataset.We use models to partition data into patterns and residuals. Fitted model is just the closest model from a family of models." }, { "code": null, "e": 12970, "s": 12666, "text": "Classification models are models that predict a categorical label. It will be interesting to study which characteristic(s) discriminates each category and to what extent. Predicting whether a customer will a customer will exit or stay with the company. Below we will use a logistic regression algorithm." }, { "code": null, "e": 13144, "s": 12970, "text": "First we must convert the non numeric variables (discrete variables) into factors. Factors are the data objects which are used to categorize the data and store it as levels." }, { "code": null, "e": 13465, "s": 13144, "text": "```{r Modeling1}library(tidyverse)library(modelr)library(plyr)library(readr)library(dplyr)library(caret)# glimpse is from dplyr# output shows that the dataset has glimpse(dataCC4)# convert the non numeric into factors.names <- c(2,5,7,9) # col numbers that are charsdataCC4[,names] <- lapply(dataCC4[,names] , factor)```" }, { "code": null, "e": 14267, "s": 13465, "text": "```{r Modeling2}#----------------------------# DATA PARTITIONING#----------------------------#build our model on the Train dataset & evaluate its performance on #the Test dataset# aka. holdout-validation approach to evaluating model performance.set.seed(100) # sets random seed for reproducibility of resultslibrary(caTools) # for data partioning# create the training and test datasets. The train dataset contains # 70 percent of the data (420 observations of 10 variables) while #the #test data contains the remaining 30 percent (180 observations #of 10 variables).spl = sample.split(dataCC4$Attrition_Flag, SplitRatio = 0.7)train = subset(dataCC4, spl==TRUE)test = subset(dataCC4, spl==FALSE)print(dim(train)) # 4957 rows/obs 9 cols/variablesprint(dim(test)) # 2124 rows/obs 9 cols/variables```" }, { "code": null, "e": 14416, "s": 14267, "text": "We fit the logistic regression model. The first step is to instantiate the algorithm. We declare binomial because 2 possible outcomes: exit/current." }, { "code": null, "e": 15875, "s": 14416, "text": "```{r Modeling3}#----------------------------#BUILD, PREDICT & EVALUATE the Model#----------------------------# BUILD#----------------------------model_glm = glm(Attrition_Flag ~ . , family=\"binomial\",data = train)summary(model_glm)# Baseline Accuracy #Let's evaluate the model further, # Since the majority class of the target (Y) variable has a #proportion of 0.84, the baseline accuracy is 84 percent.prop.table(table(train$Attrition_Flag))#Let's now evaluate the model performance on the training and test data, which should ideally be better than the baseline accuracy.# PREDICTIONS on the TRAIN setpredictTrain = predict(model_glm, data = train, type = \"response\")# confusion matrix w/ threshold of 0.5, #which means that for probability predictions >= 0.5, the #algorithm will predict the Current response for the Y #variable. table(train$Attrition_Flag, predictTrain >= 0.1) Evaluate:#prints the accuracy of the model on the training data, using the #confusion matrix, and the accuracy comes out to be 0 percent.(50+774)/nrow(test) #Accuracy - 84% (50+774)/2124-------------------------------------------------------------#We then repeat this process on the TEST data, and the accuracy #comes out to be 84 percent.# PREDICTIONS on the TEST setpredictTest = predict(model_glm, newdata = test, type = \"response\") Evaluate:# Confusion matrix on test settable(test$Attrition_Flag, predictTest >= 0.5)1790/nrow(test) #Accuracy - 84%```" }, { "code": null, "e": 16174, "s": 15875, "text": "The significance code ‘***’ in the above below output shows the relative importance of the feature variablesAIC estimates the relative amount of information lost by a given model:the less information a model loses, the higher the quality of that model. Lower AIC values indicate a better-fit model," }, { "code": null, "e": 16515, "s": 16174, "text": "You have learned techniques of building a classification model in R using the powerful logistic regression algorithm. The baseline accuracy for the training & test data was 84 percent. Overall, the logistic regression model is beating the baseline accuracy by a big margin on both the train and test datasets, and the results are very good." }, { "code": null, "e": 16600, "s": 16515, "text": "Below I will show you another way to model this, using SVM (Support Vector Machine)." }, { "code": null, "e": 17576, "s": 16600, "text": "```{r ModelAgain}unique(dataCC5$Attrition_Flag) #Levels: Current Exited# Encoding the target feature as factordataCC5$Attrition_Flag = factor(dataCC5$Attrition_Flag, levels = c(0, 1))# spliting datast into Train & Test Setinstall.packages('caTools')library(caTools) # for data partioningset.seed(123) #SEED#SPLITsplit = sample.split(dataCC5$Attrition_Flag, SplitRatio = 0.75)train_set = subset(dataCC5,split==TRUE) #TRAINtest_set = subset(dataCC5,split==FALSE) #TEST#FEATURE SCALING: agelibrary(caret)train_set[-9] = scale(train_set[-9])test_set[-9] = scale(test_set[-9])install.packages('e1071')library(e1071)model_glm = glm(Attrition_Flag ~ . , family=\"binomial\",data = train)classifier = svm(formula= Attrition_Flag ~ ., data= train_set, type= 'C-classification', kernel = 'radial')# predicting Test Set Resultsy_pred = predict(classifier, newdata = train_set[-9])# making confusion matrixcm = table(test_set[, 3],y_pred)```" }, { "code": null, "e": 17674, "s": 17576, "text": "Confidence intervals are of interest in modeling because they are often used in model validation." }, { "code": null, "e": 17980, "s": 17674, "text": "Next, we consider the 95% confidence interval of Credit Limit.As the Credit Limit is greater than 0, we narrow the confidence interval.There are 91.75% data locates within the confidence interval. We will keep the corresponding records and store the rest in another variable rest.data for latter analysis." }, { "code": null, "e": 19725, "s": 17980, "text": "```{r CI}mean.Credit_Limit <- mean(dataCC5$Credit_Limit)std.Credit_Limit <- sqrt(var(dataCC5$Credit_Limit))df = dim(dataCC5)[1] - 9conf.Credit_Limit <- mean.Credit_Limit + c(-1, 1) * qt(0.975, df) * std.Credit_Limit# As the CreditLimit is greater than 0, we narrow the confidence intervalconf.Credit_Limit[1] <- 0conf.Credit_Limit#There are 91.75% data locates within the confidence interval. We will keep the corresponding records and store the rest in another variable rest.data for later analysis.sum(dataCC5$Credit_Limit <= conf.Credit_Limit[2]) / dim(dataCC5)[1]#----------------------------##----------------------------rest.data <- dataCC5 %>% filter(Credit_Limit > conf.Credit_Limit[2])dataCC5 <- dataCC5 %>% filter(Credit_Limit <= conf.Credit_Limit[2]) %>% filter(Credit_Limit != 0)#We recall the historgrams of Credit Limitboxplot_credLim <- dataCC5 %>% ggplot() + geom_boxplot(aes(Credit_Limit))(boxplot_credLim)histplot <- dataCC5 %>% ggplot() + geom_histogram(aes(Credit_Limit))(histplot)#----------------------------##----------------------------#We consider a log-transofrmation to convert the distribution of the histogram to normal distribution. Right-skew.histplot <- dataCC5 %>% ggplot() + geom_histogram(aes(log(Credit_Limit)))(histplot)qqplot <- dataCC5 %>% ggplot() + geom_qq(aes(sample = log(Credit_Limit)))(qqplot)#It seems that normality exists. Great! There are 6 types of categorical variables.# Distrubution of Income Categoryp1 <- dataCC5 %>% ggplot() + geom_histogram(aes(Income_Category, fill = Income_Category), stat = \"count\")(p1)# Box Plots of Depdent count & Income Categoryp2 <- dataCC5 %>% ggplot() + geom_boxplot(aes(x = Dependent_count, y = Income_Category, color = Income_Category))(p2)```" }, { "code": null, "e": 19864, "s": 19725, "text": "#The following aims to build a model to predict the price. ## Evaluation We will use MSE as the criteria to measure the model performance." }, { "code": null, "e": 19922, "s": 19864, "text": "We Split 20% as test dataset and 80% as training dataset." }, { "code": null, "e": 21027, "s": 19922, "text": "```{r RMSE}#Train and test split#Split 20% as test dataset and 80% as training dataset.### convert character to factordataCC5$Gender <-as.factor(dataCC5$Gender)# Splitset.seed(100)train.index <- sample(nrow(dataCC5), 0.7*nrow(dataCC5), replace = FALSE)train.set <- dataCC5[train.index, ]test.set <- dataCC5[-train.index, ]# build a model to predict the price. ## Evaluation: We will use MSE as the criteria to measure the model performance.RMSE <- function(true, pred){ residuals <- true - pred res <- sqrt(mean(residuals^2)) return(res)}----------#----------------------------#Linear regression#Linear regressoin is a kind of simple regression methods. It is easy to be conducted while it has some strict assumptions. The following code will perform the modeling process with check some assumptions. ### Multicolinearity#library(corrplot)#cor <- cor(dataCC5)#corrplot::corrplot(cor, method = 'ellipse', type = 'lower')#cor(dataCC5$Credit_Limit, dataCC5$Dependent_count)# IF data had more numeric values use this for # correlation plot: #M <- cor(dataCC5)#corrplot(cor(dataCC5), method = \"circle\")```" }, { "code": null, "e": 21239, "s": 21027, "text": "To recal: AIC estimates the relative amount of information lost by a given model: The less information a model loses, the higher the quality of that model. Thus, the lower AIC values indicate a better-fit model," }, { "code": null, "e": 22867, "s": 21239, "text": "```{r AIC}AICs <- c()models <- c()start.model <- lm(Credit_Limit ~ Customer_Age, data = train.set)# summary(start.model) models <- append(models, as.character(start.model$call)[2])AICs <- append(AICs, AIC(start.model))# Add next varaibleupdate.model <- update(start.model, . ~ . + Gender)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add next varupdate.model <- update(update.model, . ~ . + Dependent_count)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add next varupdate.model <- update(update.model, . ~ . + Education_Level)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add next variableupdate.model <- update(update.model, . ~ . + Marital_Status)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add calculated_host_listings_countupdate.model <- update(update.model, . ~ . + Income_Category)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))# Add last varupdate.model <- update(update.model, . ~ . + Card_Category)# summary(update.model)models <- append(models, as.character(update.model$call)[2])AICs <- append(AICs, AIC(update.model))res <- data.frame( Model = models, AIC = AICs)knitr::kable(res)#----------------------------#----------------------------par(mfrow = c(3,1))plot(update.model, 1)plot(update.model, 2)plot(update.model, 3)```" }, { "code": null, "e": 23076, "s": 22867, "text": "The AIC table shows the best model is Credit_Limit ~ Customer_Age + Gender + Dependent_count + Education_Level + Marital_Status + Income_Category + Card_CategoryWith a AIC of 72870.02, we want the lowest AIC." }, { "code": null, "e": 23279, "s": 23076, "text": "```{r LogLinearRegression}log.lm <- lm(log(Credit_Limit) ~ Customer_Age + Gender + Dependent_count + Education_Level + Marital_Status + Income_Category + Card_Category, data = dataCC5)summary(log.lm)```" }, { "code": null, "e": 23414, "s": 23279, "text": "Gender Male, Income Categories, and Silver Card Card Categories were highly significant with respect to our predictor of Credit Limit." }, { "code": null, "e": 23473, "s": 23414, "text": "Here is access to the data set & code from my GitHub page:" }, { "code": null, "e": 23530, "s": 23473, "text": "https://github.com/jararzaidi/ModelingChurningCustomersR" }, { "code": null, "e": 23588, "s": 23530, "text": "https://www.kaggle.com/sakshigoyal7/credit-card-customers" } ]
How to get programmatically android serial number?
This example demonstrate about How to get programmatically android serial number. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken text view to show serial number. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.Manifest; import android.app.ProgressDialog; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101); } } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 101: if (grantResults[0] = = PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } textView.setText(Build.getSerial()); } else { //not granted } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onResume() { super.onResume(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } textView.setText(Build.getSerial()); } } Step 4 − Add the following code to AndroidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <uses-permission android:name = "android.permission.READ_PHONE_STATE" /> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrate about How to get programmatically android serial number." }, { "code": null, "e": 1273, "s": 1144, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1898, "s": 1338, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1964, "s": 1898, "text": "In the above code, we have taken text view to show serial number." }, { "code": null, "e": 2021, "s": 1964, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4191, "s": 2021, "text": "package com.example.myapplication;\nimport android.Manifest;\nimport android.app.ProgressDialog;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.CookieManager;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);\n }\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case 101:\n if (grantResults[0] = = PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n textView.setText(Build.getSerial());\n } else {\n //not granted\n }\n break;\n default:\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n }\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n protected void onResume() {\n super.onResume();\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n textView.setText(Build.getSerial());\n }\n}" }, { "code": null, "e": 4246, "s": 4191, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 5099, "s": 4246, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <uses-permission android:name = \"android.permission.READ_PHONE_STATE\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5446, "s": 5099, "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 toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5486, "s": 5446, "text": "Click here to download the project code" } ]
Search in a row-column sorted Matrix | Practice | GeeksforGeeks
Given a matrix of size n x m, where every row and column is sorted in increasing order, and a number x. Find whether element x is present in the matrix or not. Example 1: Input: n = 3, m = 3, x = 62 matrix[][] = {{ 3, 30, 38}, {36, 43, 60}, {40, 51, 69}} Output: 0 Explanation: 62 is not present in the matrix, so output is 0. Example 2: Input: n = 1, m = 6, x = 55 matrix[][] = {{18, 21, 27, 38, 55, 67}} Output: 1 Explanation: 55 is present in the matrix. Your Task: You don't need to read input or print anything. Complete the function search() that takes n, m, x, and matrix[][] as input parameters and returns a boolean value. True if x is present in the matrix and false if it is not present. Expected Time Complexity: O(N + M) Expected Auxiliary Space: O(1) Constraints: 1 <= N, M <= 1000 1 <= mat[][] <= 105 1 <= X <= 1000 +1 velspace015 days ago Java sol int row=0; int col=m-1; while(row<n && col>=0){ if(Mat[row][col]==x){ return true; } else if(Mat[row][col]>x){ col--; }else{ row++; } } return false; +1 subhaduleygba1 week ago //c++ code bool search(vector<vector<int> > matrix, int n, int m, int x) { // code here if(n==0)return false; int i=n-1; int j=0; while(i>=0 and j<n){ if(matrix[j][i]==x){ return true; } else if(matrix[j][i]<x){ j++; }else{ i--; } } return false; } +2 vishalsavade2 weeks ago Approach 1. Start with row 0 and col m-1 2. traverse while row < n and col >= 0 3. if element > target decrement col 4. else increment row 5. if found return true else false -1 giridharsonu1232 weeks ago JavaScript Solution for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (matrix[i][j] === x) { return 1; } } } return 0; 0 dileeprajoriya20192 weeks ago Problem Solved Successfully bool search(vector<vector<int> > matrix, int n, int m, int target) { int r = 0; int c = m-1; while( r < n and c >= 0) { int ele = matrix[r][c]; if(ele == target) { return true; } else if(ele > target) { c--; } else { r++; } } return false; } 0 rishaw2k2 weeks ago time complexity 0.29/1.6 Simple and efficient approach in C++ bool search(vector<vector<int> > matrix, int n, int m, int x) { bool res = false; int i=0, j=m-1; while(i<n && j>=0) { if(matrix[i][j] == x) { res = true; break; } else if(matrix[i][j] > x) j--; else i++; } return res; // code here } +1 yashvardhansingh20193 weeks ago Java # Simple Binary Search int i =0; int j = m-1; while(i<n && j>=0){ if(matrix[i][j]==x){ return true; }else if(matrix[i][j]>x){ j--; }else{ i++; }}return false; +1 mukulgoswami304 This comment was deleted. 0 sudeepgarg6711 month ago class Solution: #Function to search a given number in row-column sorted matrix. def search(self,matrix, n, m, x): for i in range(n): if x in matrix[i]: return 1 return 0 0 prakashsuraj41411 month ago Problem Solved Successfully bool search(vector<vector<int> > matrix, int n, int m, int x) { // code here int i=0; int j=m-1; while(i>=0 && i<n && j>=0 && j<m) { if(matrix[i][j]==x) return true; else if(matrix[i][j]>x) j--; else i++; } return false; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 410, "s": 238, "text": "Given a matrix of size n x m, where every row and column is sorted in increasing order, and a number x. Find whether element x is present in the matrix or not.\n\nExample 1:" }, { "code": null, "e": 596, "s": 410, "text": "Input:\nn = 3, m = 3, x = 62\nmatrix[][] = {{ 3, 30, 38},\n {36, 43, 60},\n {40, 51, 69}}\nOutput: 0\nExplanation:\n62 is not present in the matrix, \nso output is 0.\n" }, { "code": null, "e": 607, "s": 596, "text": "Example 2:" }, { "code": null, "e": 728, "s": 607, "text": "Input:\nn = 1, m = 6, x = 55\nmatrix[][] = {{18, 21, 27, 38, 55, 67}}\nOutput: 1\nExplanation: 55 is present in the matrix.\n" }, { "code": null, "e": 1104, "s": 728, "text": "\nYour Task:\nYou don't need to read input or print anything. Complete the function search() that takes n, m, x, and matrix[][] as input parameters and returns a boolean value. True if x is present in the matrix and false if it is not present.\n\nExpected Time Complexity: O(N + M)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= N, M <= 1000\n1 <= mat[][] <= 105\n1 <= X <= 1000" }, { "code": null, "e": 1107, "s": 1104, "text": "+1" }, { "code": null, "e": 1128, "s": 1107, "text": "velspace015 days ago" }, { "code": null, "e": 1391, "s": 1128, "text": "Java sol\nint row=0;\n\t int col=m-1;\n\t while(row<n && col>=0){\n\t if(Mat[row][col]==x){\n\t return true;\n\t }\n\t else if(Mat[row][col]>x){\n\t col--;\n\t }else{\n\t row++;\n\t }\n\t }\n\t return false;" }, { "code": null, "e": 1394, "s": 1391, "text": "+1" }, { "code": null, "e": 1418, "s": 1394, "text": "subhaduleygba1 week ago" }, { "code": null, "e": 1429, "s": 1418, "text": "//c++ code" }, { "code": null, "e": 1814, "s": 1429, "text": "bool search(vector<vector<int> > matrix, int n, int m, int x) { // code here if(n==0)return false; int i=n-1; int j=0; while(i>=0 and j<n){ if(matrix[j][i]==x){ return true; } else if(matrix[j][i]<x){ j++; }else{ i--; } } return false; }" }, { "code": null, "e": 1821, "s": 1818, "text": "+2" }, { "code": null, "e": 1845, "s": 1821, "text": "vishalsavade2 weeks ago" }, { "code": null, "e": 2019, "s": 1845, "text": "Approach\n1. Start with row 0 and col m-1\n2. traverse while row < n and col >= 0\n3. if element > target decrement col\n4. else increment row\n5. if found return true else false" }, { "code": null, "e": 2022, "s": 2019, "text": "-1" }, { "code": null, "e": 2049, "s": 2022, "text": "giridharsonu1232 weeks ago" }, { "code": null, "e": 2069, "s": 2049, "text": "JavaScript Solution" }, { "code": null, "e": 2238, "s": 2069, "text": "for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { if (matrix[i][j] === x) { return 1; } } } return 0;" }, { "code": null, "e": 2240, "s": 2238, "text": "0" }, { "code": null, "e": 2270, "s": 2240, "text": "dileeprajoriya20192 weeks ago" }, { "code": null, "e": 2299, "s": 2270, "text": "Problem Solved Successfully " }, { "code": null, "e": 2719, "s": 2301, "text": "bool search(vector<vector<int> > matrix, int n, int m, int target) { int r = 0; int c = m-1; while( r < n and c >= 0) { int ele = matrix[r][c]; if(ele == target) { return true; } else if(ele > target) { c--; } else { r++; } } return false; }" }, { "code": null, "e": 2721, "s": 2719, "text": "0" }, { "code": null, "e": 2741, "s": 2721, "text": "rishaw2k2 weeks ago" }, { "code": null, "e": 2766, "s": 2741, "text": "time complexity 0.29/1.6" }, { "code": null, "e": 2803, "s": 2766, "text": "Simple and efficient approach in C++" }, { "code": null, "e": 3234, "s": 2803, "text": " bool search(vector<vector<int> > matrix, int n, int m, int x) \n {\n bool res = false; \n int i=0, j=m-1;\n while(i<n && j>=0)\n {\n if(matrix[i][j] == x)\n {\n res = true;\n break;\n }\n else if(matrix[i][j] > x)\n j--;\n else \n i++;\n }\n return res;\n // code here \n }" }, { "code": null, "e": 3237, "s": 3234, "text": "+1" }, { "code": null, "e": 3269, "s": 3237, "text": "yashvardhansingh20193 weeks ago" }, { "code": null, "e": 3274, "s": 3269, "text": "Java" }, { "code": null, "e": 3297, "s": 3274, "text": "# Simple Binary Search" }, { "code": null, "e": 3488, "s": 3297, "text": "int i =0; int j = m-1; while(i<n && j>=0){ if(matrix[i][j]==x){ return true; }else if(matrix[i][j]>x){ j--; }else{ i++; }}return false;" }, { "code": null, "e": 3491, "s": 3488, "text": "+1" }, { "code": null, "e": 3507, "s": 3491, "text": "mukulgoswami304" }, { "code": null, "e": 3533, "s": 3507, "text": "This comment was deleted." }, { "code": null, "e": 3535, "s": 3533, "text": "0" }, { "code": null, "e": 3560, "s": 3535, "text": "sudeepgarg6711 month ago" }, { "code": null, "e": 3762, "s": 3560, "text": "class Solution: #Function to search a given number in row-column sorted matrix. def search(self,matrix, n, m, x): for i in range(n): if x in matrix[i]: return 1 return 0" }, { "code": null, "e": 3764, "s": 3762, "text": "0" }, { "code": null, "e": 3792, "s": 3764, "text": "prakashsuraj41411 month ago" }, { "code": null, "e": 3822, "s": 3792, "text": " Problem Solved Successfully " }, { "code": null, "e": 4153, "s": 3822, "text": "bool search(vector<vector<int> > matrix, int n, int m, int x) { // code here int i=0; int j=m-1; while(i>=0 && i<n && j>=0 && j<m) { if(matrix[i][j]==x) return true; else if(matrix[i][j]>x) j--; else i++; } return false; }" }, { "code": null, "e": 4299, "s": 4153, "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": 4335, "s": 4299, "text": " Login to access your submissions. " }, { "code": null, "e": 4345, "s": 4335, "text": "\nProblem\n" }, { "code": null, "e": 4355, "s": 4345, "text": "\nContest\n" }, { "code": null, "e": 4418, "s": 4355, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4566, "s": 4418, "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": 4774, "s": 4566, "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": 4880, "s": 4774, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
ReactJS - Routing
In web application, Routing is a process of binding a web URL to a specific resource in the web application. In React, it is binding an URL to a component. React does not support routing natively as it is basically an user interface library. React community provides many third party component to handle routing in the React application. Let us learn React Router, a top choice routing library for React application. Let us learn how to install React Router component in our Expense Manager application. Open a command prompt and go to the root folder of our application. cd /go/to/expense/manager Install the react router using below command. npm install react-router-dom --save React router provides four components to manage navigation in React application. Router − Router is th top level component. It encloses the entire application. Link − Similar to anchor tag in html. It sets the target url along with reference text. <Link to="/">Home</Link> Here, to attribute is used to set the target url. Switch & Route − Both are used together. Maps the target url to the component. Switch is the parent component and Route is the child component. Switch component can have multiple Route component and each Route component mapping a particular url to a component. <Switch> <Route exact path="/"> <Home /> </Route> <Route path="/home"> <Home /> </Route> <Route path="/list"> <ExpenseEntryItemList /> </Route> </Switch> Here, path attribute is used to match the url. Basically, Switch works similar to traditional switch statement in a programming language. It matches the target url with each child route (path attribute) one by one in sequence and invoke the first matched route. Along with router component, React router provides option to get set and get dynamic information from the url. For example, in an article website, the url may have article type attached to it and the article type needs to be dynamically extracted and has to be used to fetch the specific type of articles. <Link to="/article/c">C Programming</Link> <Link to="/article/java">Java Programming</Link> ... ... <Switch> <Route path="article/:tag" children={<ArticleList />} /> </Switch> Then, in the child component (class component), import { withRouter } from "react-router" class ArticleList extends React.Component { ... ... static getDerivedStateFromProps(props, state) { let newState = { tag: props.match.params.tag } return newState; } ... ... } export default WithRouter(ArticleList) Here, WithRouter enables ArticleList component to access the tag information through props. The same can be done differently in functional components − function ArticleList() { let { tag } = useParams(); return ( <div> <h3>ID: {id}</h3> </div> ); } Here, useParams is a custom React Hooks provided by React Router component. React router supports nested routing as well. React router provides another React Hooks, useRouteMatch() to extract parent route information in nested routes. function ArticleList() { // get the parent url and the matched path let { path, url } = useRouteMatch(); return ( <div> <h2>Articles</h2> <ul> <li> <Link to={`${url}/pointer`}>C with pointer</Link> </li> <li> <Link to={`${url}/basics`}>C basics</Link> </li> </ul> <Switch> <Route exact path={path}> <h3>Please select an article.</h3> </Route> <Route path={`${path}/:article`}> <Article /> </Route> </Switch> </div> ); } function Article() { let { article } = useParams(); return ( <div> <h3>The select article is {article}</h3> </div> ); } Here, useRouteMatch returns the matched path and the target url. url can be used to create next level of links and path can be used to map next level of components / screens. Let us learn how to do routing by creating the possible routing in our expense manager application. The minimum screens of the application are given below − Home screen − Landing or initial screen of the application Home screen − Landing or initial screen of the application Expense list screen − Shows the expense items in a tabular format Expense list screen − Shows the expense items in a tabular format Expense add screen − Add interface to add an expense item Expense add screen − Add interface to add an expense item First, create a new react application, react-router-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, Home.js under src/components folder and start editing. Next, import React library. import React from 'react'; Next, import Link from React router library. import { Link } from 'react-router-dom' Next, create a class, Home and call constructor with props. class Home extends React.Component { constructor(props) { super(props); } } Next, add render() method and show the welcome message and links to add and list expense screen. render() { return ( <div> <p>Welcome to the React tutorial</p> <p><Link to="/list">Click here</Link> to view expense list</p> <p><Link to="/add">Click here</Link> to add new expenses</p> </div> ) } Finally, export the component. export default Home; The complete source code of the Home component is given below − import React from 'react'; import { Link } from 'react-router-dom' class Home extends React.Component { constructor(props) { super(props); } render() { return ( <div> <p>Welcome to the React tutorial</p> <p><Link to="/list">Click here</Link> to view expense list</p> <p><Link to="/add">Click here</Link> to add new expenses</p> </div> ) } } export default Home; Next, create ExpenseEntryItemList.js file under src/components folder and create ExpenseEntryItemList component. import React from 'react'; import { Link } from 'react-router-dom' class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Expenses</h1> <p><Link to="/add">Click here</Link> to add new expenses</p> <div> Expense list </div> </div> ) } } export default ExpenseEntryItemList; Next, create ExpenseEntryItemForm.js file under src/components folder and create ExpenseEntryItemForm component. import React from 'react'; import { Link } from 'react-router-dom' class ExpenseEntryItemForm extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Add Expense item</h1> <p><Link to="/list">Click here</Link> to view new expense list</p> <div> Expense form </div> </div> ) } } export default ExpenseEntryItemForm; Next, create a file, App.css under src/components folder and add generic css styles. html { font-family: sans-serif; } a{ text-decoration: none; } p, li, a{ font-size: 14px; } nav ul { width: 100%; list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: rgb(235,235,235); } nav li { float: left; } nav li a { display: block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 16px; } nav li a:hover { background-color: rgb(187, 202, 211); } Next, create a file, App.js under src/components folder and start editing. The purpose of the App component is to handle all the screen in one component. It will configure routing and enable navigation to all other components. Next, import React library and other components. import React from 'react'; import Home from './Home' import ExpenseEntryItemList from './ExpenseEntryItemList' import ExpenseEntryItemForm from './ExpenseEntryItemForm' import './App.css' Next, import React router components. import { BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom' Next, write the render() method and configure routing. function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/list">List Expenses</Link> </li> <li> <Link to="/add">Add Expense</Link> </li> </ul> </nav> <Switch> <Route path="/list"> <ExpenseEntryItemList /> </Route> <Route path="/add"> <ExpenseEntryItemForm /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } Next, create a file, index.js under the src folder and use App component. import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>React router app</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Try to navigate the links and confirm that the routing is working. 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2450, "s": 2033, "text": "In web application, Routing is a process of binding a web URL to a specific resource in the web application. In React, it is binding an URL to a component. React does not support routing natively as it is basically an user interface library. React community provides many third party component to handle routing in the React application. Let us learn React Router, a top choice routing library for React application." }, { "code": null, "e": 2537, "s": 2450, "text": "Let us learn how to install React Router component in our Expense Manager application." }, { "code": null, "e": 2605, "s": 2537, "text": "Open a command prompt and go to the root folder of our application." }, { "code": null, "e": 2632, "s": 2605, "text": "cd /go/to/expense/manager\n" }, { "code": null, "e": 2678, "s": 2632, "text": "Install the react router using below command." }, { "code": null, "e": 2715, "s": 2678, "text": "npm install react-router-dom --save\n" }, { "code": null, "e": 2796, "s": 2715, "text": "React router provides four components to manage navigation in React application." }, { "code": null, "e": 2875, "s": 2796, "text": "Router − Router is th top level component. It encloses the entire application." }, { "code": null, "e": 2963, "s": 2875, "text": "Link − Similar to anchor tag in html. It sets the target url along with reference text." }, { "code": null, "e": 2989, "s": 2963, "text": "<Link to=\"/\">Home</Link>\n" }, { "code": null, "e": 3039, "s": 2989, "text": "Here, to attribute is used to set the target url." }, { "code": null, "e": 3300, "s": 3039, "text": "Switch & Route − Both are used together. Maps the target url to the component. Switch is the parent component and Route is the child component. Switch component can have multiple Route component and each Route component mapping a particular url to a component." }, { "code": null, "e": 3490, "s": 3300, "text": "<Switch>\n <Route exact path=\"/\">\n <Home />\n </Route>\n <Route path=\"/home\">\n <Home />\n </Route>\n <Route path=\"/list\">\n <ExpenseEntryItemList />\n </Route>\n</Switch>" }, { "code": null, "e": 3752, "s": 3490, "text": "Here, path attribute is used to match the url. Basically, Switch works similar to traditional switch statement in a programming language. It matches the target url with each child route (path attribute) one by one in sequence and invoke the first matched route." }, { "code": null, "e": 4058, "s": 3752, "text": "Along with router component, React router provides option to get set and get dynamic information from the url. For example, in an article website, the url may have article type attached to it and the article type needs to be dynamically extracted and has to be used to fetch the specific type of articles." }, { "code": null, "e": 4238, "s": 4058, "text": "<Link to=\"/article/c\">C Programming</Link>\n<Link to=\"/article/java\">Java Programming</Link>\n\n...\n...\n\n<Switch>\n <Route path=\"article/:tag\" children={<ArticleList />} />\n</Switch>" }, { "code": null, "e": 4286, "s": 4238, "text": "Then, in the child component (class component)," }, { "code": null, "e": 4589, "s": 4286, "text": "import { withRouter } from \"react-router\"\n\nclass ArticleList extends React.Component {\n ...\n ...\n static getDerivedStateFromProps(props, state) {\n let newState = {\n tag: props.match.params.tag\n }\n return newState;\n }\n ...\n ...\n}\nexport default WithRouter(ArticleList)" }, { "code": null, "e": 4681, "s": 4589, "text": "Here, WithRouter enables ArticleList component to access the tag information through props." }, { "code": null, "e": 4741, "s": 4681, "text": "The same can be done differently in functional components −" }, { "code": null, "e": 4868, "s": 4741, "text": "function ArticleList() {\n let { tag } = useParams();\n return (\n <div>\n <h3>ID: {id}</h3>\n </div>\n );\n}" }, { "code": null, "e": 4944, "s": 4868, "text": "Here, useParams is a custom React Hooks provided by React Router component." }, { "code": null, "e": 5103, "s": 4944, "text": "React router supports nested routing as well. React router provides another React Hooks, useRouteMatch() to extract parent route information in nested routes." }, { "code": null, "e": 5900, "s": 5103, "text": "function ArticleList() {\n // get the parent url and the matched path\n let { path, url } = useRouteMatch();\n\n return (\n <div>\n <h2>Articles</h2>\n <ul>\n <li>\n <Link to={`${url}/pointer`}>C with pointer</Link>\n </li>\n <li>\n <Link to={`${url}/basics`}>C basics</Link>\n </li>\n </ul>\n\n <Switch>\n <Route exact path={path}>\n <h3>Please select an article.</h3>\n </Route>\n <Route path={`${path}/:article`}>\n <Article />\n </Route>\n </Switch>\n </div>\n );\n}\nfunction Article() {\n let { article } = useParams();\n return (\n <div>\n <h3>The select article is {article}</h3>\n </div>\n );\n}" }, { "code": null, "e": 6075, "s": 5900, "text": "Here, useRouteMatch returns the matched path and the target url. url can be used to create next level of links and path can be used to map next level of components / screens." }, { "code": null, "e": 6232, "s": 6075, "text": "Let us learn how to do routing by creating the possible routing in our expense manager application. The minimum screens of the application are given below −" }, { "code": null, "e": 6291, "s": 6232, "text": "Home screen − Landing or initial screen of the application" }, { "code": null, "e": 6350, "s": 6291, "text": "Home screen − Landing or initial screen of the application" }, { "code": null, "e": 6416, "s": 6350, "text": "Expense list screen − Shows the expense items in a tabular format" }, { "code": null, "e": 6482, "s": 6416, "text": "Expense list screen − Shows the expense items in a tabular format" }, { "code": null, "e": 6540, "s": 6482, "text": "Expense add screen − Add interface to add an expense item" }, { "code": null, "e": 6598, "s": 6540, "text": "Expense add screen − Add interface to add an expense item" }, { "code": null, "e": 6761, "s": 6598, "text": "First, create a new react application, react-router-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 6813, "s": 6761, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 6882, "s": 6813, "text": "Next, create src folder under the root directory of the application." }, { "code": null, "e": 6931, "s": 6882, "text": "Next, create components folder under src folder." }, { "code": null, "e": 7007, "s": 6931, "text": "Next, create a file, Home.js under src/components folder and start editing." }, { "code": null, "e": 7035, "s": 7007, "text": "Next, import React library." }, { "code": null, "e": 7063, "s": 7035, "text": "import React from 'react';\n" }, { "code": null, "e": 7108, "s": 7063, "text": "Next, import Link from React router library." }, { "code": null, "e": 7149, "s": 7108, "text": "import { Link } from 'react-router-dom'\n" }, { "code": null, "e": 7209, "s": 7149, "text": "Next, create a class, Home and call constructor with props." }, { "code": null, "e": 7297, "s": 7209, "text": "class Home extends React.Component {\n constructor(props) {\n super(props);\n }\n}" }, { "code": null, "e": 7394, "s": 7297, "text": "Next, add render() method and show the welcome message and links to add and list expense screen." }, { "code": null, "e": 7637, "s": 7394, "text": "render() {\n return (\n <div>\n <p>Welcome to the React tutorial</p>\n <p><Link to=\"/list\">Click here</Link> to view expense list</p>\n <p><Link to=\"/add\">Click here</Link> to add new expenses</p>\n </div>\n )\n}" }, { "code": null, "e": 7668, "s": 7637, "text": "Finally, export the component." }, { "code": null, "e": 7690, "s": 7668, "text": "export default Home;\n" }, { "code": null, "e": 7754, "s": 7690, "text": "The complete source code of the Home component is given below −" }, { "code": null, "e": 8201, "s": 7754, "text": "import React from 'react';\nimport { Link } from 'react-router-dom'\n\nclass Home extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <p>Welcome to the React tutorial</p>\n <p><Link to=\"/list\">Click here</Link> to view expense list</p>\n <p><Link to=\"/add\">Click here</Link> to add new expenses</p>\n </div>\n )\n }\n}\nexport default Home;" }, { "code": null, "e": 8314, "s": 8201, "text": "Next, create ExpenseEntryItemList.js file under src/components folder and create ExpenseEntryItemList component." }, { "code": null, "e": 8764, "s": 8314, "text": "import React from 'react';\nimport { Link } from 'react-router-dom'\n\nclass ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <h1>Expenses</h1>\n <p><Link to=\"/add\">Click here</Link> to add new expenses</p>\n <div>\n Expense list\n </div>\n </div>\n )\n }\n}\nexport default ExpenseEntryItemList;" }, { "code": null, "e": 8877, "s": 8764, "text": "Next, create ExpenseEntryItemForm.js file under src/components folder and create ExpenseEntryItemForm component." }, { "code": null, "e": 9341, "s": 8877, "text": "import React from 'react';\nimport { Link } from 'react-router-dom'\n\nclass ExpenseEntryItemForm extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <h1>Add Expense item</h1>\n <p><Link to=\"/list\">Click here</Link> to view new expense list</p>\n <div>\n Expense form\n </div>\n </div>\n )\n }\n}\nexport default ExpenseEntryItemForm;" }, { "code": null, "e": 9426, "s": 9341, "text": "Next, create a file, App.css under src/components folder and add generic css styles." }, { "code": null, "e": 9896, "s": 9426, "text": "html {\n font-family: sans-serif;\n}\na{\n text-decoration: none;\n}\np, li, a{\n font-size: 14px;\n}\nnav ul {\n width: 100%;\n list-style-type: none;\n margin: 0;\n padding: 0;\n overflow: hidden;\n background-color: rgb(235,235,235);\n}\nnav li {\n float: left;\n}\nnav li a {\n display: block;\n color: black;\n text-align: center;\n padding: 14px 16px;\n text-decoration: none;\n font-size: 16px;\n}\nnav li a:hover {\n background-color: rgb(187, 202, 211);\n}" }, { "code": null, "e": 10123, "s": 9896, "text": "Next, create a file, App.js under src/components folder and start editing. The purpose of the App component is to handle all the screen in one component. It will configure routing and enable navigation to all other components." }, { "code": null, "e": 10172, "s": 10123, "text": "Next, import React library and other components." }, { "code": null, "e": 10362, "s": 10172, "text": "import React from 'react';\n\nimport Home from './Home'\nimport ExpenseEntryItemList from './ExpenseEntryItemList'\nimport ExpenseEntryItemForm from './ExpenseEntryItemForm'\n\nimport './App.css'" }, { "code": null, "e": 10400, "s": 10362, "text": "Next, import React router components." }, { "code": null, "e": 10492, "s": 10400, "text": "import {\n BrowserRouter as Router,\n Link,\n Switch,\n Route\n} from 'react-router-dom'" }, { "code": null, "e": 10547, "s": 10492, "text": "Next, write the render() method and configure routing." }, { "code": null, "e": 11358, "s": 10547, "text": "function App() {\n return (\n <Router>\n <div>\n <nav>\n <ul>\n <li>\n <Link to=\"/\">Home</Link>\n </li>\n <li>\n <Link to=\"/list\">List Expenses</Link>\n </li>\n <li>\n <Link to=\"/add\">Add Expense</Link>\n </li>\n </ul>\n </nav>\n\n <Switch>\n <Route path=\"/list\">\n <ExpenseEntryItemList />\n </Route>\n <Route path=\"/add\">\n <ExpenseEntryItemForm />\n </Route>\n <Route path=\"/\">\n <Home />\n </Route>\n </Switch>\n </div>\n </Router>\n );\n}" }, { "code": null, "e": 11432, "s": 11358, "text": "Next, create a file, index.js under the src folder and use App component." }, { "code": null, "e": 11645, "s": 11432, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './components/App';\n\nReactDOM.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 11727, "s": 11645, "text": "Finally, create a public folder under the root folder and create index.html file." }, { "code": null, "e": 11969, "s": 11727, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React router app</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 12016, "s": 11969, "text": "Next, serve the application using npm command." }, { "code": null, "e": 12027, "s": 12016, "text": "npm start\n" }, { "code": null, "e": 12118, "s": 12027, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 12185, "s": 12118, "text": "Try to navigate the links and confirm that the routing is working." }, { "code": null, "e": 12220, "s": 12185, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12234, "s": 12220, "text": " Anadi Sharma" }, { "code": null, "e": 12269, "s": 12234, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12289, "s": 12269, "text": " Skillbakerystudios" }, { "code": null, "e": 12324, "s": 12289, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 12347, "s": 12324, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 12382, "s": 12347, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 12398, "s": 12382, "text": " TELCOMA Global" }, { "code": null, "e": 12431, "s": 12398, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 12449, "s": 12431, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 12456, "s": 12449, "text": " Print" }, { "code": null, "e": 12467, "s": 12456, "text": " Add Notes" } ]
Decision Tree Classifiers in Julia - GeeksforGeeks
01 Nov, 2020 In statistics in Julia, classification is the problem of identifying to which of a set of categories (sub-populations) a new observation belongs, on the basis of a training set of data containing observations (or instances) whose category membership is known. In the terminology of machine learning, classification is considered an instance of supervised learning, i.e., learning where a training set of correctly identified observations is available. Some of the classification techniques which we have are: Linear Classifiers: Logistic Regression, Naive Bayes ClassifierNearest NeighborSupport Vector MachinesDecision TreesBoosted TreesRandom ForestNeural Networks Linear Classifiers: Logistic Regression, Naive Bayes Classifier Nearest Neighbor Support Vector Machines Decision Trees Boosted Trees Random Forest Neural Networks A Decision Tree is a simple representation of classifying examples. It is a Supervised Machine Learning where the data is continuously split according to a certain parameter. Decision trees are commonly used in operations research and operations management. If in practice, decisions have to be taken online with no recall under incomplete knowledge, a decision tree should be paralleled by a probability model as the best choice model or online selection model algorithm. Another use of decision trees is as a descriptive means for calculating conditional probabilities. A decision tree has mainly three components: Root Nodes: It represents the entire population or sample and this further gets divided into two or more homogeneous sets.Edges/Branch: Represents a decision rule and connect to the next node.Leaf nodes: Leaf nodes are the nodes of the tree that have no additional nodes coming off them. They don’t split the data any further Root Nodes: It represents the entire population or sample and this further gets divided into two or more homogeneous sets. Edges/Branch: Represents a decision rule and connect to the next node. Leaf nodes: Leaf nodes are the nodes of the tree that have no additional nodes coming off them. They don’t split the data any further Decision Tree is a flow chart like structure use axis-aligned linear decision boundaries to partition or bisect data Divide and conquer approach Packages and Requirements Pkg.add(“DecisionTree”) Pkg.add(“DataFrames”) Pkg.add(“Gadly”) Julia # using the packagesusing DataFramesusing DecisionTree # Loading the Data# https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/df = readtable("breastc.csv") Output: Julia # using gadly packageusing Gadfly plot(df, x = Xfeatures, y = Ylabel, Geom.histogram, color = :Class, Guide.xlabel("Features")) Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Get array dimensions and size of a dimension in Julia - size() Method Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Exception handling in Julia Getting the maximum value from a list in Julia - max() Method Working with Excel Files in Julia Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Getting the absolute value of a number in Julia - abs() Method Working with Date and Time in Julia
[ { "code": null, "e": 24544, "s": 24516, "text": "\n01 Nov, 2020" }, { "code": null, "e": 24804, "s": 24544, "text": "In statistics in Julia, classification is the problem of identifying to which of a set of categories (sub-populations) a new observation belongs, on the basis of a training set of data containing observations (or instances) whose category membership is known." }, { "code": null, "e": 24996, "s": 24804, "text": "In the terminology of machine learning, classification is considered an instance of supervised learning, i.e., learning where a training set of correctly identified observations is available." }, { "code": null, "e": 25053, "s": 24996, "text": "Some of the classification techniques which we have are:" }, { "code": null, "e": 25211, "s": 25053, "text": "Linear Classifiers: Logistic Regression, Naive Bayes ClassifierNearest NeighborSupport Vector MachinesDecision TreesBoosted TreesRandom ForestNeural Networks" }, { "code": null, "e": 25275, "s": 25211, "text": "Linear Classifiers: Logistic Regression, Naive Bayes Classifier" }, { "code": null, "e": 25292, "s": 25275, "text": "Nearest Neighbor" }, { "code": null, "e": 25316, "s": 25292, "text": "Support Vector Machines" }, { "code": null, "e": 25331, "s": 25316, "text": "Decision Trees" }, { "code": null, "e": 25345, "s": 25331, "text": "Boosted Trees" }, { "code": null, "e": 25359, "s": 25345, "text": "Random Forest" }, { "code": null, "e": 25375, "s": 25359, "text": "Neural Networks" }, { "code": null, "e": 25550, "s": 25375, "text": "A Decision Tree is a simple representation of classifying examples. It is a Supervised Machine Learning where the data is continuously split according to a certain parameter." }, { "code": null, "e": 25947, "s": 25550, "text": "Decision trees are commonly used in operations research and operations management. If in practice, decisions have to be taken online with no recall under incomplete knowledge, a decision tree should be paralleled by a probability model as the best choice model or online selection model algorithm. Another use of decision trees is as a descriptive means for calculating conditional probabilities." }, { "code": null, "e": 25992, "s": 25947, "text": "A decision tree has mainly three components:" }, { "code": null, "e": 26318, "s": 25992, "text": "Root Nodes: It represents the entire population or sample and this further gets divided into two or more homogeneous sets.Edges/Branch: Represents a decision rule and connect to the next node.Leaf nodes: Leaf nodes are the nodes of the tree that have no additional nodes coming off them. They don’t split the data any further" }, { "code": null, "e": 26441, "s": 26318, "text": "Root Nodes: It represents the entire population or sample and this further gets divided into two or more homogeneous sets." }, { "code": null, "e": 26512, "s": 26441, "text": "Edges/Branch: Represents a decision rule and connect to the next node." }, { "code": null, "e": 26646, "s": 26512, "text": "Leaf nodes: Leaf nodes are the nodes of the tree that have no additional nodes coming off them. They don’t split the data any further" }, { "code": null, "e": 26691, "s": 26646, "text": "Decision Tree is a flow chart like structure" }, { "code": null, "e": 26763, "s": 26691, "text": "use axis-aligned linear decision boundaries to partition or bisect data" }, { "code": null, "e": 26791, "s": 26763, "text": "Divide and conquer approach" }, { "code": null, "e": 26817, "s": 26791, "text": "Packages and Requirements" }, { "code": null, "e": 26841, "s": 26817, "text": "Pkg.add(“DecisionTree”)" }, { "code": null, "e": 26863, "s": 26841, "text": "Pkg.add(“DataFrames”)" }, { "code": null, "e": 26880, "s": 26863, "text": "Pkg.add(“Gadly”)" }, { "code": null, "e": 26886, "s": 26880, "text": "Julia" }, { "code": "# using the packagesusing DataFramesusing DecisionTree # Loading the Data# https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/df = readtable(\"breastc.csv\")", "e": 27074, "s": 26886, "text": null }, { "code": null, "e": 27082, "s": 27074, "text": "Output:" }, { "code": null, "e": 27088, "s": 27082, "text": "Julia" }, { "code": "# using gadly packageusing Gadfly plot(df, x = Xfeatures, y = Ylabel, Geom.histogram, color = :Class, Guide.xlabel(\"Features\"))", "e": 27231, "s": 27088, "text": null }, { "code": null, "e": 27239, "s": 27231, "text": "Output:" }, { "code": null, "e": 27245, "s": 27239, "text": "Julia" }, { "code": null, "e": 27343, "s": 27245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27413, "s": 27343, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 27461, "s": 27413, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 27531, "s": 27461, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 27590, "s": 27531, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 27618, "s": 27590, "text": "Exception handling in Julia" }, { "code": null, "e": 27680, "s": 27618, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 27714, "s": 27680, "text": "Working with Excel Files in Julia" }, { "code": null, "e": 27787, "s": 27714, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 27850, "s": 27787, "text": "Getting the absolute value of a number in Julia - abs() Method" } ]
How to use HTML5 localStorage and sessionStorage?
HTML5 introduced two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome the following drawbacks. Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data. Cookies are limited to about 4 KB of data. Not enough to store required data. The two mechanisms for storage are session storage and local storage and they would be used to handle different situations. The Session Storage is designed for scenarios where the user is carrying out a single transaction but could be carrying out multiple transactions in different windows at the same time. You can try to run the following to set a session variable and access that variable Live Demo <!DOCTYPE HTML> <html> <body> <script type="text/javascript"> if( sessionStorage.hits ){ sessionStorage.hits = Number(sessionStorage.hits) +1; } else{ sessionStorage.hits = 1; } document.write("Total Hits :" + sessionStorage.hits ); </script> <p>Refresh the page to increase number of hits.</p> <p>Close the window and open it again and check the result.</p> </body> </html> The Local Storage is designed for storage that spans multiple windows and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons. You can try to run the following code to set a local storage variable and access that variable every time this page is accessed, even next time when you open the window. Live Demo <!DOCTYPE HTML> <html> <body> <script type="text/javascript"> if( localStorage.hits ){ localStorage.hits = Number(localStorage.hits) +1; } else{ localStorage.hits = 1; } document.write("Total Hits :" + localStorage.hits ); </script> <p>Refresh the page to increase number of hits.</p> <p>Close the window and open it again and check the result.</p> </body> </html>
[ { "code": null, "e": 1216, "s": 1062, "text": "HTML5 introduced two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome the following drawbacks." }, { "code": null, "e": 1335, "s": 1216, "text": "Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data." }, { "code": null, "e": 1413, "s": 1335, "text": "Cookies are limited to about 4 KB of data. Not enough to store required data." }, { "code": null, "e": 1537, "s": 1413, "text": "The two mechanisms for storage are session storage and local storage and they would be used to handle different situations." }, { "code": null, "e": 1722, "s": 1537, "text": "The Session Storage is designed for scenarios where the user is carrying out a single transaction but could be carrying out multiple transactions in different windows at the same time." }, { "code": null, "e": 1806, "s": 1722, "text": "You can try to run the following to set a session variable and access that variable" }, { "code": null, "e": 1816, "s": 1806, "text": "Live Demo" }, { "code": null, "e": 2281, "s": 1816, "text": "<!DOCTYPE HTML>\n<html>\n <body>\n <script type=\"text/javascript\">\n if( sessionStorage.hits ){\n sessionStorage.hits = Number(sessionStorage.hits) +1;\n } else{\n sessionStorage.hits = 1;\n }\n document.write(\"Total Hits :\" + sessionStorage.hits );\n </script>\n <p>Refresh the page to increase number of hits.</p>\n <p>Close the window and open it again and check the result.</p>\n </body>\n</html>" }, { "code": null, "e": 2567, "s": 2281, "text": "The Local Storage is designed for storage that spans multiple windows and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons." }, { "code": null, "e": 2737, "s": 2567, "text": "You can try to run the following code to set a local storage variable and access that variable every time this page is accessed, even next time when you open the window." }, { "code": null, "e": 2747, "s": 2737, "text": "Live Demo" }, { "code": null, "e": 3202, "s": 2747, "text": "<!DOCTYPE HTML>\n<html>\n <body>\n <script type=\"text/javascript\">\n if( localStorage.hits ){\n localStorage.hits = Number(localStorage.hits) +1;\n } else{\n localStorage.hits = 1;\n }\n document.write(\"Total Hits :\" + localStorage.hits );\n </script>\n <p>Refresh the page to increase number of hits.</p>\n <p>Close the window and open it again and check the result.</p>\n </body>\n</html>" } ]
How to Build a Simple Marketing Mix Model with Python | by Terence Shin | Towards Data Science
IntroductionWhat You’ll LearnWhat is a Marketing Mix Model?Walkthrough of the Marketing Mix Model Introduction What You’ll Learn What is a Marketing Mix Model? Walkthrough of the Marketing Mix Model If you enjoy this, be sure to subscribe to never miss another article on data science guides, tricks and tips, life lessons, and more! Due to high demand, I’m back with another step-by-step data science project with Python code! This one is pretty interesting because there’s so much more that you can do that goes beyond what I’m about to present — however, I believe that this provides a good start for anyone that’s interested in marketing and data science. This project is related to a common real-life problem that many businesses face — marketing attribution. This is the science of determining how much each marketing channel is contributing to sales/conversions. The difficulty typically arises when you introduce offline marketing channels, like TV or radio, because there’s no direct way of measuring the impact of these channels. You’ll learn what a Marketing Mix Model (MMM) is and how you can use it to assess various marketing channels You’ll learn fundamental concepts and techniques when you explore your data You’ll learn what Ordinary Least Squares (OLS) regression is, how to implement it, and how to assess it A Marketing Mix Model (MMM) is a technique used to determine market attribution. Specifically, it is a statistical technique (usually regression) on marketing and sales data to estimate the impact of various marketing channels. Unlike Attribution Modeling, another technique used for marketing attribution, Marketing Mix Models attempt to measure the impact of immeasurable marketing channels, like TV, radio, and newspapers. Generally, your output variable will be sales or conversions, but can also be things like website traffic. Your input variables typically consist of marketing spend by channel by period (day, week, month, quarter, etc...), but can also include other variables which we’ll get to later. For this project, we’re going to use a fictional dataset that consists of marketing spend on TV, radio, and newspaper, as well as the corresponding dollar sales by period. Dataset is here. First, we’re going to import the libraries and read the data, as usual. import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf = pd.read_csv("../input/advertising.csv/Advertising.csv") Next, we’re going to look at the variables in the dataset and understand what we’re working with. print(df.columns)df.describe() Instantly, you can see that the variable, Unnamed: 0, is essentially an index starting at 1 — so we’re going to remove it. df = df.copy().drop(['Unnamed: 0'],axis=1) Because this is a fictional and simple dataset, there are a lot of steps that we don’t have to worry about, like handling missing values. But generally, you want to make sure that your dataset is clean and ready for EDA. The first thing that I always like to do is create a correlation matrix because it allows me to get a better understanding of the relationships between my variables in a glance. corr = df.corr()sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True)) Immediately, we can see that there’s a strong correlation between TV and sales (0.78), a moderate correlation between radio and sales (0.58), and a weak correlation between newspaper and sales (0.23). It’s still too early to conclude anything but this is good to keep into consideration moving forward. Similarly to the correlation matrix, I want to create a pairplot of my variables so that I can understand the relationships between my variables even more. sns.pairplot(df) This seems to be in line with the correlation matrix, as there appears to be a strong relationship between TV and sales, less for radio, and even less for newspapers. Feature importance allows you to determine how “important” each input variable is to predict the output variable. A feature is important if shuffling its values increases model error because this means the model relied on the feature for the prediction. We’re going to quickly create a random forest model so that we can determine the importance of each feature. # Setting X and y variablesX = df.loc[:, df.columns != 'sales']y = df['sales']# Building Random Forest modelfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_absolute_error as maeX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25, random_state=0)model = RandomForestRegressor(random_state=1)model.fit(X_train, y_train)pred = model.predict(X_test)# Visualizing Feature Importancefeat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(25).plot(kind='barh',figsize=(10,10)) There seems to be a pattern, where TV is the most important, followed by radio, leaving newspaper last. Let’s actually build our OLS regression model. OLS, short for Ordinary Least Squares, is a method used to estimate the parameters in a linear regression model. Check out my article, Linear Regression Explained in 5 Minutes if you don’t know what regression is! What makes Python so amazing is that it already has a library that we can use to create an OLS model: import statsmodels.formula.api as smmodel = sm.ols(formula="sales~TV+radio+newspaper", data=df).fit()print(model.summary()) .summary() provides us with an abundance of insights on our model. I’m going to point out two main things that are most useful for us in this: The Adj. R-squared is 0.896, which means that almost 90 of all variations in our data can be explained by our model, which is pretty good! If you want to learn more about r-squared and other metrics that are used to evaluate machine learning models, check out my article here.The p-values for TV and radio are less than 0.000, but the p-value for newspaper is 0.86, which indicates that newspaper spend has no significant impact on sales. The Adj. R-squared is 0.896, which means that almost 90 of all variations in our data can be explained by our model, which is pretty good! If you want to learn more about r-squared and other metrics that are used to evaluate machine learning models, check out my article here. The p-values for TV and radio are less than 0.000, but the p-value for newspaper is 0.86, which indicates that newspaper spend has no significant impact on sales. Next, let’s graph the predicted sales values with the actual sales values to visually see how our model performs: # Defining Actual and Predicted valuesy_pred = model.predict()labels = df['sales']df_temp = pd.DataFrame({'Actual': labels, 'Predicted':y_pred})df_temp.head()# Creating Line Graphfrom matplotlib.pyplot import figurefigure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')y1 = df_temp['Actual']y2 = df_temp['Predicted']plt.plot(y1, label = 'Actual')plt.plot(y2, label = 'Predicted')plt.legend()plt.show() Not bad! It seems like this model does a good job of predicting sales given TV, radio, and newspaper spend. In reality, the data probably won’t be as clean as this and the results probably won’t look as pretty. In practice, you’ll probably want to consider more variables that impact sales, including but not limited to: Seasonality: It’s almost always the case that company sales are seasonal. For example, a snowboard company’s sales would be much higher during the winter than in the summer. In practice, you’ll want to include a variable to account for seasonality. Carryover Effects: The impact of marketing is not usually immediate. In many cases, consumers need time to think about their purchasing decisions after seeing advertisements. Carryover effects account for the time lag between when consumers are exposed to an ad and their response to the ad. Base sales vs incremental sales: Not every sale is attributed to marketing. If a company spent absolutely nothing on marketing and still made sales, this would be called its base sales. Thus, to take it a step further, you could try to model advertising spend on incremental sales as opposed to total sales. I hope you enjoyed this project — let me know what other kinds of projects you’d like to see! If you like my work and want to support me... The BEST way to support me is by following me on Medium here.Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!Also, be one of the FIRST to subscribe to my new YouTube channel here! There are no videos yet but it’s coming!Follow me on LinkedIn here.Sign up on my email list here.Check out my website, terenceshin.com. The BEST way to support me is by following me on Medium here. Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here! Also, be one of the FIRST to subscribe to my new YouTube channel here! There are no videos yet but it’s coming! Follow me on LinkedIn here. Sign up on my email list here. Check out my website, terenceshin.com.
[ { "code": null, "e": 270, "s": 172, "text": "IntroductionWhat You’ll LearnWhat is a Marketing Mix Model?Walkthrough of the Marketing Mix Model" }, { "code": null, "e": 283, "s": 270, "text": "Introduction" }, { "code": null, "e": 301, "s": 283, "text": "What You’ll Learn" }, { "code": null, "e": 332, "s": 301, "text": "What is a Marketing Mix Model?" }, { "code": null, "e": 371, "s": 332, "text": "Walkthrough of the Marketing Mix Model" }, { "code": null, "e": 506, "s": 371, "text": "If you enjoy this, be sure to subscribe to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 832, "s": 506, "text": "Due to high demand, I’m back with another step-by-step data science project with Python code! This one is pretty interesting because there’s so much more that you can do that goes beyond what I’m about to present — however, I believe that this provides a good start for anyone that’s interested in marketing and data science." }, { "code": null, "e": 1212, "s": 832, "text": "This project is related to a common real-life problem that many businesses face — marketing attribution. This is the science of determining how much each marketing channel is contributing to sales/conversions. The difficulty typically arises when you introduce offline marketing channels, like TV or radio, because there’s no direct way of measuring the impact of these channels." }, { "code": null, "e": 1321, "s": 1212, "text": "You’ll learn what a Marketing Mix Model (MMM) is and how you can use it to assess various marketing channels" }, { "code": null, "e": 1397, "s": 1321, "text": "You’ll learn fundamental concepts and techniques when you explore your data" }, { "code": null, "e": 1501, "s": 1397, "text": "You’ll learn what Ordinary Least Squares (OLS) regression is, how to implement it, and how to assess it" }, { "code": null, "e": 1729, "s": 1501, "text": "A Marketing Mix Model (MMM) is a technique used to determine market attribution. Specifically, it is a statistical technique (usually regression) on marketing and sales data to estimate the impact of various marketing channels." }, { "code": null, "e": 1927, "s": 1729, "text": "Unlike Attribution Modeling, another technique used for marketing attribution, Marketing Mix Models attempt to measure the impact of immeasurable marketing channels, like TV, radio, and newspapers." }, { "code": null, "e": 2213, "s": 1927, "text": "Generally, your output variable will be sales or conversions, but can also be things like website traffic. Your input variables typically consist of marketing spend by channel by period (day, week, month, quarter, etc...), but can also include other variables which we’ll get to later." }, { "code": null, "e": 2385, "s": 2213, "text": "For this project, we’re going to use a fictional dataset that consists of marketing spend on TV, radio, and newspaper, as well as the corresponding dollar sales by period." }, { "code": null, "e": 2402, "s": 2385, "text": "Dataset is here." }, { "code": null, "e": 2474, "s": 2402, "text": "First, we’re going to import the libraries and read the data, as usual." }, { "code": null, "e": 2624, "s": 2474, "text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdf = pd.read_csv(\"../input/advertising.csv/Advertising.csv\")" }, { "code": null, "e": 2722, "s": 2624, "text": "Next, we’re going to look at the variables in the dataset and understand what we’re working with." }, { "code": null, "e": 2753, "s": 2722, "text": "print(df.columns)df.describe()" }, { "code": null, "e": 2876, "s": 2753, "text": "Instantly, you can see that the variable, Unnamed: 0, is essentially an index starting at 1 — so we’re going to remove it." }, { "code": null, "e": 2919, "s": 2876, "text": "df = df.copy().drop(['Unnamed: 0'],axis=1)" }, { "code": null, "e": 3140, "s": 2919, "text": "Because this is a fictional and simple dataset, there are a lot of steps that we don’t have to worry about, like handling missing values. But generally, you want to make sure that your dataset is clean and ready for EDA." }, { "code": null, "e": 3318, "s": 3140, "text": "The first thing that I always like to do is create a correlation matrix because it allows me to get a better understanding of the relationships between my variables in a glance." }, { "code": null, "e": 3467, "s": 3318, "text": "corr = df.corr()sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap=sns.diverging_palette(220, 20, as_cmap=True))" }, { "code": null, "e": 3770, "s": 3467, "text": "Immediately, we can see that there’s a strong correlation between TV and sales (0.78), a moderate correlation between radio and sales (0.58), and a weak correlation between newspaper and sales (0.23). It’s still too early to conclude anything but this is good to keep into consideration moving forward." }, { "code": null, "e": 3926, "s": 3770, "text": "Similarly to the correlation matrix, I want to create a pairplot of my variables so that I can understand the relationships between my variables even more." }, { "code": null, "e": 3943, "s": 3926, "text": "sns.pairplot(df)" }, { "code": null, "e": 4110, "s": 3943, "text": "This seems to be in line with the correlation matrix, as there appears to be a strong relationship between TV and sales, less for radio, and even less for newspapers." }, { "code": null, "e": 4364, "s": 4110, "text": "Feature importance allows you to determine how “important” each input variable is to predict the output variable. A feature is important if shuffling its values increases model error because this means the model relied on the feature for the prediction." }, { "code": null, "e": 4473, "s": 4364, "text": "We’re going to quickly create a random forest model so that we can determine the importance of each feature." }, { "code": null, "e": 5094, "s": 4473, "text": "# Setting X and y variablesX = df.loc[:, df.columns != 'sales']y = df['sales']# Building Random Forest modelfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_absolute_error as maeX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.25, random_state=0)model = RandomForestRegressor(random_state=1)model.fit(X_train, y_train)pred = model.predict(X_test)# Visualizing Feature Importancefeat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(25).plot(kind='barh',figsize=(10,10))" }, { "code": null, "e": 5245, "s": 5094, "text": "There seems to be a pattern, where TV is the most important, followed by radio, leaving newspaper last. Let’s actually build our OLS regression model." }, { "code": null, "e": 5459, "s": 5245, "text": "OLS, short for Ordinary Least Squares, is a method used to estimate the parameters in a linear regression model. Check out my article, Linear Regression Explained in 5 Minutes if you don’t know what regression is!" }, { "code": null, "e": 5561, "s": 5459, "text": "What makes Python so amazing is that it already has a library that we can use to create an OLS model:" }, { "code": null, "e": 5685, "s": 5561, "text": "import statsmodels.formula.api as smmodel = sm.ols(formula=\"sales~TV+radio+newspaper\", data=df).fit()print(model.summary())" }, { "code": null, "e": 5828, "s": 5685, "text": ".summary() provides us with an abundance of insights on our model. I’m going to point out two main things that are most useful for us in this:" }, { "code": null, "e": 6267, "s": 5828, "text": "The Adj. R-squared is 0.896, which means that almost 90 of all variations in our data can be explained by our model, which is pretty good! If you want to learn more about r-squared and other metrics that are used to evaluate machine learning models, check out my article here.The p-values for TV and radio are less than 0.000, but the p-value for newspaper is 0.86, which indicates that newspaper spend has no significant impact on sales." }, { "code": null, "e": 6544, "s": 6267, "text": "The Adj. R-squared is 0.896, which means that almost 90 of all variations in our data can be explained by our model, which is pretty good! If you want to learn more about r-squared and other metrics that are used to evaluate machine learning models, check out my article here." }, { "code": null, "e": 6707, "s": 6544, "text": "The p-values for TV and radio are less than 0.000, but the p-value for newspaper is 0.86, which indicates that newspaper spend has no significant impact on sales." }, { "code": null, "e": 6821, "s": 6707, "text": "Next, let’s graph the predicted sales values with the actual sales values to visually see how our model performs:" }, { "code": null, "e": 7240, "s": 6821, "text": "# Defining Actual and Predicted valuesy_pred = model.predict()labels = df['sales']df_temp = pd.DataFrame({'Actual': labels, 'Predicted':y_pred})df_temp.head()# Creating Line Graphfrom matplotlib.pyplot import figurefigure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')y1 = df_temp['Actual']y2 = df_temp['Predicted']plt.plot(y1, label = 'Actual')plt.plot(y2, label = 'Predicted')plt.legend()plt.show()" }, { "code": null, "e": 7348, "s": 7240, "text": "Not bad! It seems like this model does a good job of predicting sales given TV, radio, and newspaper spend." }, { "code": null, "e": 7561, "s": 7348, "text": "In reality, the data probably won’t be as clean as this and the results probably won’t look as pretty. In practice, you’ll probably want to consider more variables that impact sales, including but not limited to:" }, { "code": null, "e": 7810, "s": 7561, "text": "Seasonality: It’s almost always the case that company sales are seasonal. For example, a snowboard company’s sales would be much higher during the winter than in the summer. In practice, you’ll want to include a variable to account for seasonality." }, { "code": null, "e": 8102, "s": 7810, "text": "Carryover Effects: The impact of marketing is not usually immediate. In many cases, consumers need time to think about their purchasing decisions after seeing advertisements. Carryover effects account for the time lag between when consumers are exposed to an ad and their response to the ad." }, { "code": null, "e": 8410, "s": 8102, "text": "Base sales vs incremental sales: Not every sale is attributed to marketing. If a company spent absolutely nothing on marketing and still made sales, this would be called its base sales. Thus, to take it a step further, you could try to model advertising spend on incremental sales as opposed to total sales." }, { "code": null, "e": 8504, "s": 8410, "text": "I hope you enjoyed this project — let me know what other kinds of projects you’d like to see!" }, { "code": null, "e": 8550, "s": 8504, "text": "If you like my work and want to support me..." }, { "code": null, "e": 8927, "s": 8550, "text": "The BEST way to support me is by following me on Medium here.Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!Also, be one of the FIRST to subscribe to my new YouTube channel here! There are no videos yet but it’s coming!Follow me on LinkedIn here.Sign up on my email list here.Check out my website, terenceshin.com." }, { "code": null, "e": 8989, "s": 8927, "text": "The BEST way to support me is by following me on Medium here." }, { "code": null, "e": 9099, "s": 8989, "text": "Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!" }, { "code": null, "e": 9211, "s": 9099, "text": "Also, be one of the FIRST to subscribe to my new YouTube channel here! There are no videos yet but it’s coming!" }, { "code": null, "e": 9239, "s": 9211, "text": "Follow me on LinkedIn here." }, { "code": null, "e": 9270, "s": 9239, "text": "Sign up on my email list here." } ]
Get the location of an element in Java ArrayList
The location of an element in an ArrayList can be obtained using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the ArrayList, then this method returns -1. A program that demonstrates this is given as follows − Live Demo import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The index of element C in ArrayList is: " + aList.indexOf("C")); System.out.println("The index of element F in ArrayList is: " + aList.indexOf("F")); } } The index of element C in ArrayList is: 2 The index of element F in ArrayList is: -1 Now let us understand the above program. The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.indexOf() returns the index of the first occurrence of “C” and “F” that is displayed. A code snippet which demonstrates this is as follows − List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The index of element C in ArrayList is: " + aList.indexOf("C")); System.out.println("The index of element F in ArrayList is: " + aList.indexOf("F"));
[ { "code": null, "e": 1336, "s": 1062, "text": "The location of an element in an ArrayList can be obtained using the method java.util.ArrayList.indexOf(). This method returns the index of the first occurrence of the element that is specified. If the element is not available in the ArrayList, then this method returns -1." }, { "code": null, "e": 1391, "s": 1336, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1402, "s": 1391, "text": " Live Demo" }, { "code": null, "e": 1852, "s": 1402, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n List aList = new ArrayList();\n aList.add(\"A\");\n aList.add(\"B\");\n aList.add(\"C\");\n aList.add(\"D\");\n aList.add(\"E\");\n System.out.println(\"The index of element C in ArrayList is: \" + aList.indexOf(\"C\"));\n System.out.println(\"The index of element F in ArrayList is: \" + aList.indexOf(\"F\"));\n }\n}" }, { "code": null, "e": 1937, "s": 1852, "text": "The index of element C in ArrayList is: 2\nThe index of element F in ArrayList is: -1" }, { "code": null, "e": 1978, "s": 1937, "text": "Now let us understand the above program." }, { "code": null, "e": 2228, "s": 1978, "text": "The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.indexOf() returns the index of the first occurrence of “C” and “F” that is displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2508, "s": 2228, "text": "List aList = new ArrayList();\naList.add(\"A\");\naList.add(\"B\");\naList.add(\"C\");\naList.add(\"D\");\naList.add(\"E\");\nSystem.out.println(\"The index of element C in ArrayList is: \" + aList.indexOf(\"C\"));\nSystem.out.println(\"The index of element F in ArrayList is: \" + aList.indexOf(\"F\"));" } ]
How to merge many TSV files by common key using Python Pandas? - GeeksforGeeks
23 Mar, 2022 For data analysis the most important thing is data and we need to prepare it before we can use it for analysis. Sometimes required data can be scattered in multiple files and we need to merge them. In this article, we are going to merge multiple TSV (Tab Separated Values) files with a common key. This can be possible by using the merge method of the pandas Python library. This method allows us to combine files by using a common key. Import pandas library Then read first two tsv files and merge them using pd.merge() function by setting the ‘on’ parameter to the common column present in both files. Then store the result in a new dataframe called ‘Output_df’. Store remaining files in a list. Run a loop that will iterate over these file names. Read these files one by one and merge them with ‘Output_df’ dataframe Save ‘Output_df’ in tsv file In this example, we will merge tsv files by using an inner join. We have taken four tsv files for this example as follows. Used file: Customer.tsv, Account.tsv, Branch.tsv, Loan.tsv Python3 # Import pandas libraryimport pandas as pd # Read first two csv files with '\t' separatortsv1 = pd.read_csv("Documents/Customer.tsv", sep='\t')tsv2 = pd.read_csv("Documents/Account.tsv", sep='\t') # store the result in Output_df dataframe.# Here common column is 'ID' columnOutput_df = pd.merge(tsv1, tsv2, on='ID', how='inner') # store remaining file names in listtsv_files = ["Branch.tsv", "Loan.tsv"] # One by one read tsv files and merge with# 'Output_df' dataframe and again store# the final result in Output_dffor i in tsv_files: path = "Documents/"+i tsv = pd.read_csv(path, sep='\t') Output_df = pd.merge(Output_df, tsv, on='ID', how='inner') # Now store the 'Output_df'# in tsv file 'Output.tsv'Output_df.to_csv("Documents/Output.tsv", sep="\t", header=True, index=False) Output: Output.tsv In this example, we will merge tsv files by using an outer join. We have taken four tsv files for this example as follows. Used file: Course.tsv, Teacher.tsv, Credits.tsv, Marks.tsv Python3 # Import pandas libraryimport pandas as pd # Read first two csv files with '\t' separatortsv3 = pd.read_csv("Documents/Course.tsv", sep='\t')tsv4 = pd.read_csv("Documents/Teacher.tsv", sep='\t') # store the result in Output_df dataframe.# Here common column is 'Course_ID' columnOutput_df2 = pd.merge(tsv3, tsv4, on='Course_ID', how='outer') # store remaining file names in listtsv_files = ["Credits.tsv", "Marks.tsv"] # One by one read tsv files and merge with# 'Output_df2' dataframe and again store# the final result in 'Output_df2'for i in tsv_files: path = "Documents/"+i tsv = pd.read_csv(path, sep='\t') Output_df2 = pd.merge(Output_df2, tsv, on='Course_ID', how='outer') # Now store the 'Output_df2' in tsv file 'Output_outer.tsv'# Here we replacing nan values with NAOutput_df2.to_csv("Documents/Output_outer.tsv", sep="\t", header=True, index=False, na_rep="NA") Output: rkbhola5 Picked Python pandas-io Python-pandas 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n23 Mar, 2022" }, { "code": null, "e": 24338, "s": 23901, "text": "For data analysis the most important thing is data and we need to prepare it before we can use it for analysis. Sometimes required data can be scattered in multiple files and we need to merge them. In this article, we are going to merge multiple TSV (Tab Separated Values) files with a common key. This can be possible by using the merge method of the pandas Python library. This method allows us to combine files by using a common key." }, { "code": null, "e": 24360, "s": 24338, "text": "Import pandas library" }, { "code": null, "e": 24566, "s": 24360, "text": "Then read first two tsv files and merge them using pd.merge() function by setting the ‘on’ parameter to the common column present in both files. Then store the result in a new dataframe called ‘Output_df’." }, { "code": null, "e": 24599, "s": 24566, "text": "Store remaining files in a list." }, { "code": null, "e": 24722, "s": 24599, "text": "Run a loop that will iterate over these file names. Read these files one by one and merge them with ‘Output_df’ dataframe" }, { "code": null, "e": 24751, "s": 24722, "text": "Save ‘Output_df’ in tsv file" }, { "code": null, "e": 24874, "s": 24751, "text": "In this example, we will merge tsv files by using an inner join. We have taken four tsv files for this example as follows." }, { "code": null, "e": 24933, "s": 24874, "text": "Used file: Customer.tsv, Account.tsv, Branch.tsv, Loan.tsv" }, { "code": null, "e": 24941, "s": 24933, "text": "Python3" }, { "code": "# Import pandas libraryimport pandas as pd # Read first two csv files with '\\t' separatortsv1 = pd.read_csv(\"Documents/Customer.tsv\", sep='\\t')tsv2 = pd.read_csv(\"Documents/Account.tsv\", sep='\\t') # store the result in Output_df dataframe.# Here common column is 'ID' columnOutput_df = pd.merge(tsv1, tsv2, on='ID', how='inner') # store remaining file names in listtsv_files = [\"Branch.tsv\", \"Loan.tsv\"] # One by one read tsv files and merge with# 'Output_df' dataframe and again store# the final result in Output_dffor i in tsv_files: path = \"Documents/\"+i tsv = pd.read_csv(path, sep='\\t') Output_df = pd.merge(Output_df, tsv, on='ID', how='inner') # Now store the 'Output_df'# in tsv file 'Output.tsv'Output_df.to_csv(\"Documents/Output.tsv\", sep=\"\\t\", header=True, index=False)", "e": 25807, "s": 24941, "text": null }, { "code": null, "e": 25815, "s": 25807, "text": "Output:" }, { "code": null, "e": 25826, "s": 25815, "text": "Output.tsv" }, { "code": null, "e": 25949, "s": 25826, "text": "In this example, we will merge tsv files by using an outer join. We have taken four tsv files for this example as follows." }, { "code": null, "e": 26008, "s": 25949, "text": "Used file: Course.tsv, Teacher.tsv, Credits.tsv, Marks.tsv" }, { "code": null, "e": 26016, "s": 26008, "text": "Python3" }, { "code": "# Import pandas libraryimport pandas as pd # Read first two csv files with '\\t' separatortsv3 = pd.read_csv(\"Documents/Course.tsv\", sep='\\t')tsv4 = pd.read_csv(\"Documents/Teacher.tsv\", sep='\\t') # store the result in Output_df dataframe.# Here common column is 'Course_ID' columnOutput_df2 = pd.merge(tsv3, tsv4, on='Course_ID', how='outer') # store remaining file names in listtsv_files = [\"Credits.tsv\", \"Marks.tsv\"] # One by one read tsv files and merge with# 'Output_df2' dataframe and again store# the final result in 'Output_df2'for i in tsv_files: path = \"Documents/\"+i tsv = pd.read_csv(path, sep='\\t') Output_df2 = pd.merge(Output_df2, tsv, on='Course_ID', how='outer') # Now store the 'Output_df2' in tsv file 'Output_outer.tsv'# Here we replacing nan values with NAOutput_df2.to_csv(\"Documents/Output_outer.tsv\", sep=\"\\t\", header=True, index=False, na_rep=\"NA\")", "e": 26941, "s": 26016, "text": null }, { "code": null, "e": 26949, "s": 26941, "text": "Output:" }, { "code": null, "e": 26958, "s": 26949, "text": "rkbhola5" }, { "code": null, "e": 26965, "s": 26958, "text": "Picked" }, { "code": null, "e": 26982, "s": 26965, "text": "Python pandas-io" }, { "code": null, "e": 26996, "s": 26982, "text": "Python-pandas" }, { "code": null, "e": 27003, "s": 26996, "text": "Python" }, { "code": null, "e": 27101, "s": 27003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27110, "s": 27101, "text": "Comments" }, { "code": null, "e": 27123, "s": 27110, "text": "Old Comments" }, { "code": null, "e": 27155, "s": 27123, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27211, "s": 27155, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27253, "s": 27211, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27295, "s": 27253, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27331, "s": 27295, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27353, "s": 27331, "text": "Defaultdict in Python" }, { "code": null, "e": 27392, "s": 27353, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27419, "s": 27392, "text": "Python Classes and Objects" }, { "code": null, "e": 27450, "s": 27419, "text": "Python | os.path.join() method" } ]
Software Analysis & Design Tools
Software analysis and design includes all activities, which help the transformation of requirement specification into implementation. Requirement specifications specify all functional and non-functional expectations from the software. These requirement specifications come in the shape of human readable and understandable documents, to which a computer has nothing to do. Software analysis and design is the intermediate stage, which helps human-readable requirements to be transformed into actual code. Let us see few analysis and design tools used by software designers: Data flow diagram is graphical representation of flow of data in an information system. It is capable of depicting incoming data flow, outgoing data flow and stored data. The DFD does not mention anything about how data flows through the system. There is a prominent difference between DFD and Flowchart. The flowchart depicts flow of control in program modules. DFDs depict flow of data in the system at various levels. DFD does not contain any control or branch elements. Data Flow Diagrams are either Logical or Physical. Logical DFD - This type of DFD concentrates on the system process, and flow of data in the system.For example in a Banking software system, how data is moved between different entities. Physical DFD - This type of DFD shows how the data flow is actually implemented in the system. It is more specific and close to the implementation. DFD can represent Source, destination, storage and flow of data using the following set of components - Entities - Entities are source and destination of information data. Entities are represented by a rectangles with their respective names. Process - Activities and action taken on the data are represented by Circle or Round-edged rectangles. Data Storage - There are two variants of data storage - it can either be represented as a rectangle with absence of both smaller sides or as an open-sided rectangle with only one side missing. Data Flow - Movement of data is shown by pointed arrows. Data movement is shown from the base of arrow as its source towards head of the arrow as destination. Level 0 - Highest abstraction level DFD is known as Level 0 DFD, which depicts the entire information system as one diagram concealing all the underlying details. Level 0 DFDs are also known as context level DFDs. Level 1 - The Level 0 DFD is broken down into more specific, Level 1 DFD. Level 1 DFD depicts basic modules in the system and flow of data among various modules. Level 1 DFD also mentions basic processes and sources of information. Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1. Higher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved. Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1. Higher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved. Structure chart is a chart derived from Data Flow Diagram. It represents the system in more detail than DFD. It breaks down the entire system into lowest functional modules, describes functions and sub-functions of each module of the system to a greater detail than DFD. Structure chart represents hierarchical structure of modules. At each layer a specific task is performed. Here are the symbols used in construction of structure charts - Module - It represents process or subroutine or task. A control module branches to more than one sub-module. Library Modules are re-usable and invokable from any module. Condition - It is represented by small diamond at the base of module. It depicts that control module can select any of sub-routine based on some condition. Jump - An arrow is shown pointing inside the module to depict that the control will jump in the middle of the sub-module. Loop - A curved arrow represents loop in the module. All sub-modules covered by loop repeat execution of module. Data flow - A directed arrow with empty circle at the end represents data flow. Control flow - A directed arrow with filled circle at the end represents control flow. HIPO (Hierarchical Input Process Output) diagram is a combination of two organized method to analyze the system and provide the means of documentation. HIPO model was developed by IBM in year 1970. HIPO diagram represents the hierarchy of modules in the software system. Analyst uses HIPO diagram in order to obtain high-level view of system functions. It decomposes functions into sub-functions in a hierarchical manner. It depicts the functions performed by system. HIPO diagrams are good for documentation purpose. Their graphical representation makes it easier for designers and managers to get the pictorial idea of the system structure. In contrast to IPO (Input Process Output) diagram, which depicts the flow of control and data in a module, HIPO does not provide any information about data flow or control flow. Both parts of HIPO diagram, Hierarchical presentation and IPO Chart are used for structure design of software program as well as documentation of the same. Most programmers are unaware of the large picture of software so they only rely on what their managers tell them to do. It is the responsibility of higher software management to provide accurate information to the programmers to develop accurate yet fast code. Other forms of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people. Hence, analysts and designers of the software come up with tools such as Structured English. It is nothing but the description of what is required to code and how to code it. Structured English helps the programmer to write error-free code. Other form of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people. Here, both Structured English and Pseudo-Code tries to mitigate that understanding gap. Structured English is the It uses plain English words in structured programming paradigm. It is not the ultimate code but a kind of description what is required to code and how to code it. The following are some tokens of structured programming. IF-THEN-ELSE, DO-WHILE-UNTIL Analyst uses the same variable and data name, which are stored in Data Dictionary, making it much simpler to write and understand the code. We take the same example of Customer Authentication in the online shopping environment. This procedure to authenticate customer can be written in Structured English as: Enter Customer_Name SEEK Customer_Name in Customer_Name_DB file IF Customer_Name found THEN Call procedure USER_PASSWORD_AUTHENTICATE() ELSE PRINT error message Call procedure NEW_CUSTOMER_REQUEST() ENDIF The code written in Structured English is more like day-to-day spoken English. It can not be implemented directly as a code of software. Structured English is independent of programming language. Pseudo code is written more close to programming language. It may be considered as augmented programming language, full of comments and descriptions. Pseudo code avoids variable declaration but they are written using some actual programming language’s constructs, like C, Fortran, Pascal etc. Pseudo code contains more programming details than Structured English. It provides a method to perform the task, as if a computer is executing the code. Program to print Fibonacci up to n numbers. void function Fibonacci Get value of n; Set value of a to 1; Set value of b to 1; Initialize I to 0 for (i=0; i< n; i++) { if a greater than b { Increase b by a; Print b; } else if b greater than a { increase a by b; print a; } } A Decision table represents conditions and the respective actions to be taken to address them, in a structured tabular format. It is a powerful tool to debug and prevent errors. It helps group similar information into a single table and then by combining tables it delivers easy and convenient decision-making. To create the decision table, the developer must follow basic four steps: Identify all possible conditions to be addressed Determine actions for all identified conditions Create Maximum possible rules Define action for each rule Decision Tables should be verified by end-users and can lately be simplified by eliminating duplicate rules and actions. Let us take a simple example of day-to-day problem with our Internet connectivity. We begin by identifying all problems that can arise while starting the internet and their respective possible solutions. We list all possible problems under column conditions and the prospective actions under column Actions. Entity-Relationship model is a type of database model based on the notion of real world entities and relationship among them. We can map real world scenario onto ER database model. ER Model creates a set of entities with their attributes, a set of constraints and relation among them. ER Model is best used for the conceptual design of database. ER Model can be represented as follows : Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain. For example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc. Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain. For example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc. Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities. Mapping cardinalities: one to one one to many many to one many to many Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities. Mapping cardinalities: one to one one to many many to one many to many Data dictionary is the centralized collection of information about data. It stores meaning and origin of data, its relationship with other data, data format for usage etc. Data dictionary has rigorous definitions of all names in order to facilitate user and software designers. Data dictionary is often referenced as meta-data (data about data) repository. It is created along with DFD (Data Flow Diagram) model of software program and is expected to be updated whenever DFD is changed or updated. The data is referenced via data dictionary while designing and implementing software. Data dictionary removes any chances of ambiguity. It helps keeping work of programmers and designers synchronized while using same object reference everywhere in the program. Data dictionary provides a way of documentation for the complete database system in one place. Validation of DFD is carried out using data dictionary. Data dictionary should contain information about the following Data Flow Data Structure Data Elements Data Stores Data Processing Data Flow is described by means of DFDs as studied earlier and represented in algebraic form as described. Address = House No + (Street / Area) + City + State Course ID = Course Number + Course Name + Course Level + Course Grades Data elements consist of Name and descriptions of Data and Control Items, Internal or External data stores etc. with the following details: Primary Name Secondary Name (Alias) Use-case (How and where to use) Content Description (Notation etc. ) Supplementary Information (preset values, constraints etc.) It stores the information from where the data enters into the system and exists out of the system. The Data Store may include - Files Internal to software. External to software but on the same machine. External to software and system, located on different machine. Internal to software. External to software but on the same machine. External to software and system, located on different machine. Tables Naming convention Indexing property Naming convention Indexing property There are two types of Data Processing: Logical: As user sees it Physical: As software sees it 80 Lectures 7.5 hours Arnab Chakraborty 10 Lectures 1 hours Zach Miller 17 Lectures 1.5 hours Zach Miller 60 Lectures 5 hours John Shea 99 Lectures 10 hours Daniel IT 62 Lectures 5 hours GlobalETraining Print Add Notes Bookmark this page
[ { "code": null, "e": 2413, "s": 2037, "text": "Software analysis and design includes all activities, which help the transformation of requirement specification into implementation. Requirement specifications specify all functional and non-functional expectations from the software. These requirement specifications come in the shape of human readable and understandable documents, to which a computer has nothing to do. " }, { "code": null, "e": 2545, "s": 2413, "text": "Software analysis and design is the intermediate stage, which helps human-readable requirements to be transformed into actual code." }, { "code": null, "e": 2614, "s": 2545, "text": "Let us see few analysis and design tools used by software designers:" }, { "code": null, "e": 2860, "s": 2614, "text": "Data flow diagram is graphical representation of flow of data in an information system. It is capable of depicting incoming data flow, outgoing data flow and stored data. The DFD does not mention anything about how data flows through the system." }, { "code": null, "e": 3088, "s": 2860, "text": "There is a prominent difference between DFD and Flowchart. The flowchart depicts flow of control in program modules. DFDs depict flow of data in the system at various levels. DFD does not contain any control or branch elements." }, { "code": null, "e": 3139, "s": 3088, "text": "Data Flow Diagrams are either Logical or Physical." }, { "code": null, "e": 3325, "s": 3139, "text": "Logical DFD - This type of DFD concentrates on the system process, and flow of data in the system.For example in a Banking software system, how data is moved between different entities." }, { "code": null, "e": 3474, "s": 3325, "text": "Physical DFD - This type of DFD shows how the data flow is actually implemented in the system. It is more specific and close to the implementation." }, { "code": null, "e": 3578, "s": 3474, "text": "DFD can represent Source, destination, storage and flow of data using the following set of components -" }, { "code": null, "e": 3717, "s": 3578, "text": "Entities - Entities are source and destination of information data. Entities are represented by a rectangles with their respective names." }, { "code": null, "e": 3820, "s": 3717, "text": "Process - Activities and action taken on the data are represented by Circle or Round-edged rectangles." }, { "code": null, "e": 4015, "s": 3820, "text": "Data Storage - There are two variants of data storage - it can either be represented as a rectangle with absence of both smaller sides or as an open-sided rectangle with only one side missing." }, { "code": null, "e": 4175, "s": 4015, "text": "Data Flow - Movement of data is shown by pointed arrows. Data movement is shown from the base of arrow as its source towards head of the arrow as destination." }, { "code": null, "e": 4390, "s": 4175, "text": "Level 0 - Highest abstraction level DFD is known as Level 0 DFD, which depicts the entire information system as one diagram concealing all the underlying details. Level 0 DFDs are also known as context level DFDs." }, { "code": null, "e": 4623, "s": 4390, "text": "Level 1 - The Level 0 DFD is broken down into more specific, Level 1 DFD. Level 1 DFD depicts basic modules in the system and flow of data among various modules. Level 1 DFD also mentions basic processes and sources of information." }, { "code": null, "e": 4877, "s": 4623, "text": "Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1.\nHigher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved." }, { "code": null, "e": 4968, "s": 4877, "text": "Level 2 - At this level, DFD shows how data flows inside the modules mentioned in Level 1." }, { "code": null, "e": 5131, "s": 4968, "text": "Higher level DFDs can be transformed into more specific lower level DFDs with deeper level of understanding unless the desired level of specification is achieved." }, { "code": null, "e": 5406, "s": 5131, "text": "Structure chart is a chart derived from Data Flow Diagram. It represents the system in more detail than DFD. It breaks down the entire system into lowest functional modules, describes functions and sub-functions of each module of the system to a greater detail than DFD." }, { "code": null, "e": 5512, "s": 5406, "text": "Structure chart represents hierarchical structure of modules. At each layer a specific task is performed." }, { "code": null, "e": 5577, "s": 5512, "text": "Here are the symbols used in construction of structure charts -" }, { "code": null, "e": 5749, "s": 5577, "text": "Module - It represents process or subroutine or task. A control module branches to more than one sub-module. Library Modules are re-usable and invokable from any module.\n" }, { "code": null, "e": 5908, "s": 5749, "text": "Condition - It is represented by small diamond at the base of module. It depicts that control module can select any of sub-routine based on some condition.\n" }, { "code": null, "e": 6031, "s": 5908, "text": "Jump - An arrow is shown pointing inside the module to depict that the control will jump in the middle of the sub-module.\n" }, { "code": null, "e": 6147, "s": 6031, "text": "Loop - A curved arrow represents loop in the module. All sub-modules covered by loop repeat execution of module.\n" }, { "code": null, "e": 6228, "s": 6147, "text": "Data flow - A directed arrow with empty circle at the end represents data flow.\n" }, { "code": null, "e": 6317, "s": 6228, "text": "Control flow - A directed arrow with filled circle at the end represents control flow.\n" }, { "code": null, "e": 6515, "s": 6317, "text": "HIPO (Hierarchical Input Process Output) diagram is a combination of two organized method to analyze the system and provide the means of documentation. HIPO model was developed by IBM in year 1970." }, { "code": null, "e": 6791, "s": 6515, "text": "HIPO diagram represents the hierarchy of modules in the software system. Analyst uses HIPO diagram in order to obtain high-level view of system functions. It decomposes functions into sub-functions in a hierarchical manner. It depicts the functions performed by system. " }, { "code": null, "e": 6968, "s": 6791, "text": "HIPO diagrams are good for documentation purpose. Their graphical representation makes it easier for designers and managers to get the pictorial idea of the system structure. " }, { "code": null, "e": 7147, "s": 6968, "text": "In contrast to IPO (Input Process Output) diagram, which depicts the flow of control and data in a module, HIPO does not provide any information about data flow or control flow." }, { "code": null, "e": 7303, "s": 7147, "text": "Both parts of HIPO diagram, Hierarchical presentation and IPO Chart are used for structure design of software program as well as documentation of the same." }, { "code": null, "e": 7565, "s": 7303, "text": "Most programmers are unaware of the large picture of software so they only rely on what their managers tell them to do. It is the responsibility of higher software management to provide accurate information to the programmers to develop accurate yet fast code." }, { "code": null, "e": 7682, "s": 7565, "text": "Other forms of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people." }, { "code": null, "e": 7924, "s": 7682, "text": "Hence, analysts and designers of the software come up with tools such as Structured English. It is nothing but the description of what is required to code and how to code it. Structured English helps the programmer to write error-free code. " }, { "code": null, "e": 8128, "s": 7924, "text": "Other form of methods, which use graphs or diagrams, may are sometimes interpreted differently by different people. Here, both Structured English and Pseudo-Code tries to mitigate that understanding gap." }, { "code": null, "e": 8375, "s": 8128, "text": "Structured English is the It uses plain English words in structured programming paradigm. It is not the ultimate code but a kind of description what is required to code and how to code it. The following are some tokens of structured programming." }, { "code": null, "e": 8406, "s": 8375, "text": "IF-THEN-ELSE, \nDO-WHILE-UNTIL" }, { "code": null, "e": 8546, "s": 8406, "text": "Analyst uses the same variable and data name, which are stored in Data Dictionary, making it much simpler to write and understand the code." }, { "code": null, "e": 8715, "s": 8546, "text": "We take the same example of Customer Authentication in the online shopping environment. This procedure to authenticate customer can be written in Structured English as:" }, { "code": null, "e": 8929, "s": 8715, "text": "Enter Customer_Name\nSEEK Customer_Name in Customer_Name_DB file\nIF Customer_Name found THEN\n Call procedure USER_PASSWORD_AUTHENTICATE()\nELSE\n PRINT error message\n Call procedure NEW_CUSTOMER_REQUEST()\nENDIF" }, { "code": null, "e": 9126, "s": 8929, "text": "The code written in Structured English is more like day-to-day spoken English. It can not be implemented directly as a code of software. Structured English is independent of programming language." }, { "code": null, "e": 9279, "s": 9126, "text": "Pseudo code is written more close to programming language. It may be considered as augmented programming language, full of comments and descriptions. " }, { "code": null, "e": 9422, "s": 9279, "text": "Pseudo code avoids variable declaration but they are written using some actual programming language’s constructs, like C, Fortran, Pascal etc." }, { "code": null, "e": 9576, "s": 9422, "text": "Pseudo code contains more programming details than Structured English. It provides a method to perform the task, as if a computer is executing the code." }, { "code": null, "e": 9620, "s": 9576, "text": "Program to print Fibonacci up to n numbers." }, { "code": null, "e": 9894, "s": 9620, "text": "void function Fibonacci\nGet value of n;\nSet value of a to 1;\nSet value of b to 1;\nInitialize I to 0\nfor (i=0; i< n; i++)\n{\n if a greater than b \n {\n Increase b by a;\n Print b;\n } \n else if b greater than a\n {\n increase a by b;\n print a;\n }\n}" }, { "code": null, "e": 10021, "s": 9894, "text": "A Decision table represents conditions and the respective actions to be taken to address them, in a structured tabular format." }, { "code": null, "e": 10205, "s": 10021, "text": "It is a powerful tool to debug and prevent errors. It helps group similar information into a single table and then by combining tables it delivers easy and convenient decision-making." }, { "code": null, "e": 10279, "s": 10205, "text": "To create the decision table, the developer must follow basic four steps:" }, { "code": null, "e": 10328, "s": 10279, "text": "Identify all possible conditions to be addressed" }, { "code": null, "e": 10376, "s": 10328, "text": "Determine actions for all identified conditions" }, { "code": null, "e": 10406, "s": 10376, "text": "Create Maximum possible rules" }, { "code": null, "e": 10434, "s": 10406, "text": "Define action for each rule" }, { "code": null, "e": 10555, "s": 10434, "text": "Decision Tables should be verified by end-users and can lately be simplified by eliminating duplicate rules and actions." }, { "code": null, "e": 10761, "s": 10555, "text": "Let us take a simple example of day-to-day problem with our Internet connectivity. We begin by identifying all problems that can arise while starting the internet and their respective possible solutions. " }, { "code": null, "e": 10865, "s": 10761, "text": "We list all possible problems under column conditions and the prospective actions under column Actions." }, { "code": null, "e": 11151, "s": 10865, "text": "Entity-Relationship model is a type of database model based on the notion of real world entities and relationship among them. We can map real world scenario onto ER database model. ER Model creates a set of entities with their attributes, a set of constraints and relation among them." }, { "code": null, "e": 11253, "s": 11151, "text": "ER Model is best used for the conceptual design of database. ER Model can be represented as follows :" }, { "code": null, "e": 11570, "s": 11253, "text": "Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain.\nFor example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc." }, { "code": null, "e": 11749, "s": 11570, "text": "Entity - An entity in ER Model is a real world being, which has some properties called attributes. Every attribute is defined by its corresponding set of values, called domain." }, { "code": null, "e": 11887, "s": 11749, "text": "For example, Consider a school database. Here, a student is an entity. Student has various attributes like name, id, age and class etc." }, { "code": null, "e": 12174, "s": 11887, "text": "Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities.\nMapping cardinalities:\n\none to one\none to many\nmany to one\nmany to many\n\n" }, { "code": null, "e": 12387, "s": 12174, "text": "Relationship - The logical association among entities is called relationship. Relationships are mapped with entities in various ways. Mapping cardinalities define the number of associations between two entities." }, { "code": null, "e": 12410, "s": 12387, "text": "Mapping cardinalities:" }, { "code": null, "e": 12421, "s": 12410, "text": "one to one" }, { "code": null, "e": 12433, "s": 12421, "text": "one to many" }, { "code": null, "e": 12445, "s": 12433, "text": "many to one" }, { "code": null, "e": 12458, "s": 12445, "text": "many to many" }, { "code": null, "e": 12737, "s": 12458, "text": "Data dictionary is the centralized collection of information about data. It stores meaning and origin of data, its relationship with other data, data format for usage etc. Data dictionary has rigorous definitions of all names in order to facilitate user and software designers." }, { "code": null, "e": 12959, "s": 12737, "text": "Data dictionary is often referenced as meta-data (data about data) repository. It is created along with DFD (Data Flow Diagram) model of software program and is expected to be updated whenever DFD is changed or updated." }, { "code": null, "e": 13222, "s": 12959, "text": "The data is referenced via data dictionary while designing and implementing software. Data dictionary removes any chances of ambiguity. It helps keeping work of programmers and designers synchronized while using same object reference everywhere in the program." }, { "code": null, "e": 13375, "s": 13222, "text": "Data dictionary provides a way of documentation for the complete database system in one place. Validation of DFD is carried out using data dictionary." }, { "code": null, "e": 13439, "s": 13375, "text": "Data dictionary should contain information about the following " }, { "code": null, "e": 13449, "s": 13439, "text": "Data Flow" }, { "code": null, "e": 13464, "s": 13449, "text": "Data Structure" }, { "code": null, "e": 13478, "s": 13464, "text": "Data Elements" }, { "code": null, "e": 13490, "s": 13478, "text": "Data Stores" }, { "code": null, "e": 13506, "s": 13490, "text": "Data Processing" }, { "code": null, "e": 13613, "s": 13506, "text": "Data Flow is described by means of DFDs as studied earlier and represented in algebraic form as described." }, { "code": null, "e": 13665, "s": 13613, "text": "Address = House No + (Street / Area) + City + State" }, { "code": null, "e": 13736, "s": 13665, "text": "Course ID = Course Number + Course Name + Course Level + Course Grades" }, { "code": null, "e": 13876, "s": 13736, "text": "Data elements consist of Name and descriptions of Data and Control Items, Internal or External data stores etc. with the following details:" }, { "code": null, "e": 13889, "s": 13876, "text": "Primary Name" }, { "code": null, "e": 13912, "s": 13889, "text": "Secondary Name (Alias)" }, { "code": null, "e": 13945, "s": 13912, "text": "Use-case (How and where to use)" }, { "code": null, "e": 13982, "s": 13945, "text": "Content Description (Notation etc. )" }, { "code": null, "e": 14042, "s": 13982, "text": "Supplementary Information (preset values, constraints etc.)" }, { "code": null, "e": 14171, "s": 14042, "text": "It stores the information from where the data enters into the system and exists out of the system. The Data Store may include -" }, { "code": null, "e": 14311, "s": 14171, "text": "Files\n\nInternal to software.\nExternal to software but on the same machine.\nExternal to software and system, located on different machine.\n\n" }, { "code": null, "e": 14333, "s": 14311, "text": "Internal to software." }, { "code": null, "e": 14379, "s": 14333, "text": "External to software but on the same machine." }, { "code": null, "e": 14442, "s": 14379, "text": "External to software and system, located on different machine." }, { "code": null, "e": 14490, "s": 14442, "text": "Tables\n\nNaming convention\n Indexing property\n\n" }, { "code": null, "e": 14508, "s": 14490, "text": "Naming convention" }, { "code": null, "e": 14528, "s": 14508, "text": " Indexing property" }, { "code": null, "e": 14568, "s": 14528, "text": "There are two types of Data Processing:" }, { "code": null, "e": 14593, "s": 14568, "text": "Logical: As user sees it" }, { "code": null, "e": 14623, "s": 14593, "text": "Physical: As software sees it" }, { "code": null, "e": 14658, "s": 14623, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 14677, "s": 14658, "text": " Arnab Chakraborty" }, { "code": null, "e": 14710, "s": 14677, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 14723, "s": 14710, "text": " Zach Miller" }, { "code": null, "e": 14758, "s": 14723, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 14771, "s": 14758, "text": " Zach Miller" }, { "code": null, "e": 14804, "s": 14771, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 14815, "s": 14804, "text": " John Shea" }, { "code": null, "e": 14849, "s": 14815, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 14860, "s": 14849, "text": " Daniel IT" }, { "code": null, "e": 14893, "s": 14860, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 14910, "s": 14893, "text": " GlobalETraining" }, { "code": null, "e": 14917, "s": 14910, "text": " Print" }, { "code": null, "e": 14928, "s": 14917, "text": " Add Notes" } ]
Program to check points are forming concave polygon or not in Python
Suppose we have outer points of a polygon in clockwise order. We have to check these points are forming a convex polygon or not. A polygon is said to be concave if any one of its interior angle is greater than 180°. From this diagram it is clear that for each three consecutive points the interior angle is not more than 180° except CDE. So, if the input is like points = [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)], then the output will be True. To solve this, we will follow these steps − n := size of points for i in range 0 to size of points, dop1 := points[i-2] when i > 1, otherwise points[n-2]p2 := points[i-2] when i > 0, otherwise points[n-1]p3 := points[i]if angle between points (p1, p2, p3) > 180, thenreturn True p1 := points[i-2] when i > 1, otherwise points[n-2] p2 := points[i-2] when i > 0, otherwise points[n-1] p3 := points[i] if angle between points (p1, p2, p3) > 180, thenreturn True return True return False Let us see the following implementation to get better understanding − import math def get_angle(a, b, c): angle = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0])) return angle + 360 if angle < 0 else angle def solve(points): n = len(points) for i in range(len(points)): p1 = points[i-2] p2 = points[i-1] p3 = points[i] if get_angle(p1, p2, p3) > 180: return True return False points = [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)] print(solve(points)) [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)] True
[ { "code": null, "e": 1278, "s": 1062, "text": "Suppose we have outer points of a polygon in clockwise order. We have to check these points are forming a convex polygon or not. A polygon is said to be concave if any one of its interior angle is greater than 180°." }, { "code": null, "e": 1400, "s": 1278, "text": "From this diagram it is clear that for each three consecutive points the interior angle is not more than 180° except CDE." }, { "code": null, "e": 1512, "s": 1400, "text": "So, if the input is like points = [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)], then the output will be True." }, { "code": null, "e": 1556, "s": 1512, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1576, "s": 1556, "text": "n := size of points" }, { "code": null, "e": 1791, "s": 1576, "text": "for i in range 0 to size of points, dop1 := points[i-2] when i > 1, otherwise points[n-2]p2 := points[i-2] when i > 0, otherwise points[n-1]p3 := points[i]if angle between points (p1, p2, p3) > 180, thenreturn True" }, { "code": null, "e": 1843, "s": 1791, "text": "p1 := points[i-2] when i > 1, otherwise points[n-2]" }, { "code": null, "e": 1895, "s": 1843, "text": "p2 := points[i-2] when i > 0, otherwise points[n-1]" }, { "code": null, "e": 1911, "s": 1895, "text": "p3 := points[i]" }, { "code": null, "e": 1971, "s": 1911, "text": "if angle between points (p1, p2, p3) > 180, thenreturn True" }, { "code": null, "e": 1983, "s": 1971, "text": "return True" }, { "code": null, "e": 1996, "s": 1983, "text": "return False" }, { "code": null, "e": 2066, "s": 1996, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2532, "s": 2066, "text": "import math\ndef get_angle(a, b, c):\n angle = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))\n return angle + 360 if angle < 0 else angle\n\ndef solve(points):\n n = len(points)\n for i in range(len(points)):\n p1 = points[i-2]\n p2 = points[i-1]\n p3 = points[i]\n if get_angle(p1, p2, p3) > 180:\n return True\n return False\n\npoints = [(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)]\nprint(solve(points))" }, { "code": null, "e": 2580, "s": 2532, "text": "[(3,4), (4,7),(7,8),(8,4),(12,3),(10,1),(5,2)]\n" }, { "code": null, "e": 2585, "s": 2580, "text": "True" } ]
DateTime.Subtract() Method in C#
The DateTime.Subtract() method in C# is used to subtract the specified DateTime or span. Following is the syntax − public TimeSpan Subtract (DateTime value); public DateTime Subtract (TimeSpan value); Let us now see an example to implement the DateTime.Subtract() method − using System; public class Demo { public static void Main() { DateTime d1 = new DateTime(2019, 10, 10, 8, 10, 40); DateTime d2 = new DateTime(2017, 11, 06, 8, 10, 40); Console.WriteLine("Date 1 = "+d1); Console.WriteLine("Date 2 = "+d2); TimeSpan res = d1.Subtract(d2); Console.WriteLine("TimeSpan between two dates = {0} ",res); } } This will produce the following output − Date 1 = 10/10/2019 8:10:40 AM Date 2 = 11/6/2017 8:10:40 AM TimeSpan between two dates = 703.00:00:00 Let us now see another example to implement the DateTime.Subtract() method − using System; public class Demo { public static void Main() { DateTime d = new DateTime(2019, 10, 10, 8, 10, 40); TimeSpan t = new TimeSpan(1, 10, 10, 12); Console.WriteLine("Date = "+d); DateTime res = d.Subtract(t); Console.WriteLine("DateTime between date d and timespan t = {0} ",res); } } This will produce the following output − Date = 10/10/2019 8:10:40 AM DateTime between date d and timespan t = 10/8/2019 10:00:28 PM
[ { "code": null, "e": 1151, "s": 1062, "text": "The DateTime.Subtract() method in C# is used to subtract the specified DateTime or span." }, { "code": null, "e": 1177, "s": 1151, "text": "Following is the syntax −" }, { "code": null, "e": 1263, "s": 1177, "text": "public TimeSpan Subtract (DateTime value);\npublic DateTime Subtract (TimeSpan value);" }, { "code": null, "e": 1335, "s": 1263, "text": "Let us now see an example to implement the DateTime.Subtract() method −" }, { "code": null, "e": 1711, "s": 1335, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d1 = new DateTime(2019, 10, 10, 8, 10, 40);\n DateTime d2 = new DateTime(2017, 11, 06, 8, 10, 40);\n Console.WriteLine(\"Date 1 = \"+d1);\n Console.WriteLine(\"Date 2 = \"+d2);\n TimeSpan res = d1.Subtract(d2);\n Console.WriteLine(\"TimeSpan between two dates = {0} \",res);\n }\n}" }, { "code": null, "e": 1752, "s": 1711, "text": "This will produce the following output −" }, { "code": null, "e": 1855, "s": 1752, "text": "Date 1 = 10/10/2019 8:10:40 AM\nDate 2 = 11/6/2017 8:10:40 AM\nTimeSpan between two dates = 703.00:00:00" }, { "code": null, "e": 1932, "s": 1855, "text": "Let us now see another example to implement the DateTime.Subtract() method −" }, { "code": null, "e": 2262, "s": 1932, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 10, 10, 8, 10, 40);\n TimeSpan t = new TimeSpan(1, 10, 10, 12);\n Console.WriteLine(\"Date = \"+d);\n DateTime res = d.Subtract(t);\n Console.WriteLine(\"DateTime between date d and timespan t = {0} \",res);\n }\n}" }, { "code": null, "e": 2303, "s": 2262, "text": "This will produce the following output −" }, { "code": null, "e": 2395, "s": 2303, "text": "Date = 10/10/2019 8:10:40 AM\nDateTime between date d and timespan t = 10/8/2019 10:00:28 PM" } ]
How to make a multi-select dropdown using Angular 11/10 ? - GeeksforGeeks
07 Oct, 2021 In this article, we will learn to build the multiple selection drop-down menu in Angular. To accomplish this task, we require Angular 10 or the Angular 11 version. Sometimes we need to display dynamically fetched multi-selected data in a drop-down menu, for this, we will use the npm @ng-select/ng-select package as a multi-select drop-down menu. The package is used to provide a set method that gives an option for a drop-down menu & also provides the change events to fetch the value of the selected option. To build a multiple-select drop-down menu using Angular, we will follow the below steps in sequence. Syntax: <ng-select [items]="item-name" bindLabel="name" placeholder="Select item" appendTo="body" [multiple]="true" [(ngModel)]="selected"> </ng-select> Prerequisites: NPM must be preinstalled. Environment Setup: Install Angular npm install -g @angular/cli Install Angular npm install -g @angular/cli Create a new Angular project ng new <project-name> Create a new Angular project ng new <project-name> Check the installation by running the project. You should see the angular landing page on http://localhost:4200/ ng serve -o Check the installation by running the project. You should see the angular landing page on http://localhost:4200/ ng serve -o Project Structure: After completing the above steps, our project structure will look like the following image: Creating drop-down multi-select: Create a new application. We will use the below command to create a new application. ng new geeksforgeeks-multiSelect Create a new application. We will use the below command to create a new application. ng new geeksforgeeks-multiSelect Install @ngselect npm package. In order to use the drop-down menu, we will follow the below command to install the @ngselect package from the npm. npm install --save @ng-select/ng-select Install @ngselect npm package. In order to use the drop-down menu, we will follow the below command to install the @ngselect package from the npm. npm install --save @ng-select/ng-select Example: Import NgSelectModule and FormsModule inside the app.module.ts file. Here, in order to use ngSelect in the application. we need to import NgSelectModule and FormsModule in the app.module.ts file. app.module.ts import { NgModule } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { BrowserModule } from "@angular/platform-browser"; import { NgSelectModule } from "@ng-select/ng-select"; import { AppComponent } from "./app.component"; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, FormsModule, NgSelectModule], providers: [], bootstrap: [AppComponent], }) export class AppModule {} Import CSS file: We need to import a CSS of NgSelectModule. We will use a default.theme.css which is in ng-select/themes folder. This will provide us with a multi-select drop-down design. We will use this import CSS file inside the style.css. styles.css @import "~@ng-select/ng-select/themes/default.theme.css"; Declare an object that will contain the lists of the cars, inside the app.component.ts file. Here, we will update the app.component.ts file. This file is used to store the “cars” array containing a list of cars. We are storing all car’s details in javascript objects and inside that objects. We are providing id and names for all different cars. We are also taking the selected array in which we are selecting those menu items which we want to select by default. app.component.ts import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"], }) export class AppComponent { title = "geeksforgeeks-multiSelect"; cars = [ { id: 1, name: "BMW Hyundai" }, { id: 2, name: "Kia Tata" }, { id: 3, name: "Volkswagen Ford" }, { id: 4, name: "Renault Audi" }, { id: 5, name: "Mercedes Benz Skoda" }, ]; selected = [{ id: 3, name: "Volkswagen Ford" }]; } Rendering the content: Here, we will update our layout or view file to render our content. Here, we are using the app.component.html file for updating or viewing our content like this: app.component.html <h1>Multi-Select Dropdown using Angular 11/10</h1> <!-- Using Items Input --> <ng-select [items]="cars" bindLabel="name" placeholder="Select Category" appendTo="body" [multiple]="true" [(ngModel)]="selected"> </ng-select> Run the application: In this step, we are ready to run the application. A similar output can be seen as shown below. ng serve Output: varshagumber28 Angular10 AngularJS-Questions Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Roadmap to Become a Web Developer in 2022 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? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25093, "s": 25062, "text": " \n07 Oct, 2021\n" }, { "code": null, "e": 25704, "s": 25093, "text": "In this article, we will learn to build the multiple selection drop-down menu in Angular. To accomplish this task, we require Angular 10 or the Angular 11 version. Sometimes we need to display dynamically fetched multi-selected data in a drop-down menu, for this, we will use the npm @ng-select/ng-select package as a multi-select drop-down menu. The package is used to provide a set method that gives an option for a drop-down menu & also provides the change events to fetch the value of the selected option. To build a multiple-select drop-down menu using Angular, we will follow the below steps in sequence." }, { "code": null, "e": 25712, "s": 25704, "text": "Syntax:" }, { "code": null, "e": 25863, "s": 25712, "text": "<ng-select\n [items]=\"item-name\"\n bindLabel=\"name\"\n placeholder=\"Select item\"\n appendTo=\"body\"\n [multiple]=\"true\"\n [(ngModel)]=\"selected\">\n</ng-select>" }, { "code": null, "e": 25904, "s": 25863, "text": "Prerequisites: NPM must be preinstalled." }, { "code": null, "e": 25925, "s": 25906, "text": "Environment Setup:" }, { "code": null, "e": 25971, "s": 25925, "text": "\nInstall Angular\nnpm install -g @angular/cli\n" }, { "code": null, "e": 25987, "s": 25971, "text": "Install Angular" }, { "code": null, "e": 26015, "s": 25987, "text": "npm install -g @angular/cli" }, { "code": null, "e": 26068, "s": 26015, "text": "\nCreate a new Angular project\nng new <project-name>\n" }, { "code": null, "e": 26097, "s": 26068, "text": "Create a new Angular project" }, { "code": null, "e": 26119, "s": 26097, "text": "ng new <project-name>" }, { "code": null, "e": 26246, "s": 26119, "text": "\nCheck the installation by running the project. You should see the angular landing page on http://localhost:4200/\nng serve -o\n" }, { "code": null, "e": 26359, "s": 26246, "text": "Check the installation by running the project. You should see the angular landing page on http://localhost:4200/" }, { "code": null, "e": 26371, "s": 26359, "text": "ng serve -o" }, { "code": null, "e": 26482, "s": 26371, "text": "Project Structure: After completing the above steps, our project structure will look like the following image:" }, { "code": null, "e": 26517, "s": 26484, "text": "Creating drop-down multi-select:" }, { "code": null, "e": 26637, "s": 26517, "text": "\nCreate a new application. We will use the below command to create a new application.\nng new geeksforgeeks-multiSelect\n" }, { "code": null, "e": 26722, "s": 26637, "text": "Create a new application. We will use the below command to create a new application." }, { "code": null, "e": 26755, "s": 26722, "text": "ng new geeksforgeeks-multiSelect" }, { "code": null, "e": 26945, "s": 26755, "text": "\nInstall @ngselect npm package. In order to use the drop-down menu, we will follow the below command to install the @ngselect package from the npm.\nnpm install --save @ng-select/ng-select\n" }, { "code": null, "e": 27093, "s": 26945, "text": "Install @ngselect npm package. In order to use the drop-down menu, we will follow the below command to install the @ngselect package from the npm." }, { "code": null, "e": 27133, "s": 27093, "text": "npm install --save @ng-select/ng-select" }, { "code": null, "e": 27339, "s": 27133, "text": "Example: Import NgSelectModule and FormsModule inside the app.module.ts file. Here, in order to use ngSelect in the application. we need to import NgSelectModule and FormsModule in the app.module.ts file." }, { "code": null, "e": 27353, "s": 27339, "text": "app.module.ts" }, { "code": "\n\n\n\n\n\n\nimport { NgModule } from \"@angular/core\"; \nimport { FormsModule } from \"@angular/forms\"; \nimport { BrowserModule } from \"@angular/platform-browser\"; \nimport { NgSelectModule } from \"@ng-select/ng-select\"; \n \nimport { AppComponent } from \"./app.component\"; \n \n@NgModule({ \n declarations: [AppComponent], \n imports: [BrowserModule, FormsModule, NgSelectModule], \n providers: [], \n bootstrap: [AppComponent], \n}) \nexport class AppModule {}\n\n\n\n\n\n", "e": 27819, "s": 27363, "text": null }, { "code": null, "e": 28063, "s": 27819, "text": "Import CSS file: We need to import a CSS of NgSelectModule. We will use a default.theme.css which is in ng-select/themes folder. This will provide us with a multi-select drop-down design. We will use this import CSS file inside the style.css. " }, { "code": null, "e": 28074, "s": 28063, "text": "styles.css" }, { "code": null, "e": 28132, "s": 28074, "text": "@import \"~@ng-select/ng-select/themes/default.theme.css\";" }, { "code": null, "e": 28595, "s": 28132, "text": "Declare an object that will contain the lists of the cars, inside the app.component.ts file. Here, we will update the app.component.ts file. This file is used to store the “cars” array containing a list of cars. We are storing all car’s details in javascript objects and inside that objects. We are providing id and names for all different cars. We are also taking the selected array in which we are selecting those menu items which we want to select by default." }, { "code": null, "e": 28612, "s": 28595, "text": "app.component.ts" }, { "code": "\n\n\n\n\n\n\nimport { Component } from \"@angular/core\"; \n \n@Component({ \n selector: \"my-app\", \n templateUrl: \"./app.component.html\", \n styleUrls: [\"./app.component.css\"], \n}) \nexport class AppComponent { \n title = \"geeksforgeeks-multiSelect\"; \n \n cars = [ \n { id: 1, name: \"BMW Hyundai\" }, \n { id: 2, name: \"Kia Tata\" }, \n { id: 3, name: \"Volkswagen Ford\" }, \n { id: 4, name: \"Renault Audi\" }, \n { id: 5, name: \"Mercedes Benz Skoda\" }, \n ]; \n \n selected = [{ id: 3, name: \"Volkswagen Ford\" }]; \n}\n\n\n\n\n\n", "e": 29144, "s": 28622, "text": null }, { "code": null, "e": 29329, "s": 29144, "text": "Rendering the content: Here, we will update our layout or view file to render our content. Here, we are using the app.component.html file for updating or viewing our content like this:" }, { "code": null, "e": 29348, "s": 29329, "text": "app.component.html" }, { "code": "\n\n\n\n\n\n\n<h1>Multi-Select Dropdown using Angular 11/10</h1> \n \n<!-- Using Items Input --> \n<ng-select \n [items]=\"cars\"\n bindLabel=\"name\"\n placeholder=\"Select Category\"\n appendTo=\"body\"\n [multiple]=\"true\"\n [(ngModel)]=\"selected\"> \n</ng-select>\n\n\n\n\n\n", "e": 29612, "s": 29358, "text": null }, { "code": null, "e": 29730, "s": 29612, "text": "Run the application: In this step, we are ready to run the application. A similar output can be seen as shown below. " }, { "code": null, "e": 29739, "s": 29730, "text": "ng serve" }, { "code": null, "e": 29747, "s": 29739, "text": "Output:" }, { "code": null, "e": 29762, "s": 29747, "text": "varshagumber28" }, { "code": null, "e": 29774, "s": 29762, "text": "\nAngular10\n" }, { "code": null, "e": 29796, "s": 29774, "text": "\nAngularJS-Questions\n" }, { "code": null, "e": 29805, "s": 29796, "text": "\nPicked\n" }, { "code": null, "e": 29817, "s": 29805, "text": "\nAngularJS\n" }, { "code": null, "e": 29836, "s": 29817, "text": "\nWeb Technologies\n" }, { "code": null, "e": 30041, "s": 29836, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 30085, "s": 30041, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 30120, "s": 30085, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30144, "s": 30120, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 30197, "s": 30144, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 30246, "s": 30197, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 30288, "s": 30246, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30321, "s": 30288, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30364, "s": 30321, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30414, "s": 30364, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks
28 Jun, 2021 A pennant is a sequence of numbers, each number being 1 or 2. An n-pennant is a sequence of numbers with sum equal to n. For example, (1,1,2) is a 4-pennant. The set of all possible 1-pennants is {(1)}, the set of all possible 2-pennants is {(2), (1,1)} and the set of all 3-pennants is {(2,1), (1,1,1), (1,2)}. Note that the pennant (1,2) is not the same as the pennant (2,1). The number of 10-pennants is ______________.(A) 88.9 to 89.1Answer: (A)Explanation: 1-pennant {(1)} - #1 2-pennant {(1,1),(2)} - #2 3-pennant {(1,1,1),(1,2),(2,1)} - #3 4-pennant {(1,1,1,1),(2,2),(1,1,2),(1,2,1),(2,1,1)} - #5 5-pennant {(1,1,1,1,1),(2,1,1,1),(1,2,1,1),(1,1,2,1), (1,1,1,2),(2,2,1),(2,1,2),(1,2,2)} - #8 If one observe carefully they are the terms(part of) a Fibonacci series. (0,1,1,2,3,5,8,13 ....). Hence the # of 10-pennant is the 12th term of the series ie. 89Quiz of this Question GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(Set-1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE CS 2012 | Question 40 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24075, "s": 24047, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24537, "s": 24075, "text": "A pennant is a sequence of numbers, each number being 1 or 2. An n-pennant is a sequence of numbers with sum equal to n. For example, (1,1,2) is a 4-pennant. The set of all possible 1-pennants is {(1)}, the set of all possible 2-pennants is {(2), (1,1)} and the set of all 3-pennants is {(2,1), (1,1,1), (1,2)}. Note that the pennant (1,2) is not the same as the pennant (2,1). The number of 10-pennants is ______________.(A) 88.9 to 89.1Answer: (A)Explanation:" }, { "code": null, "e": 24790, "s": 24537, "text": "1-pennant {(1)} - #1\n\n2-pennant {(1,1),(2)} - #2\n\n3-pennant {(1,1,1),(1,2),(2,1)} - #3\n\n4-pennant {(1,1,1,1),(2,2),(1,1,2),(1,2,1),(2,1,1)} - #5\n\n5-pennant {(1,1,1,1,1),(2,1,1,1),(1,2,1,1),(1,1,2,1),\n (1,1,1,2),(2,2,1),(2,1,2),(1,2,2)} - #8\n" }, { "code": null, "e": 24973, "s": 24790, "text": "If one observe carefully they are the terms(part of) a Fibonacci series. (0,1,1,2,3,5,8,13 ....). Hence the # of 10-pennant is the 12th term of the series ie. 89Quiz of this Question" }, { "code": null, "e": 24994, "s": 24973, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 25020, "s": 24994, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 25025, "s": 25020, "text": "GATE" }, { "code": null, "e": 25123, "s": 25025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25132, "s": 25123, "text": "Comments" }, { "code": null, "e": 25145, "s": 25132, "text": "Old Comments" }, { "code": null, "e": 25187, "s": 25145, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25229, "s": 25187, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25263, "s": 25229, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25296, "s": 25263, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25338, "s": 25296, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25392, "s": 25338, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25426, "s": 25392, "text": "GATE | GATE CS 2012 | Question 40" }, { "code": null, "e": 25460, "s": 25426, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25502, "s": 25460, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" } ]
Outlier Detection with Hampel Filter | by Eryk Lewinson | Towards Data Science
Recently I stumbled upon a new (to me) outlier detection algorithm — the Hampel filter. In this short article, I would like to describe how it works and how to use it in practice. To the best of my knowledge, there is no Python library containing this algorithm, so we will implement it from scratch using two different approaches (for-loop and pandas). In the end, we will see which one performs better in terms of execution speed. Update: Hampel filter is implemented in sktime, you can find more about it here. Let’s start with a quick theoretical introduction. There is not a lot of online resources describing the algorithm (even no page on Wikipedia), but it is simple enough to quickly understand the logic. Also, I put some references at the end of the article. The goal of the Hampel filter is to identify and replace outliers in a given series. It uses a sliding window of configurable width to go over the data. For each window (given observation and the 2 window_size surrounding elements, window_size for each side), we calculate the median and the standard deviation expressed as the median absolute deviation. For the MAD to be a consistent estimator for the standard deviation, we must multiply it by a constant scale factor k. The factor is dependent on the distribution, for Gaussian it is approximately 1.4826. If the considered observation differs from the window median by more than x standard deviations, we treat it as an outlier and replace it with the median. The Hampel filter has two configurable parameters: the size of the sliding window the number of standard deviations which identify the outlier We select these two parameters depending on the use-case. A higher standard deviation threshold makes the filter more forgiving, a lower one identifies more points as outliers. Setting the threshold to 0 corresponds to John Tukey’s median filter. As the filter uses a sliding window, it makes the most sense to use it with time-series data, where the order of the data is governed by time. The first step is importing the required libraries. import matplotlib.pyplot as pltimport warningsimport pandas as pdimport numpy as np Before implementing the algorithm, we create an artificial dataset using random walk. We define a function that accepts the percentage of outliers as a parameter and randomly scales some random walk increments by a constant multiplier. Using the function we generate artificial data and plot it below, together with the introduced outliers. rw, outlier_ind = random_walk_with_outliers(0, 1000, 0.01)plt.plot(np.arange(len(rw)), rw)plt.scatter(outlier_ind, rw[outlier_ind], c='r', label='outlier')plt.title('Random Walk with outliers')plt.xlabel('Time steps')plt.ylabel('Values')plt.legend(); We also need to define a function for evaluating the results of our outlier detection algorithms. For that, we will plot the actual vs. detected outliers and return a short summary of the performance. for-loop implementation for-loop implementation We start with the for-loop implementation of the Hampel filter. We base the code on the one from the pracma R package. We run the algorithm on the RW series. We chose window size 10, but this should be determined empirically for the best performance. res, detected_outliers = hampel_filter_forloop(rw, 10) We evaluate the results using the previously defined helper function. tp, fp, fn = evaluate_detection(rw, outlier_ind, detected_outliers) In the plot, we can see that the algorithm correctly identified 8 (out of 10) outliers, mistook one observation for an outlier (red dot) and missed 2 outliers (black dots). Perhaps better performance can be achieved by tuning the window size. However, this is sufficient for the purpose of the exercise. We additionally plot the transformed series, in which the outliers were replaced with the window median. plt.plot(np.arange(len(res)), res);plt.scatter(outlier_ind, rw[outlier_ind], c='g', label='true outlier')plt.scatter(fp, rw[fp], c='r', label='false positive')plt.title('Cleaned series (without detected outliers)')plt.legend(); 2. pandas implementation For the pandas implementation we make use of the rolling method of a pd.Series and a lambda function. In the rolling method we specify twice the window size and use centering, so the considered observation is in the middle of a 2 * window_size + 1 window. Before running the algorithm, we transform the RW from np.ndarray topd.Series. rw_series = pd.Series(rw)res, detected_outliers = hampel_filter_pandas(rw_series, 10)tp, fp, fn = evaluate_detection(rw, outlier_ind, detected_outliers) The results of both approaches are identical, which is always a good sign :) At this point, we test the two implementations against each other in terms of execution speed. We expect that the pandas one will perform faster. First, we test the for-loop implementation: %%timeitres, detected_outliers = hampel_filter_forloop(rw, 10)# 67.9 ms ± 990 μs per loop (mean ± std. dev. of 7 runs, 10 loops each) Then, we run the analogical test for the pandas implementation: %%timeitres, detected_outliers = hampel_filter_pandas(rw_series, 10)# 76.1 ms ± 4.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) We see that the pandas implementation turned out to be slower. One hypothesis to test is that the pandas implementation will be faster for a larger series. That is why we also increase the length of the random walk series to 100000 and test the performance once again. rw, outlier_ind = random_walk_with_outliers(0, 10 ** 5, 0.01)rw_series = pd.Series(rw) Having prepared the data, we move to test the performance: %%timeitres, detected_outliers = hampel_filter_forloop(rw, 10)# 6.75 s ± 203 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)%%timeitres, detected_outliers = hampel_filter_pandas(rw_series, 10)# 6.76 s ± 30.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) It turns out that now they achieved comparable performance, with the pandas implementation providing more stable performance (lower standard deviation). As a bonus, we explore the possibility of speeding up the code based on for-loops with numba. numba is a library that under-the-hood translates Python code into an optimized machine code. Given it is possible to transform the code, numba can make certain algorithms written in Python approach the speed of C. The best part about numba is that (if possible) the speed boost comes at a very small price in terms of coding. We need to import the library and add the @jit decorator before the function we want to translate to machine code. The nopython argument indicates if we want numba to use purely machine code or to use some Python code if necessary. Ideally, this should always be set to true, as long as there are no errors returned by numba. Below we test the execution speed. %%timeitres, detected_outliers = hampel_filter_forloop_numba(rw, 10)# 108 ms ± 1.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) It only takes 108 ms (milliseconds) as compared to 6.76 s in case of the pandas implementation! That is a massive speed-up of ~63 times! Summing up, in this article we showed explained how Hampel filter work in terms of outlier detection and how to implement it in Python. We also compared the implementations in terms of execution speed. It is also good to consider the drawbacks of the Hampel filter: it has problems with detecting outliers at the beginning and the end of the series — when the window is not complete (even on one side), the function does not detect possible outliers it struggles to detect outliers when they are close to each other — within the window range As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. You can find the code used for this article on my GitHub. Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around! Hampel F. R., ”The influence curve and its role in robust estimation,” Journal of the American Statistical Association, 69, 382–393, 1974 Liu, Hancong, Sirish Shah, and Wei Jiang. “On-line outlier detection and data cleaning.” Computers and Chemical Engineering. Vol. 28, March 2004, pp. 1635–1647 Suomela, Jukka. “Median Filtering Is Equivalent to Sorting.” 2014
[ { "code": null, "e": 605, "s": 172, "text": "Recently I stumbled upon a new (to me) outlier detection algorithm — the Hampel filter. In this short article, I would like to describe how it works and how to use it in practice. To the best of my knowledge, there is no Python library containing this algorithm, so we will implement it from scratch using two different approaches (for-loop and pandas). In the end, we will see which one performs better in terms of execution speed." }, { "code": null, "e": 686, "s": 605, "text": "Update: Hampel filter is implemented in sktime, you can find more about it here." }, { "code": null, "e": 942, "s": 686, "text": "Let’s start with a quick theoretical introduction. There is not a lot of online resources describing the algorithm (even no page on Wikipedia), but it is simple enough to quickly understand the logic. Also, I put some references at the end of the article." }, { "code": null, "e": 1297, "s": 942, "text": "The goal of the Hampel filter is to identify and replace outliers in a given series. It uses a sliding window of configurable width to go over the data. For each window (given observation and the 2 window_size surrounding elements, window_size for each side), we calculate the median and the standard deviation expressed as the median absolute deviation." }, { "code": null, "e": 1502, "s": 1297, "text": "For the MAD to be a consistent estimator for the standard deviation, we must multiply it by a constant scale factor k. The factor is dependent on the distribution, for Gaussian it is approximately 1.4826." }, { "code": null, "e": 1657, "s": 1502, "text": "If the considered observation differs from the window median by more than x standard deviations, we treat it as an outlier and replace it with the median." }, { "code": null, "e": 1708, "s": 1657, "text": "The Hampel filter has two configurable parameters:" }, { "code": null, "e": 1739, "s": 1708, "text": "the size of the sliding window" }, { "code": null, "e": 1800, "s": 1739, "text": "the number of standard deviations which identify the outlier" }, { "code": null, "e": 2047, "s": 1800, "text": "We select these two parameters depending on the use-case. A higher standard deviation threshold makes the filter more forgiving, a lower one identifies more points as outliers. Setting the threshold to 0 corresponds to John Tukey’s median filter." }, { "code": null, "e": 2190, "s": 2047, "text": "As the filter uses a sliding window, it makes the most sense to use it with time-series data, where the order of the data is governed by time." }, { "code": null, "e": 2242, "s": 2190, "text": "The first step is importing the required libraries." }, { "code": null, "e": 2326, "s": 2242, "text": "import matplotlib.pyplot as pltimport warningsimport pandas as pdimport numpy as np" }, { "code": null, "e": 2562, "s": 2326, "text": "Before implementing the algorithm, we create an artificial dataset using random walk. We define a function that accepts the percentage of outliers as a parameter and randomly scales some random walk increments by a constant multiplier." }, { "code": null, "e": 2667, "s": 2562, "text": "Using the function we generate artificial data and plot it below, together with the introduced outliers." }, { "code": null, "e": 2918, "s": 2667, "text": "rw, outlier_ind = random_walk_with_outliers(0, 1000, 0.01)plt.plot(np.arange(len(rw)), rw)plt.scatter(outlier_ind, rw[outlier_ind], c='r', label='outlier')plt.title('Random Walk with outliers')plt.xlabel('Time steps')plt.ylabel('Values')plt.legend();" }, { "code": null, "e": 3119, "s": 2918, "text": "We also need to define a function for evaluating the results of our outlier detection algorithms. For that, we will plot the actual vs. detected outliers and return a short summary of the performance." }, { "code": null, "e": 3143, "s": 3119, "text": "for-loop implementation" }, { "code": null, "e": 3167, "s": 3143, "text": "for-loop implementation" }, { "code": null, "e": 3286, "s": 3167, "text": "We start with the for-loop implementation of the Hampel filter. We base the code on the one from the pracma R package." }, { "code": null, "e": 3418, "s": 3286, "text": "We run the algorithm on the RW series. We chose window size 10, but this should be determined empirically for the best performance." }, { "code": null, "e": 3473, "s": 3418, "text": "res, detected_outliers = hampel_filter_forloop(rw, 10)" }, { "code": null, "e": 3543, "s": 3473, "text": "We evaluate the results using the previously defined helper function." }, { "code": null, "e": 3611, "s": 3543, "text": "tp, fp, fn = evaluate_detection(rw, outlier_ind, detected_outliers)" }, { "code": null, "e": 3915, "s": 3611, "text": "In the plot, we can see that the algorithm correctly identified 8 (out of 10) outliers, mistook one observation for an outlier (red dot) and missed 2 outliers (black dots). Perhaps better performance can be achieved by tuning the window size. However, this is sufficient for the purpose of the exercise." }, { "code": null, "e": 4020, "s": 3915, "text": "We additionally plot the transformed series, in which the outliers were replaced with the window median." }, { "code": null, "e": 4248, "s": 4020, "text": "plt.plot(np.arange(len(res)), res);plt.scatter(outlier_ind, rw[outlier_ind], c='g', label='true outlier')plt.scatter(fp, rw[fp], c='r', label='false positive')plt.title('Cleaned series (without detected outliers)')plt.legend();" }, { "code": null, "e": 4273, "s": 4248, "text": "2. pandas implementation" }, { "code": null, "e": 4375, "s": 4273, "text": "For the pandas implementation we make use of the rolling method of a pd.Series and a lambda function." }, { "code": null, "e": 4608, "s": 4375, "text": "In the rolling method we specify twice the window size and use centering, so the considered observation is in the middle of a 2 * window_size + 1 window. Before running the algorithm, we transform the RW from np.ndarray topd.Series." }, { "code": null, "e": 4761, "s": 4608, "text": "rw_series = pd.Series(rw)res, detected_outliers = hampel_filter_pandas(rw_series, 10)tp, fp, fn = evaluate_detection(rw, outlier_ind, detected_outliers)" }, { "code": null, "e": 4838, "s": 4761, "text": "The results of both approaches are identical, which is always a good sign :)" }, { "code": null, "e": 4984, "s": 4838, "text": "At this point, we test the two implementations against each other in terms of execution speed. We expect that the pandas one will perform faster." }, { "code": null, "e": 5028, "s": 4984, "text": "First, we test the for-loop implementation:" }, { "code": null, "e": 5162, "s": 5028, "text": "%%timeitres, detected_outliers = hampel_filter_forloop(rw, 10)# 67.9 ms ± 990 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)" }, { "code": null, "e": 5226, "s": 5162, "text": "Then, we run the analogical test for the pandas implementation:" }, { "code": null, "e": 5367, "s": 5226, "text": "%%timeitres, detected_outliers = hampel_filter_pandas(rw_series, 10)# 76.1 ms ± 4.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)" }, { "code": null, "e": 5636, "s": 5367, "text": "We see that the pandas implementation turned out to be slower. One hypothesis to test is that the pandas implementation will be faster for a larger series. That is why we also increase the length of the random walk series to 100000 and test the performance once again." }, { "code": null, "e": 5723, "s": 5636, "text": "rw, outlier_ind = random_walk_with_outliers(0, 10 ** 5, 0.01)rw_series = pd.Series(rw)" }, { "code": null, "e": 5782, "s": 5723, "text": "Having prepared the data, we move to test the performance:" }, { "code": null, "e": 6050, "s": 5782, "text": "%%timeitres, detected_outliers = hampel_filter_forloop(rw, 10)# 6.75 s ± 203 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)%%timeitres, detected_outliers = hampel_filter_pandas(rw_series, 10)# 6.76 s ± 30.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)" }, { "code": null, "e": 6203, "s": 6050, "text": "It turns out that now they achieved comparable performance, with the pandas implementation providing more stable performance (lower standard deviation)." }, { "code": null, "e": 6512, "s": 6203, "text": "As a bonus, we explore the possibility of speeding up the code based on for-loops with numba. numba is a library that under-the-hood translates Python code into an optimized machine code. Given it is possible to transform the code, numba can make certain algorithms written in Python approach the speed of C." }, { "code": null, "e": 6739, "s": 6512, "text": "The best part about numba is that (if possible) the speed boost comes at a very small price in terms of coding. We need to import the library and add the @jit decorator before the function we want to translate to machine code." }, { "code": null, "e": 6950, "s": 6739, "text": "The nopython argument indicates if we want numba to use purely machine code or to use some Python code if necessary. Ideally, this should always be set to true, as long as there are no errors returned by numba." }, { "code": null, "e": 6985, "s": 6950, "text": "Below we test the execution speed." }, { "code": null, "e": 7122, "s": 6985, "text": "%%timeitres, detected_outliers = hampel_filter_forloop_numba(rw, 10)# 108 ms ± 1.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)" }, { "code": null, "e": 7259, "s": 7122, "text": "It only takes 108 ms (milliseconds) as compared to 6.76 s in case of the pandas implementation! That is a massive speed-up of ~63 times!" }, { "code": null, "e": 7461, "s": 7259, "text": "Summing up, in this article we showed explained how Hampel filter work in terms of outlier detection and how to implement it in Python. We also compared the implementations in terms of execution speed." }, { "code": null, "e": 7525, "s": 7461, "text": "It is also good to consider the drawbacks of the Hampel filter:" }, { "code": null, "e": 7709, "s": 7525, "text": "it has problems with detecting outliers at the beginning and the end of the series — when the window is not complete (even on one side), the function does not detect possible outliers" }, { "code": null, "e": 7801, "s": 7709, "text": "it struggles to detect outliers when they are close to each other — within the window range" }, { "code": null, "e": 7963, "s": 7801, "text": "As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. You can find the code used for this article on my GitHub." }, { "code": null, "e": 8177, "s": 7963, "text": "Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!" }, { "code": null, "e": 8315, "s": 8177, "text": "Hampel F. R., ”The influence curve and its role in robust estimation,” Journal of the American Statistical Association, 69, 382–393, 1974" }, { "code": null, "e": 8475, "s": 8315, "text": "Liu, Hancong, Sirish Shah, and Wei Jiang. “On-line outlier detection and data cleaning.” Computers and Chemical Engineering. Vol. 28, March 2004, pp. 1635–1647" } ]
MySQL date column auto fill with current date?
You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Case 1: The syntax is as follows: yourDateColumnName date default ‘yourDateValue’; Case 2: The syntax is as follows: yourDateColumnName datetime default now(); To understand the above, let us create a table. The query to create a table is as follows: mysql> create table DefaultCurrentdateDemo -> ( -> LoginDate datetime default now() -> ); Query OK, 0 rows affected (0.59 sec) Insert some records in the table using insert command. The query is as follows: mysql> insert into DefaultCurrentdateDemo values(); Query OK, 1 row affected (0.18 sec) mysql> insert into DefaultCurrentdateDemo values('2017-11-19'); Query OK, 1 row affected (0.16 sec) mysql> insert into DefaultCurrentdateDemo values('2018-10-21'); Query OK, 1 row affected (0.12 sec) mysql> insert into DefaultCurrentdateDemo values(); Query OK, 1 row affected (0.23 sec) mysql> insert into DefaultCurrentdateDemo values('2020-12-24'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from DefaultCurrentdateDemo; The following is the output: +---------------------+ | LoginDate | +---------------------+ | 2019-01-12 20:33:51 | | 2017-11-19 00:00:00 | | 2018-10-21 00:00:00 | | 2019-01-12 20:34:37 | | 2020-12-24 00:00:00 | +---------------------+ 5 rows in set (0.00 sec) If you want to extract only date, then use the date() method. The query is as follows: mysql> select date(LoginDate) as OnlyDate from DefaultCurrentdateDemo; The following is the output: +------------+ | OnlyDate | +------------+ | 2019-01-12 | | 2017-11-19 | | 2018-10-21 | | 2019-01-12 | | 2020-12-24 | +------------+ 5 rows in set (0.00 sec) Let us set the default value with some date. The query to create a default value to date column is as follows: mysql> create table DefaultDate -> ( -> LoginDate date default '2019-01-12' -> ); Query OK, 0 rows affected (0.53 sec) If you do not pass any value to the column then default value will be provided to the column. The query to insert record is as follows: mysql> insert into DefaultDate values(); Query OK, 1 row affected (0.13 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from DefaultDate; The following is the output: +------------+ | LoginDate | +------------+ | 2019-01-12 | +------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1199, "s": 1062, "text": "You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function." }, { "code": null, "e": 1207, "s": 1199, "text": "Case 1:" }, { "code": null, "e": 1233, "s": 1207, "text": "The syntax is as follows:" }, { "code": null, "e": 1282, "s": 1233, "text": "yourDateColumnName date default ‘yourDateValue’;" }, { "code": null, "e": 1290, "s": 1282, "text": "Case 2:" }, { "code": null, "e": 1316, "s": 1290, "text": "The syntax is as follows:" }, { "code": null, "e": 1359, "s": 1316, "text": "yourDateColumnName datetime default now();" }, { "code": null, "e": 1450, "s": 1359, "text": "To understand the above, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1586, "s": 1450, "text": "mysql> create table DefaultCurrentdateDemo\n -> (\n -> LoginDate datetime default now()\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1666, "s": 1586, "text": "Insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2146, "s": 1666, "text": "mysql> insert into DefaultCurrentdateDemo values();\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into DefaultCurrentdateDemo values('2017-11-19');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DefaultCurrentdateDemo values('2018-10-21');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DefaultCurrentdateDemo values();\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DefaultCurrentdateDemo values('2020-12-24');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2230, "s": 2146, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2274, "s": 2230, "text": "mysql> select *from DefaultCurrentdateDemo;" }, { "code": null, "e": 2303, "s": 2274, "text": "The following is the output:" }, { "code": null, "e": 2534, "s": 2303, "text": "+---------------------+\n| LoginDate |\n+---------------------+\n| 2019-01-12 20:33:51 |\n| 2017-11-19 00:00:00 |\n| 2018-10-21 00:00:00 |\n| 2019-01-12 20:34:37 |\n| 2020-12-24 00:00:00 |\n+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2621, "s": 2534, "text": "If you want to extract only date, then use the date() method. The query is as follows:" }, { "code": null, "e": 2692, "s": 2621, "text": "mysql> select date(LoginDate) as OnlyDate from DefaultCurrentdateDemo;" }, { "code": null, "e": 2721, "s": 2692, "text": "The following is the output:" }, { "code": null, "e": 2879, "s": 2721, "text": "+------------+\n| OnlyDate |\n+------------+\n| 2019-01-12 |\n| 2017-11-19 |\n| 2018-10-21 |\n| 2019-01-12 |\n| 2020-12-24 |\n+------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2924, "s": 2879, "text": "Let us set the default value with some date." }, { "code": null, "e": 2990, "s": 2924, "text": "The query to create a default value to date column is as follows:" }, { "code": null, "e": 3118, "s": 2990, "text": "mysql> create table DefaultDate\n -> (\n -> LoginDate date default '2019-01-12'\n -> );\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 3254, "s": 3118, "text": "If you do not pass any value to the column then default value will be provided to the column. The query to insert record is as follows:" }, { "code": null, "e": 3331, "s": 3254, "text": "mysql> insert into DefaultDate values();\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 3372, "s": 3331, "text": "Display all records from the table using" }, { "code": null, "e": 3415, "s": 3372, "text": "select statement. The query is as follows:" }, { "code": null, "e": 3448, "s": 3415, "text": "mysql> select *from DefaultDate;" }, { "code": null, "e": 3477, "s": 3448, "text": "The following is the output:" }, { "code": null, "e": 3576, "s": 3477, "text": "+------------+\n| LoginDate |\n+------------+\n| 2019-01-12 |\n+------------+\n1 row in set (0.00 sec)" } ]
How can we implement a timer thread in Java?
The Timer class schedules a task to run at a given time once or repeatedly. It can also run in the background as a daemon thread. To associate Timer with a daemon thread, there is a constructor with a boolean value. The Timer schedules a task with fixed delay as well as a fixed rate. In a fixed delay, if any execution is delayed by System GC, the other execution will also be delayed and every execution is delayed corresponding to previous execution. In a fixed rate, if any execution is delayed by System GC then 2-3 execution happens consecutively to cover the fixed rate corresponding to the first execution start time. The Timer class provides a cancel() method to cancel a timer. When this method is called, the Timer is terminated. The Timer class executes only the task that implements the TimerTask. import java.util.*; public class TimerThreadTest { public static void main(String []args) { Task t1 = new Task("Task 1"); Task t2 = new Task("Task 2"); Timer t = new Timer(); t.schedule(t1, 10000); // executes for every 10 seconds t.schedule(t2, 1000, 2000); // executes for every 2 seconds } } class Task extends TimerTask { private String name; public Task(String name) { this.name = name; } public void run() { System.out.println("[" + new Date() + "] " + name + ": task executed!"); } } [Thu Aug 01 21:32:44 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:46 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:48 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:50 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:52 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:53 IST 2019] Task 1: task executed! [Thu Aug 01 21:32:54 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:56 IST 2019] Task 2: task executed! [Thu Aug 01 21:32:58 IST 2019] Task 2: task executed! [Thu Aug 01 21:33:00 IST 2019] Task 2: task executed!
[ { "code": null, "e": 1873, "s": 1062, "text": "The Timer class schedules a task to run at a given time once or repeatedly. It can also run in the background as a daemon thread. To associate Timer with a daemon thread, there is a constructor with a boolean value. The Timer schedules a task with fixed delay as well as a fixed rate. In a fixed delay, if any execution is delayed by System GC, the other execution will also be delayed and every execution is delayed corresponding to previous execution. In a fixed rate, if any execution is delayed by System GC then 2-3 execution happens consecutively to cover the fixed rate corresponding to the first execution start time. The Timer class provides a cancel() method to cancel a timer. When this method is called, the Timer is terminated. The Timer class executes only the task that implements the TimerTask." }, { "code": null, "e": 2429, "s": 1873, "text": "import java.util.*;\npublic class TimerThreadTest {\n public static void main(String []args) {\n Task t1 = new Task(\"Task 1\");\n Task t2 = new Task(\"Task 2\");\n Timer t = new Timer();\n t.schedule(t1, 10000); // executes for every 10 seconds\n t.schedule(t2, 1000, 2000); // executes for every 2 seconds\n }\n}\nclass Task extends TimerTask {\n private String name;\n public Task(String name) {\n this.name = name;\n }\n public void run() {\n System.out.println(\"[\" + new Date() + \"] \" + name + \": task executed!\");\n }\n}" }, { "code": null, "e": 2969, "s": 2429, "text": "[Thu Aug 01 21:32:44 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:46 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:48 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:50 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:52 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:53 IST 2019] Task 1: task executed!\n[Thu Aug 01 21:32:54 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:56 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:32:58 IST 2019] Task 2: task executed!\n[Thu Aug 01 21:33:00 IST 2019] Task 2: task executed!" } ]
Forgetting in Deep Learning. Team member: Qiang Fei, Yingsi Jian... | by Mingyue Wei | Towards Data Science
Authors: Qiang Fei, Yingsi Jian, Mingyue Wei, Shuyuan Xiao You may also checkout the contents through our project poster and video. Disclaimer: The views expressed in this blog are those of the authors and are not endorsed by Harvard or Google. Neural network models suffer from the phenomenon of catastrophic forgetting: a model can drastically lose its generalization ability on a task after being trained on a new task. This usually means a new task will likely override the weights that have been learned in the past (see Figure 1), and thus degrade the model performance for the past tasks. Without fixing this problem, a single neural network will not be able to adapt itself to a continuous learning scenario, because it forgets the existing information/knowledge when it learns new things. For realistic applications of deep learning, where continual learning can be crucial, catastrophic forgetting would need to be avoided. However, there is only limited study about catastrophic forgetting and its underlying causes. In this project, we will explore how commonly used deep learning methods mitigate or exacerbate the degree of forgetting (e.g. batch-norm, dropout, data augmentation, weight decay, etc.). Further, we would like to select one or several methods and try to learn about the cause of effects. For forgetting measurement, the main approach is to revisit a task after training on later tasks and compare the accuracy before and after2. With different task settings, Kemker et al. proposed a method specifically for incremental class learning3 (for each new section, data of a single class will be learned), and Arora et al. suggest using scaled accuracy when comparing different models4. There have been studies of ways to reduce the forgetting effect, and some of the proposed or accepted methods include: adding dropout layers5, max pooling, decreasing number of layers, and decreasing learning rates. The dataset we use is CIFAR-10. This dataset consists of 60,000 color images in total, evenly divided into 10 classes. For each class, 5,000 images are in the train set and the remaining are in the test set. The images are of size 32x32. The 10 classes of the dataset are: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck We went with the approach of comparing before and after accuracy to measure forgetting effects. Our experiment workflow is shown in Figure 2. The whole dataset is first evenly split into task 1 and task 2, each consisting of 5 classes of images. We train the model consecutively on task 1 and task 2, and after that, we re-evaluate the model on task 1 data by only refitting the output layer. The two accuracy scores were then compared. Accuracy 1: Accuracy on task 1 test before task 2 trainingAccuracy 2: Accuracy on task 2 test after task 2 trainingForgetting = Accuracy 1 - Accuracy 2 We used 2 sets of splits throughout the experiments. The first set was used during the initial modeling and exploration stage, which consists of 5 different splits, (split 0 to split 4), all are randomly divided. We formalized the second set of splits after some experiments, which consists of one semantic split based on image similarity from human perspective and two random splits. This set was used for extended experiments of random shift and constant learning rate experiments. Following are the task 1 classes for each split: Semantic split: airplane, automobile, bird, ship, truck Random split 1: airplane, deer, frog, ship, truck Random split 2: automobile, cat, deer, frog, ship Figure 3 shows the structure of our model. It is a customized CNN with decent performance across various task splits and trials, achieving consistent Accuracy 1 around 90%. Other than the input and output layer, the model consists of 4 intermediate convolutional blocks, each with 2 convolutional layers, 1 batch normalization layer, 1 max pooling layer, and 1 dropout layer with 0.2 dropout rate. The main objective of our experiments was to confirm whether the proposed methods of mitigating forgetting effects could work. We had two major directions: the first consists of experiments with various data augmentation methods, and the second dealt with training settings, including learning rate, weight decay, and training epochs. After initial exploration of these approaches, we specifically extended our experiments on random shifting in data augmentation, and learning rate in training settings. We experimented with some basic data augmentation methods: Horizontal/Vertical FlipRandom Shift up to 10% and up to 20%Random Rotation up to 10°, 15°, 20° Horizontal/Vertical Flip Random Shift up to 10% and up to 20% Random Rotation up to 10°, 15°, 20° These data augmentation methods were applied on both task 1 and task 2 training process. The test set did not involve any data augmentation. Their influences on forgetting comparing to the baseline are shown in Figure 4. There is some variation between different data splits from the results. For most of the data augmentation methods, we cannot conclude if they have any effect on forgetting, as in some splits they increased forgetting while in some they did not, and the change was also generally not large. However, among all the methods, random shift were clearly increasing forgetting, and the influence seems to increase when we shift more. We confirmed that Accuracy 1 of the models with random shifts were comparable to that of baseline without data augmentation, and as results were consistent across all 5 task splits, we believe that random shift does increase forgetting. This is interesting and quite surprising for us to learn more because random shift is a popular method applied to CIFAR-10 data to improve model performance. Apart from basic data augmentation methods, we also experimented with mixup. Mixup is a popular method that can improve classification accuracy (as shown in Figure 5). Instead of feeding the network with raw images, mixup refers to take 2 images and do a linear combination of them using λ: y_new = λ × (1 - y1) + (1 - λ) × y2x_new = λ × (1 - x1) + (1 - λ) × x2 λ is a number between 0 and 1 and is drawn from Beta(α, α) each time, with α being a pre-defined hyper-parameter. Smaller α creates less mixup effect, and mixup with large α could lead to under-fitting. We experimented with α values of [0.1, 0.2, 0.3, 0.4], all within the suggested range from Zhang et al.6 Figure 6 shows results from mixup experiments. For most of the data splits and α values, mixup did not mitigate forgetting. Impact of mixup on forgetting varied across different data splits as well, e.g. when α= 0.1, forgetting was decreased with two data splits but increased with the other. After the initial experiments, we reached the following conclusions: Random shift increases forgetting under the current setting.Mix up improves prediction accuracy but does not mitigate forgetting.The effect on forgetting of most data augmentation methods depends on data splits, thus generalization is not an easy get. Random shift increases forgetting under the current setting. Mix up improves prediction accuracy but does not mitigate forgetting. The effect on forgetting of most data augmentation methods depends on data splits, thus generalization is not an easy get. Based on these, we performed extended experiments with random shift using the second set of task splits. In addition to the previous experiments applying random shift to both task 1 and task 2, we also did experiments where random shift was applied only to task 1, the results of which were presented in dashed lines in Figure 7. As the images are of size 32x32, we controlled the number of pixels up to which the image might shift in each experiment, with random shift of 4 pixels being the common practice in the field. All experiments were repeated 9 times and the average is presented. In the third plot, we can see that when applying random shift to both task 1 and task 2, there is a clear trend across all data splits, that forgetting decreases when the images were randomly shifted for 1 pixel and then increases when shifted pixels increase. Learning rate controls the speed of neural network updating its weights during training. We did two sets of exploration experiments study the effect of learning rate on forgetting. We experimented with 5 initial learning rates [0.001, 0.005, 0.01, 0.05, 0.1] based on common practice. We applied piecewise learning rate decay which applies cascading decrease after every certain amount of iterations. The same learning rate and rate decay were applied to both Task 1 and Task 2 training. The experiment was run on one task split only. Figure 8 presents the results. Learning rates 0.05, 0.01, and 0.005 had similar effects on Accuracy 1, but given the similar Accuracy 1, they had different effects on forgetting. Learning rate 0.005 resulted in the least amount of forgetting. We experimented with 4 initial learning rates: [0.005, 0.01, 0.05, 0.1] and thus there were a total of 16 pairs of (task 1 learning rate, task 2 learning rate). Figure 9 shows the results of the experiments. However, either fixing initial learning rate on task 1 or task 2 did not give apparent trend. One observation is that the diagonal seems to have the least forgetting, which corresponds to cases when task 1 and task 2 have the same initial learning rates. With the experiments in exploration, it is hard to draw more conclusions because there are too many hyper-parameters to select for each experiment setting, and it was hard to associate the forgetting effect with any single one of them. We then decided to focused on constant learning rate experiments without rate decay. We experimented with learning rates [0.0005, 0.001, 0.005, 0.01, 0.05], same for task 1 and task 2. These were selected based on Accuracy 1, i.e. they all achieve comparable Accuracy with these learning rates. Figure 10 shows the forgetting effects in the three splits. Heat map is easier to discern trend when we need to fix value on one of the axes. From the plots we got the following conclusions: Holding task 1 learning rate constant, decreasing task 2 learning rate mitigates the forgettingHolding task 2 learning rate constant, increasing task 1 learning rate mitigates the forgetting Holding task 1 learning rate constant, decreasing task 2 learning rate mitigates the forgetting Holding task 2 learning rate constant, increasing task 1 learning rate mitigates the forgetting Task 2 Frozen Accuracy Tests In order to investigate why increasing the learning rate on task 1 could decrease forgetting effects, we also experimented with task 2 frozen accuracy, which is the test accuracy on task 2 without training on task 2. The hypothesis we wanted to test is that larger task 1 learning rate leads to better features generated, which then lead to mitigated forgetting. However, our experiments did not show a trend or relationship between task 1 learning rate and task 2 frozen accuracy. We set up experiments by fixing task 2 training epochs to learn the effect of number of epochs for task 1 on forgetting. Since both tasks training converge at around 40 epochs, we set task 2 training epoch = 40 and experimented with task 1 training epoch = [40, 60, 80, 100]. Figure 11 shows that Accuracy 1 generally increases when the number of epochs increases, which aligns with common notice of longer training leading to better performance. But in the meanwhile, the forgetting effect generally increases when the task 1 number of epochs increases. We also ran experiments to investigate the influence of weight decay on forgetting. We did 2 sets of experiments: adding weight decay to the Conv2D layers in the first convolutional blockadding weight decay to the Conv2D layers in the last convolutional block adding weight decay to the Conv2D layers in the first convolutional block adding weight decay to the Conv2D layers in the last convolutional block For each set of experiments, we applied the l2 regularizer to weights and bias with the same rate, and we tested rates: [0.01, 0.05, 0.1, 0.2]. Other than these experiments, we also performed a grid search with learning rates [0.0008, 0.001, 0.002] and decay rates [5e-5 ,1e-4, 5e-4, 1e-3]. We applied weight decay on all Conv2D layers for either task 1 or task 2. Accuracy 1 all seem valid with these settings. However, the resultant forgetting did not show consistent trends between different data splits, and thus we could not reach a conclusion on the effect of weight decay on forgetting. From our four sets of experiments, we find some interesting results related to data augmentation and learning rates. Our next step would be to interpret these results. More specifically, for the data augmentation part, we want to know why random shifts and mixup have such relationships with forgetting. For learning rate, we would also like to explore why increasing task 1 learning rate mitigates forgetting. One hypothesis is that larger task 1 learning rate helps capture and generate better features, but we would need other control experiments to test it. [1] Kolouri, S., Ketz, N., Zou, X., Krichmar, J., & Pilly, P. (2019). Attention-based selective plasticity. [2] Ramasesh, V. V., Dyer, E., & Raghu, M. (2020). Anatomy of catastrophic forgetting: Hidden representations and task semantics. arXiv preprint arXiv:2007.07400. [3] Kemker, R., McClure, M., Abitino, A., Hayes, T., & Kanan, C. (2017). Measuring catastrophic forgetting in neural networks. arXiv preprint arXiv:1708.02072. [4] Arora, G., Rahimi, A., & Baldwin, T. (2019). Does an LSTM forget more than a CNN? An empirical study of catastrophic forgetting in NLP. In Proceedings of the The 17th Annual Workshop of the Australasian Language Technology Association (pp. 77–86). [5] Goodfellow, I. J., Mirza, M., Xiao, D., Courville, A., & Bengio, Y. (2013). An empirical investigation of catastrophic forgetting in gradient-based neural networks. arXiv preprint arXiv:1312.6211. [6] Zhang, H., Cisse, M., Dauphin, Y. N., & Lopez-Paz, D. (2017). mixup: Beyond empirical risk minimization. arXiv preprint arXiv:1710.09412.
[ { "code": null, "e": 231, "s": 172, "text": "Authors: Qiang Fei, Yingsi Jian, Mingyue Wei, Shuyuan Xiao" }, { "code": null, "e": 304, "s": 231, "text": "You may also checkout the contents through our project poster and video." }, { "code": null, "e": 417, "s": 304, "text": "Disclaimer: The views expressed in this blog are those of the authors and are not endorsed by Harvard or Google." }, { "code": null, "e": 970, "s": 417, "text": "Neural network models suffer from the phenomenon of catastrophic forgetting: a model can drastically lose its generalization ability on a task after being trained on a new task. This usually means a new task will likely override the weights that have been learned in the past (see Figure 1), and thus degrade the model performance for the past tasks. Without fixing this problem, a single neural network will not be able to adapt itself to a continuous learning scenario, because it forgets the existing information/knowledge when it learns new things." }, { "code": null, "e": 1489, "s": 970, "text": "For realistic applications of deep learning, where continual learning can be crucial, catastrophic forgetting would need to be avoided. However, there is only limited study about catastrophic forgetting and its underlying causes. In this project, we will explore how commonly used deep learning methods mitigate or exacerbate the degree of forgetting (e.g. batch-norm, dropout, data augmentation, weight decay, etc.). Further, we would like to select one or several methods and try to learn about the cause of effects." }, { "code": null, "e": 1882, "s": 1489, "text": "For forgetting measurement, the main approach is to revisit a task after training on later tasks and compare the accuracy before and after2. With different task settings, Kemker et al. proposed a method specifically for incremental class learning3 (for each new section, data of a single class will be learned), and Arora et al. suggest using scaled accuracy when comparing different models4." }, { "code": null, "e": 2098, "s": 1882, "text": "There have been studies of ways to reduce the forgetting effect, and some of the proposed or accepted methods include: adding dropout layers5, max pooling, decreasing number of layers, and decreasing learning rates." }, { "code": null, "e": 2371, "s": 2098, "text": "The dataset we use is CIFAR-10. This dataset consists of 60,000 color images in total, evenly divided into 10 classes. For each class, 5,000 images are in the train set and the remaining are in the test set. The images are of size 32x32. The 10 classes of the dataset are:" }, { "code": null, "e": 2440, "s": 2371, "text": "airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck" }, { "code": null, "e": 2582, "s": 2440, "text": "We went with the approach of comparing before and after accuracy to measure forgetting effects. Our experiment workflow is shown in Figure 2." }, { "code": null, "e": 2833, "s": 2582, "text": "The whole dataset is first evenly split into task 1 and task 2, each consisting of 5 classes of images. We train the model consecutively on task 1 and task 2, and after that, we re-evaluate the model on task 1 data by only refitting the output layer." }, { "code": null, "e": 2877, "s": 2833, "text": "The two accuracy scores were then compared." }, { "code": null, "e": 3029, "s": 2877, "text": "Accuracy 1: Accuracy on task 1 test before task 2 trainingAccuracy 2: Accuracy on task 2 test after task 2 trainingForgetting = Accuracy 1 - Accuracy 2" }, { "code": null, "e": 3082, "s": 3029, "text": "We used 2 sets of splits throughout the experiments." }, { "code": null, "e": 3242, "s": 3082, "text": "The first set was used during the initial modeling and exploration stage, which consists of 5 different splits, (split 0 to split 4), all are randomly divided." }, { "code": null, "e": 3562, "s": 3242, "text": "We formalized the second set of splits after some experiments, which consists of one semantic split based on image similarity from human perspective and two random splits. This set was used for extended experiments of random shift and constant learning rate experiments. Following are the task 1 classes for each split:" }, { "code": null, "e": 3618, "s": 3562, "text": "Semantic split: airplane, automobile, bird, ship, truck" }, { "code": null, "e": 3668, "s": 3618, "text": "Random split 1: airplane, deer, frog, ship, truck" }, { "code": null, "e": 3718, "s": 3668, "text": "Random split 2: automobile, cat, deer, frog, ship" }, { "code": null, "e": 3891, "s": 3718, "text": "Figure 3 shows the structure of our model. It is a customized CNN with decent performance across various task splits and trials, achieving consistent Accuracy 1 around 90%." }, { "code": null, "e": 4116, "s": 3891, "text": "Other than the input and output layer, the model consists of 4 intermediate convolutional blocks, each with 2 convolutional layers, 1 batch normalization layer, 1 max pooling layer, and 1 dropout layer with 0.2 dropout rate." }, { "code": null, "e": 4451, "s": 4116, "text": "The main objective of our experiments was to confirm whether the proposed methods of mitigating forgetting effects could work. We had two major directions: the first consists of experiments with various data augmentation methods, and the second dealt with training settings, including learning rate, weight decay, and training epochs." }, { "code": null, "e": 4620, "s": 4451, "text": "After initial exploration of these approaches, we specifically extended our experiments on random shifting in data augmentation, and learning rate in training settings." }, { "code": null, "e": 4679, "s": 4620, "text": "We experimented with some basic data augmentation methods:" }, { "code": null, "e": 4775, "s": 4679, "text": "Horizontal/Vertical FlipRandom Shift up to 10% and up to 20%Random Rotation up to 10°, 15°, 20°" }, { "code": null, "e": 4800, "s": 4775, "text": "Horizontal/Vertical Flip" }, { "code": null, "e": 4837, "s": 4800, "text": "Random Shift up to 10% and up to 20%" }, { "code": null, "e": 4873, "s": 4837, "text": "Random Rotation up to 10°, 15°, 20°" }, { "code": null, "e": 5094, "s": 4873, "text": "These data augmentation methods were applied on both task 1 and task 2 training process. The test set did not involve any data augmentation. Their influences on forgetting comparing to the baseline are shown in Figure 4." }, { "code": null, "e": 5384, "s": 5094, "text": "There is some variation between different data splits from the results. For most of the data augmentation methods, we cannot conclude if they have any effect on forgetting, as in some splits they increased forgetting while in some they did not, and the change was also generally not large." }, { "code": null, "e": 5916, "s": 5384, "text": "However, among all the methods, random shift were clearly increasing forgetting, and the influence seems to increase when we shift more. We confirmed that Accuracy 1 of the models with random shifts were comparable to that of baseline without data augmentation, and as results were consistent across all 5 task splits, we believe that random shift does increase forgetting. This is interesting and quite surprising for us to learn more because random shift is a popular method applied to CIFAR-10 data to improve model performance." }, { "code": null, "e": 6207, "s": 5916, "text": "Apart from basic data augmentation methods, we also experimented with mixup. Mixup is a popular method that can improve classification accuracy (as shown in Figure 5). Instead of feeding the network with raw images, mixup refers to take 2 images and do a linear combination of them using λ:" }, { "code": null, "e": 6280, "s": 6207, "text": "y_new = λ × (1 - y1) + (1 - λ) × y2x_new = λ × (1 - x1) + (1 - λ) × x2" }, { "code": null, "e": 6588, "s": 6280, "text": "λ is a number between 0 and 1 and is drawn from Beta(α, α) each time, with α being a pre-defined hyper-parameter. Smaller α creates less mixup effect, and mixup with large α could lead to under-fitting. We experimented with α values of [0.1, 0.2, 0.3, 0.4], all within the suggested range from Zhang et al.6" }, { "code": null, "e": 6881, "s": 6588, "text": "Figure 6 shows results from mixup experiments. For most of the data splits and α values, mixup did not mitigate forgetting. Impact of mixup on forgetting varied across different data splits as well, e.g. when α= 0.1, forgetting was decreased with two data splits but increased with the other." }, { "code": null, "e": 6950, "s": 6881, "text": "After the initial experiments, we reached the following conclusions:" }, { "code": null, "e": 7202, "s": 6950, "text": "Random shift increases forgetting under the current setting.Mix up improves prediction accuracy but does not mitigate forgetting.The effect on forgetting of most data augmentation methods depends on data splits, thus generalization is not an easy get." }, { "code": null, "e": 7263, "s": 7202, "text": "Random shift increases forgetting under the current setting." }, { "code": null, "e": 7333, "s": 7263, "text": "Mix up improves prediction accuracy but does not mitigate forgetting." }, { "code": null, "e": 7456, "s": 7333, "text": "The effect on forgetting of most data augmentation methods depends on data splits, thus generalization is not an easy get." }, { "code": null, "e": 7561, "s": 7456, "text": "Based on these, we performed extended experiments with random shift using the second set of task splits." }, { "code": null, "e": 8046, "s": 7561, "text": "In addition to the previous experiments applying random shift to both task 1 and task 2, we also did experiments where random shift was applied only to task 1, the results of which were presented in dashed lines in Figure 7. As the images are of size 32x32, we controlled the number of pixels up to which the image might shift in each experiment, with random shift of 4 pixels being the common practice in the field. All experiments were repeated 9 times and the average is presented." }, { "code": null, "e": 8307, "s": 8046, "text": "In the third plot, we can see that when applying random shift to both task 1 and task 2, there is a clear trend across all data splits, that forgetting decreases when the images were randomly shifted for 1 pixel and then increases when shifted pixels increase." }, { "code": null, "e": 8488, "s": 8307, "text": "Learning rate controls the speed of neural network updating its weights during training. We did two sets of exploration experiments study the effect of learning rate on forgetting." }, { "code": null, "e": 8842, "s": 8488, "text": "We experimented with 5 initial learning rates [0.001, 0.005, 0.01, 0.05, 0.1] based on common practice. We applied piecewise learning rate decay which applies cascading decrease after every certain amount of iterations. The same learning rate and rate decay were applied to both Task 1 and Task 2 training. The experiment was run on one task split only." }, { "code": null, "e": 9085, "s": 8842, "text": "Figure 8 presents the results. Learning rates 0.05, 0.01, and 0.005 had similar effects on Accuracy 1, but given the similar Accuracy 1, they had different effects on forgetting. Learning rate 0.005 resulted in the least amount of forgetting." }, { "code": null, "e": 9246, "s": 9085, "text": "We experimented with 4 initial learning rates: [0.005, 0.01, 0.05, 0.1] and thus there were a total of 16 pairs of (task 1 learning rate, task 2 learning rate)." }, { "code": null, "e": 9548, "s": 9246, "text": "Figure 9 shows the results of the experiments. However, either fixing initial learning rate on task 1 or task 2 did not give apparent trend. One observation is that the diagonal seems to have the least forgetting, which corresponds to cases when task 1 and task 2 have the same initial learning rates." }, { "code": null, "e": 9869, "s": 9548, "text": "With the experiments in exploration, it is hard to draw more conclusions because there are too many hyper-parameters to select for each experiment setting, and it was hard to associate the forgetting effect with any single one of them. We then decided to focused on constant learning rate experiments without rate decay." }, { "code": null, "e": 10079, "s": 9869, "text": "We experimented with learning rates [0.0005, 0.001, 0.005, 0.01, 0.05], same for task 1 and task 2. These were selected based on Accuracy 1, i.e. they all achieve comparable Accuracy with these learning rates." }, { "code": null, "e": 10270, "s": 10079, "text": "Figure 10 shows the forgetting effects in the three splits. Heat map is easier to discern trend when we need to fix value on one of the axes. From the plots we got the following conclusions:" }, { "code": null, "e": 10461, "s": 10270, "text": "Holding task 1 learning rate constant, decreasing task 2 learning rate mitigates the forgettingHolding task 2 learning rate constant, increasing task 1 learning rate mitigates the forgetting" }, { "code": null, "e": 10557, "s": 10461, "text": "Holding task 1 learning rate constant, decreasing task 2 learning rate mitigates the forgetting" }, { "code": null, "e": 10653, "s": 10557, "text": "Holding task 2 learning rate constant, increasing task 1 learning rate mitigates the forgetting" }, { "code": null, "e": 10682, "s": 10653, "text": "Task 2 Frozen Accuracy Tests" }, { "code": null, "e": 11164, "s": 10682, "text": "In order to investigate why increasing the learning rate on task 1 could decrease forgetting effects, we also experimented with task 2 frozen accuracy, which is the test accuracy on task 2 without training on task 2. The hypothesis we wanted to test is that larger task 1 learning rate leads to better features generated, which then lead to mitigated forgetting. However, our experiments did not show a trend or relationship between task 1 learning rate and task 2 frozen accuracy." }, { "code": null, "e": 11440, "s": 11164, "text": "We set up experiments by fixing task 2 training epochs to learn the effect of number of epochs for task 1 on forgetting. Since both tasks training converge at around 40 epochs, we set task 2 training epoch = 40 and experimented with task 1 training epoch = [40, 60, 80, 100]." }, { "code": null, "e": 11719, "s": 11440, "text": "Figure 11 shows that Accuracy 1 generally increases when the number of epochs increases, which aligns with common notice of longer training leading to better performance. But in the meanwhile, the forgetting effect generally increases when the task 1 number of epochs increases." }, { "code": null, "e": 11833, "s": 11719, "text": "We also ran experiments to investigate the influence of weight decay on forgetting. We did 2 sets of experiments:" }, { "code": null, "e": 11979, "s": 11833, "text": "adding weight decay to the Conv2D layers in the first convolutional blockadding weight decay to the Conv2D layers in the last convolutional block" }, { "code": null, "e": 12053, "s": 11979, "text": "adding weight decay to the Conv2D layers in the first convolutional block" }, { "code": null, "e": 12126, "s": 12053, "text": "adding weight decay to the Conv2D layers in the last convolutional block" }, { "code": null, "e": 12270, "s": 12126, "text": "For each set of experiments, we applied the l2 regularizer to weights and bias with the same rate, and we tested rates: [0.01, 0.05, 0.1, 0.2]." }, { "code": null, "e": 12491, "s": 12270, "text": "Other than these experiments, we also performed a grid search with learning rates [0.0008, 0.001, 0.002] and decay rates [5e-5 ,1e-4, 5e-4, 1e-3]. We applied weight decay on all Conv2D layers for either task 1 or task 2." }, { "code": null, "e": 12720, "s": 12491, "text": "Accuracy 1 all seem valid with these settings. However, the resultant forgetting did not show consistent trends between different data splits, and thus we could not reach a conclusion on the effect of weight decay on forgetting." }, { "code": null, "e": 12837, "s": 12720, "text": "From our four sets of experiments, we find some interesting results related to data augmentation and learning rates." }, { "code": null, "e": 13282, "s": 12837, "text": "Our next step would be to interpret these results. More specifically, for the data augmentation part, we want to know why random shifts and mixup have such relationships with forgetting. For learning rate, we would also like to explore why increasing task 1 learning rate mitigates forgetting. One hypothesis is that larger task 1 learning rate helps capture and generate better features, but we would need other control experiments to test it." }, { "code": null, "e": 13390, "s": 13282, "text": "[1] Kolouri, S., Ketz, N., Zou, X., Krichmar, J., & Pilly, P. (2019). Attention-based selective plasticity." }, { "code": null, "e": 13553, "s": 13390, "text": "[2] Ramasesh, V. V., Dyer, E., & Raghu, M. (2020). Anatomy of catastrophic forgetting: Hidden representations and task semantics. arXiv preprint arXiv:2007.07400." }, { "code": null, "e": 13713, "s": 13553, "text": "[3] Kemker, R., McClure, M., Abitino, A., Hayes, T., & Kanan, C. (2017). Measuring catastrophic forgetting in neural networks. arXiv preprint arXiv:1708.02072." }, { "code": null, "e": 13965, "s": 13713, "text": "[4] Arora, G., Rahimi, A., & Baldwin, T. (2019). Does an LSTM forget more than a CNN? An empirical study of catastrophic forgetting in NLP. In Proceedings of the The 17th Annual Workshop of the Australasian Language Technology Association (pp. 77–86)." }, { "code": null, "e": 14166, "s": 13965, "text": "[5] Goodfellow, I. J., Mirza, M., Xiao, D., Courville, A., & Bengio, Y. (2013). An empirical investigation of catastrophic forgetting in gradient-based neural networks. arXiv preprint arXiv:1312.6211." } ]
Add a horizontal rule in HTML
The HTML <hr> tag is the horizontal rule tag, used for creating a horizontal line. The HTML <hr> tag supports following additional attributes − You can try to run the following code to add a horizontal rule in HTML − <!DOCTYPE html> <html> <head> <title>HTML hr Tag</title> </head> <body> <p>This text will be followed by a horizontal line</p> <hr /> <p>Another horizontal line</p> <hr /> </body> </html>
[ { "code": null, "e": 1206, "s": 1062, "text": "The HTML <hr> tag is the horizontal rule tag, used for creating a horizontal line. The HTML <hr> tag supports following additional attributes −" }, { "code": null, "e": 1279, "s": 1206, "text": "You can try to run the following code to add a horizontal rule in HTML −" }, { "code": null, "e": 1509, "s": 1279, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML hr Tag</title>\n </head>\n <body>\n <p>This text will be followed by a horizontal line</p>\n <hr />\n <p>Another horizontal line</p>\n <hr />\n </body>\n</html>" } ]
C# Program to Create a Thread Pool
For a thread pool, create more than two functions and queue methods for execution. Firstly, create a method like − public void one(object o) { for (int i = 0; i <= 3; i++) { Console.WriteLine("One executed"); } } In the same way, create more methods and then use ThreadPool.QueueUserWorkItem to queue the methods for execution − Demo d = new Demo(); for (int i = 0; i < 3; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(d.one)); ThreadPool.QueueUserWorkItem(new WaitCallback(d.two)); ThreadPool.QueueUserWorkItem(new WaitCallback(d.three)); } You can try to run the following C# code to create a Thread Pool. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; class Demo { public void one(object o) { for (int i = 0; i <= 3; i++) { Console.WriteLine("One executed"); } } public void two(object o) { for (int i = 0; i <= 3; i++) { Console.WriteLine("Two executed"); } } public void three(object o) { for (int i = 0; i <= 3; i++) { Console.WriteLine("Three executed"); } } static void Main() { Demo d = new Demo(); for (int i = 0; i < 3; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(d.one)); ThreadPool.QueueUserWorkItem(new WaitCallback(d.two)); ThreadPool.QueueUserWorkItem(new WaitCallback(d.three)); } Console.Read(); } } Two executed Two executed Two executed Two executed Two executed Two executed Two executed One executed One executed One executed One executed One executed Two executed Two executed Three executed Three executed Two executed One executed Three executed Two executed Three executed One executed One executed One executed
[ { "code": null, "e": 1145, "s": 1062, "text": "For a thread pool, create more than two functions and queue methods for execution." }, { "code": null, "e": 1177, "s": 1145, "text": "Firstly, create a method like −" }, { "code": null, "e": 1287, "s": 1177, "text": "public void one(object o) {\n for (int i = 0; i <= 3; i++) {\n Console.WriteLine(\"One executed\");\n }\n}" }, { "code": null, "e": 1403, "s": 1287, "text": "In the same way, create more methods and then use ThreadPool.QueueUserWorkItem to queue the methods for execution −" }, { "code": null, "e": 1632, "s": 1403, "text": "Demo d = new Demo();\nfor (int i = 0; i < 3; i++) {\n ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));\n ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));\n ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));\n}" }, { "code": null, "e": 1698, "s": 1632, "text": "You can try to run the following C# code to create a Thread Pool." }, { "code": null, "e": 1708, "s": 1698, "text": "Live Demo" }, { "code": null, "e": 2528, "s": 1708, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nclass Demo {\n public void one(object o) {\n for (int i = 0; i <= 3; i++) {\n Console.WriteLine(\"One executed\");\n }\n }\n public void two(object o) {\n for (int i = 0; i <= 3; i++) {\n Console.WriteLine(\"Two executed\");\n }\n }\n public void three(object o) {\n for (int i = 0; i <= 3; i++) {\n Console.WriteLine(\"Three executed\");\n }\n }\n static void Main() {\n Demo d = new Demo();\n for (int i = 0; i < 3; i++) {\n ThreadPool.QueueUserWorkItem(new WaitCallback(d.one));\n ThreadPool.QueueUserWorkItem(new WaitCallback(d.two));\n ThreadPool.QueueUserWorkItem(new WaitCallback(d.three));\n }\n Console.Read();\n }\n}" }, { "code": null, "e": 2848, "s": 2528, "text": "Two executed\nTwo executed\nTwo executed\nTwo executed\nTwo executed\nTwo executed\nTwo executed\nOne executed\nOne executed\nOne executed\nOne executed\nOne executed\nTwo executed\nTwo executed\nThree executed\nThree executed\nTwo executed\nOne executed\nThree executed\nTwo executed\nThree executed\nOne executed\nOne executed\nOne executed" } ]
AWS - SAM Serverless Function Example - 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 Here we will see how to define the sam serverless function in AWS sam or cloud formation template. Make sure you have already installed SAM. A simple serverless function goes like the following. Resources: ServerlessFucntion: Type: AWS::Serverless::Function Properties: FunctionName: sample-serverless-example Description: "A simple serverless example in SAM" CodeUri: .serverless_example Handler: src.lambda_handler The above AWS::Serverless::Function resource creates a serverless function. Here the CodeUri is a location where the function code resides. Handler is the actual function with the code that triggers when the lambda is being accessed. Events are used to trigger the lambda. If we attach an event to the lambda whenever the event gets triggered the will be executed. For example, if I would like to attach a cloud watch schedule that triggers the lambda every 60 secs. Resources: ServerlessFucntion: Type: AWS::Serverless::Function Properties: FunctionName: sample-serverless-example Description: "A simple serverless example in SAM" CodeUri: .serverless_example Handler: src.lambda_handler Events: ScheduleEvent: Type: Schedule Properties: Schedule: rate(60 minutes) Name: "sample-scheduler" Description: "event to trigger lambda for every 60 minutes" Enabled: false An AWS lambda supports the following events to be attached. S3 SNS Kinesis DynamoDB SQS Api Schedule CloudWatchEvent EventBridgeRule CloudWatchLogs IoTRule AlexaSkill Cognito HttpApi MSK MQ Every event has its own defined set of properties and it needs to be configured as per the requirement. We can attach one or more policies to a lambda function. For example, if I want to attach DynamoDBFullAccess and APIGatewayInvokeFullAccess that goes the following. Resources: ServerlessFucntion: Type: AWS::Serverless::Function Properties: FunctionName: sample-serverless-example Description: "A simple serverless example in SAM" CodeUri: .serverless_example Handler: src.lambda_handler Events: ScheduleEvent: Type: Schedule Properties: Schedule: rate(60 minutes) Name: "sample-scheduler" Description: "event to trigger lambda for every 60 minutes" Enabled: false Policies: - AmazonSSMFullAccess - AmazonAPIGatewayInvokeFullAccess increasing the memory, set timeout and environment properties can be considered as common properties that we can set as Globals in the template. The Globals can be applied to all the functions within the template. Globals: Function: Timeout: 600 Runtime: python3.8 Environment: Variables: STAGE: DEV If you would like to bound these properties to a specific function that has to be defined within the function definition itself under the Properties section like the following. Resources: ServerlessFucntion: Type: AWS::Serverless::Function Properties: FunctionName: sample-serverless-example Description: "A simple serverless example in SAM" CodeUri: .serverless_example Handler: src.lambda_handler Runtime: python3.8 Timeout: 600 Environment: Variables: STAGE: DEV Complete yaml file. AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Globals: Function: Timeout: 600 Runtime: python3.8 Environment: Variables: STAGE: DEV Resources: ServerlessFucntion: Type: AWS::Serverless::Function Properties: FunctionName: sample-serverless-example Description: "A simple serverless example in SAM" CodeUri: .serverless_example Handler: src.lambda_handler Events: ScheduleEvent: Type: Schedule Properties: Schedule: rate(60 minutes) Name: "sample-scheduler" Description: "event to trigger lambda for every 60 minutes" Enabled: false Policies: - AmazonSSMFullAccess - AmazonAPIGatewayInvokeFullAccess AWS serverless function AWS SAM Lambda example Install AWS CLI on windows Happy Learning 🙂 Python – AWS SAM Lambda Example [Fixed] – Error: No changes to deploy. Stack is up to date [Fixed] – Malformed Lambda proxy response – status 502 Javascript – How to listObjects from AWS S3 How to install AWS CLI on Windows 10 How to Copy Local Files to AWS EC2 instance Manually ? How set AWS Access Keys in Windows or Mac Environment Java AWS – How to read messages from SQS How to connect AWS EC2 Instance using PuTTY Java AWS – How to Create SQS Standard and FIFO Queues Java AWS – How to Send Messages to SQS Queues What are Python default function parameters ? How add files to S3 Bucket using Shell Script Different ways to use Lambdas in Python Python raw_input read input from keyboard Python – AWS SAM Lambda Example [Fixed] – Error: No changes to deploy. Stack is up to date [Fixed] – Malformed Lambda proxy response – status 502 Javascript – How to listObjects from AWS S3 How to install AWS CLI on Windows 10 How to Copy Local Files to AWS EC2 instance Manually ? How set AWS Access Keys in Windows or Mac Environment Java AWS – How to read messages from SQS How to connect AWS EC2 Instance using PuTTY Java AWS – How to Create SQS Standard and FIFO Queues Java AWS – How to Send Messages to SQS Queues What are Python default function parameters ? How add files to S3 Bucket using Shell Script Different ways to use Lambdas in Python Python raw_input read input from keyboard Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows
[ { "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": 497, "s": 398, "text": "Here we will see how to define the sam serverless function in AWS sam or cloud formation template." }, { "code": null, "e": 539, "s": 497, "text": "Make sure you have already installed SAM." }, { "code": null, "e": 593, "s": 539, "text": "A simple serverless function goes like the following." }, { "code": null, "e": 852, "s": 593, "text": "Resources: \n ServerlessFucntion:\n Type: AWS::Serverless::Function\n Properties:\n FunctionName: sample-serverless-example\n Description: \"A simple serverless example in SAM\"\n CodeUri: .serverless_example\n Handler: src.lambda_handler\n" }, { "code": null, "e": 928, "s": 852, "text": "The above AWS::Serverless::Function resource creates a serverless function." }, { "code": null, "e": 1086, "s": 928, "text": "Here the CodeUri is a location where the function code resides. Handler is the actual function with the code that triggers when the lambda is being accessed." }, { "code": null, "e": 1217, "s": 1086, "text": "Events are used to trigger the lambda. If we attach an event to the lambda whenever the event gets triggered the will be executed." }, { "code": null, "e": 1319, "s": 1217, "text": "For example, if I would like to attach a cloud watch schedule that triggers the lambda every 60 secs." }, { "code": null, "e": 1846, "s": 1319, "text": "Resources: \n ServerlessFucntion: \n Type: AWS::Serverless::Function \n Properties: \n FunctionName: sample-serverless-example \n Description: \"A simple serverless example in SAM\" \n CodeUri: .serverless_example \n Handler: src.lambda_handler\n Events:\n ScheduleEvent:\n Type: Schedule\n Properties:\n Schedule: rate(60 minutes)\n Name: \"sample-scheduler\"\n Description: \"event to trigger lambda for every 60 minutes\"\n Enabled: false" }, { "code": null, "e": 1906, "s": 1846, "text": "An AWS lambda supports the following events to be attached." }, { "code": null, "e": 1909, "s": 1906, "text": "S3" }, { "code": null, "e": 1913, "s": 1909, "text": "SNS" }, { "code": null, "e": 1921, "s": 1913, "text": "Kinesis" }, { "code": null, "e": 1930, "s": 1921, "text": "DynamoDB" }, { "code": null, "e": 1934, "s": 1930, "text": "SQS" }, { "code": null, "e": 1938, "s": 1934, "text": "Api" }, { "code": null, "e": 1947, "s": 1938, "text": "Schedule" }, { "code": null, "e": 1963, "s": 1947, "text": "CloudWatchEvent" }, { "code": null, "e": 1979, "s": 1963, "text": "EventBridgeRule" }, { "code": null, "e": 1994, "s": 1979, "text": "CloudWatchLogs" }, { "code": null, "e": 2002, "s": 1994, "text": "IoTRule" }, { "code": null, "e": 2013, "s": 2002, "text": "AlexaSkill" }, { "code": null, "e": 2021, "s": 2013, "text": "Cognito" }, { "code": null, "e": 2029, "s": 2021, "text": "HttpApi" }, { "code": null, "e": 2033, "s": 2029, "text": "MSK" }, { "code": null, "e": 2036, "s": 2033, "text": "MQ" }, { "code": null, "e": 2140, "s": 2036, "text": "Every event has its own defined set of properties and it needs to be configured as per the requirement." }, { "code": null, "e": 2305, "s": 2140, "text": "We can attach one or more policies to a lambda function. For example, if I want to attach DynamoDBFullAccess and APIGatewayInvokeFullAccess that goes the following." }, { "code": null, "e": 2922, "s": 2305, "text": "Resources: \n ServerlessFucntion: \n Type: AWS::Serverless::Function \n Properties: \n FunctionName: sample-serverless-example \n Description: \"A simple serverless example in SAM\" \n CodeUri: .serverless_example \n Handler: src.lambda_handler\n Events:\n ScheduleEvent:\n Type: Schedule\n Properties:\n Schedule: rate(60 minutes)\n Name: \"sample-scheduler\"\n Description: \"event to trigger lambda for every 60 minutes\"\n Enabled: false\n Policies:\n - AmazonSSMFullAccess\n - AmazonAPIGatewayInvokeFullAccess" }, { "code": null, "e": 3136, "s": 2922, "text": "increasing the memory, set timeout and environment properties can be considered as common properties that we can set as Globals in the template. The Globals can be applied to all the functions within the template." }, { "code": null, "e": 3250, "s": 3136, "text": "Globals:\n Function:\n Timeout: 600\n Runtime: python3.8\n Environment:\n Variables:\n STAGE: DEV" }, { "code": null, "e": 3427, "s": 3250, "text": "If you would like to bound these properties to a specific function that has to be defined within the function definition itself under the Properties section like the following." }, { "code": null, "e": 3805, "s": 3427, "text": "Resources: \n ServerlessFucntion: \n Type: AWS::Serverless::Function \n Properties: \n FunctionName: sample-serverless-example \n Description: \"A simple serverless example in SAM\" \n CodeUri: .serverless_example \n Handler: src.lambda_handler\n Runtime: python3.8\n Timeout: 600\n Environment:\n Variables:\n STAGE: DEV" }, { "code": null, "e": 3825, "s": 3805, "text": "Complete yaml file." }, { "code": null, "e": 4648, "s": 3825, "text": "AWSTemplateFormatVersion: \"2010-09-09\"\nTransform: AWS::Serverless-2016-10-31\n\n Globals:\n Function:\n Timeout: 600\n Runtime: python3.8\n Environment:\n Variables:\n STAGE: DEV\nResources: \n ServerlessFucntion: \n Type: AWS::Serverless::Function \n Properties: \n FunctionName: sample-serverless-example \n Description: \"A simple serverless example in SAM\" \n CodeUri: .serverless_example \n Handler: src.lambda_handler\n Events:\n ScheduleEvent:\n Type: Schedule\n Properties:\n Schedule: rate(60 minutes)\n Name: \"sample-scheduler\"\n Description: \"event to trigger lambda for every 60 minutes\"\n Enabled: false\n Policies:\n - AmazonSSMFullAccess\n - AmazonAPIGatewayInvokeFullAccess" }, { "code": null, "e": 4672, "s": 4648, "text": "AWS serverless function" }, { "code": null, "e": 4695, "s": 4672, "text": "AWS SAM Lambda example" }, { "code": null, "e": 4722, "s": 4695, "text": "Install AWS CLI on windows" }, { "code": null, "e": 4739, "s": 4722, "text": "Happy Learning 🙂" }, { "code": null, "e": 5437, "s": 4739, "text": "\nPython – AWS SAM Lambda Example\n[Fixed] – Error: No changes to deploy. Stack is up to date\n[Fixed] – Malformed Lambda proxy response – status 502\nJavascript – How to listObjects from AWS S3\nHow to install AWS CLI on Windows 10\nHow to Copy Local Files to AWS EC2 instance Manually ?\nHow set AWS Access Keys in Windows or Mac Environment\nJava AWS – How to read messages from SQS\nHow to connect AWS EC2 Instance using PuTTY\nJava AWS – How to Create SQS Standard and FIFO Queues\nJava AWS – How to Send Messages to SQS Queues\nWhat are Python default function parameters ?\nHow add files to S3 Bucket using Shell Script\nDifferent ways to use Lambdas in Python\nPython raw_input read input from keyboard\n" }, { "code": null, "e": 5469, "s": 5437, "text": "Python – AWS SAM Lambda Example" }, { "code": null, "e": 5528, "s": 5469, "text": "[Fixed] – Error: No changes to deploy. Stack is up to date" }, { "code": null, "e": 5584, "s": 5528, "text": "[Fixed] – Malformed Lambda proxy response – status 502" }, { "code": null, "e": 5628, "s": 5584, "text": "Javascript – How to listObjects from AWS S3" }, { "code": null, "e": 5665, "s": 5628, "text": "How to install AWS CLI on Windows 10" }, { "code": null, "e": 5720, "s": 5665, "text": "How to Copy Local Files to AWS EC2 instance Manually ?" }, { "code": null, "e": 5774, "s": 5720, "text": "How set AWS Access Keys in Windows or Mac Environment" }, { "code": null, "e": 5815, "s": 5774, "text": "Java AWS – How to read messages from SQS" }, { "code": null, "e": 5859, "s": 5815, "text": "How to connect AWS EC2 Instance using PuTTY" }, { "code": null, "e": 5913, "s": 5859, "text": "Java AWS – How to Create SQS Standard and FIFO Queues" }, { "code": null, "e": 5959, "s": 5913, "text": "Java AWS – How to Send Messages to SQS Queues" }, { "code": null, "e": 6005, "s": 5959, "text": "What are Python default function parameters ?" }, { "code": null, "e": 6051, "s": 6005, "text": "How add files to S3 Bucket using Shell Script" }, { "code": null, "e": 6091, "s": 6051, "text": "Different ways to use Lambdas in Python" }, { "code": null, "e": 6133, "s": 6091, "text": "Python raw_input read input from keyboard" }, { "code": null, "e": 6139, "s": 6137, "text": "Δ" }, { "code": null, "e": 6163, "s": 6139, "text": " Install Java on Mac OS" }, { "code": null, "e": 6191, "s": 6163, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 6220, "s": 6191, "text": " Install Minikube on Windows" }, { "code": null, "e": 6255, "s": 6220, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 6282, "s": 6255, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 6309, "s": 6282, "text": " Install Gradle on Windows" }, { "code": null, "e": 6338, "s": 6309, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 6364, "s": 6338, "text": " Install PuTTY on windows" }, { "code": null, "e": 6390, "s": 6364, "text": " Install Mysql on Windows" }, { "code": null, "e": 6426, "s": 6390, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 6460, "s": 6426, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 6486, "s": 6460, "text": " Install Maven on Windows" }, { "code": null, "e": 6511, "s": 6486, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 6545, "s": 6511, "text": " Install Maven on Windows Command" }, { "code": null, "e": 6580, "s": 6545, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 6604, "s": 6580, "text": " Install Ant on Windows" }, { "code": null, "e": 6633, "s": 6604, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 6665, "s": 6633, "text": " Install Apache Kafka on Ubuntu" } ]
Java Cryptography - KeyPairGenerator
Java provides the KeyPairGenerator class. This class is used to generate pairs of public and private keys. To generate keys using the KeyPairGenerator class, follow the steps given below. The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys. Create KeyPairGenerator object using the getInstance() method as shown below. //Creating KeyPair generator object KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA"); The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size. Initialize the KeyPairGenerator object created in the previous step using this method as shown below. //Initializing the KeyPairGenerator keyPairGen.initialize(2048); You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below. //Generate the pair of keys KeyPair pair = keyPairGen.generateKeyPair(); You can get the private key from the generated KeyPair object using the getPrivate() method as shown below. //Getting the private key from the key pair PrivateKey privKey = pair.getPrivate(); You can get the public key from the generated KeyPair object using the getPublic() method as shown below. //Getting the public key from the key pair PublicKey publicKey = pair.getPublic(); Following example demonstrates the key generation of the secret key using the KeyPairGenerator class of the javax.crypto package. import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; public class KeyPairGenertor { public static void main(String args[]) throws Exception{ //Creating KeyPair generator object KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA"); //Initializing the KeyPairGenerator keyPairGen.initialize(2048); //Generating the pair of keys KeyPair pair = keyPairGen.generateKeyPair(); //Getting the private key from the key pair PrivateKey privKey = pair.getPrivate(); //Getting the public key from the key pair PublicKey publicKey = pair.getPublic(); System.out.println("Keys generated"); } } The above program generates the following output − Keys generated 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2241, "s": 2053, "text": "Java provides the KeyPairGenerator class. This class is used to generate pairs of public and private keys. To generate keys using the KeyPairGenerator class, follow the steps given below." }, { "code": null, "e": 2440, "s": 2241, "text": "The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys." }, { "code": null, "e": 2518, "s": 2440, "text": "Create KeyPairGenerator object using the getInstance() method as shown below." }, { "code": null, "e": 2622, "s": 2518, "text": "//Creating KeyPair generator object\nKeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"DSA\");\n" }, { "code": null, "e": 2808, "s": 2622, "text": "The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size." }, { "code": null, "e": 2910, "s": 2808, "text": "Initialize the KeyPairGenerator object created in the previous step using this method as shown below." }, { "code": null, "e": 2976, "s": 2910, "text": "//Initializing the KeyPairGenerator\nkeyPairGen.initialize(2048);\n" }, { "code": null, "e": 3127, "s": 2976, "text": "You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below." }, { "code": null, "e": 3201, "s": 3127, "text": "//Generate the pair of keys\nKeyPair pair = keyPairGen.generateKeyPair();\n" }, { "code": null, "e": 3309, "s": 3201, "text": "You can get the private key from the generated KeyPair object using the getPrivate() method as shown below." }, { "code": null, "e": 3394, "s": 3309, "text": "//Getting the private key from the key pair\nPrivateKey privKey = pair.getPrivate();\n" }, { "code": null, "e": 3500, "s": 3394, "text": "You can get the public key from the generated KeyPair object using the getPublic() method as shown below." }, { "code": null, "e": 3584, "s": 3500, "text": "//Getting the public key from the key pair\nPublicKey publicKey = pair.getPublic();\n" }, { "code": null, "e": 3714, "s": 3584, "text": "Following example demonstrates the key generation of the secret key using the KeyPairGenerator class of the javax.crypto package." }, { "code": null, "e": 4493, "s": 3714, "text": "import java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\n\npublic class KeyPairGenertor {\n public static void main(String args[]) throws Exception{\n //Creating KeyPair generator object\n KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"DSA\");\n \n //Initializing the KeyPairGenerator\n keyPairGen.initialize(2048);\n \n //Generating the pair of keys\n KeyPair pair = keyPairGen.generateKeyPair();\n \n //Getting the private key from the key pair\n PrivateKey privKey = pair.getPrivate(); \n \n //Getting the public key from the key pair\n PublicKey publicKey = pair.getPublic(); \n System.out.println(\"Keys generated\");\n }\n}" }, { "code": null, "e": 4544, "s": 4493, "text": "The above program generates the following output −" }, { "code": null, "e": 4560, "s": 4544, "text": "Keys generated\n" }, { "code": null, "e": 4593, "s": 4560, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4609, "s": 4593, "text": " Malhar Lathkar" }, { "code": null, "e": 4642, "s": 4609, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4658, "s": 4642, "text": " Malhar Lathkar" }, { "code": null, "e": 4693, "s": 4658, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4707, "s": 4693, "text": " Anadi Sharma" }, { "code": null, "e": 4741, "s": 4707, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4755, "s": 4741, "text": " Tushar Kale" }, { "code": null, "e": 4792, "s": 4755, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4807, "s": 4792, "text": " Monica Mittal" }, { "code": null, "e": 4840, "s": 4807, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4859, "s": 4840, "text": " Arnab Chakraborty" }, { "code": null, "e": 4866, "s": 4859, "text": " Print" }, { "code": null, "e": 4877, "s": 4866, "text": " Add Notes" } ]
Apex - SOQL For Loop
This type of for loop is used when we do not want to create the List and directly iterate over the returned set of records of the SOQL query. We will study more about the SOQL query in subsequent chapters. For now, just remember that it returns the list of records and field as given in the query. for (variable : [soql_query]) { code_block } or for (variable_list : [soql_query]) { code_block } One thing to note here is that the variable_list or variable should always be of the same type as the records returned by the Query. In our example, it is of the same type as APEX_Invoice_c. Consider the following for loop example using SOQL for loop. // The same previous example using For SOQL Loop List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>(); // initializing the custom object records list to store // the Invoice Records List<string> InvoiceNumberList = new List<string>(); // List to store the Invoice Number of Paid invoices for (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE CreatedDate = today]) { // this loop will iterate and will process the each record returned by the Query if (objInvoice.APEX_Status__c == 'Paid') { // Condition to check the current record in context values System.debug('Value of Current Record on which Loop is iterating is '+objInvoice); //current record on which loop is iterating InvoiceNumberList.add(objInvoice.Name); // if Status value is paid then it will the invoice number into List of String } } System.debug('Value of InvoiceNumberList with Invoice Name:'+InvoiceNumberList); 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": 2350, "s": 2052, "text": "This type of for loop is used when we do not want to create the List and directly iterate over the returned set of records of the SOQL query. We will study more about the SOQL query in subsequent chapters. For now, just remember that it returns the list of records and field as given in the query." }, { "code": null, "e": 2396, "s": 2350, "text": "for (variable : [soql_query]) { code_block }\n" }, { "code": null, "e": 2399, "s": 2396, "text": "or" }, { "code": null, "e": 2450, "s": 2399, "text": "for (variable_list : [soql_query]) { code_block }\n" }, { "code": null, "e": 2641, "s": 2450, "text": "One thing to note here is that the variable_list or variable should always be of the same type as the records returned by the Query. In our example, it is of the same type as APEX_Invoice_c." }, { "code": null, "e": 2702, "s": 2641, "text": "Consider the following for loop example using SOQL for loop." }, { "code": null, "e": 3732, "s": 2702, "text": "// The same previous example using For SOQL Loop\nList<apex_invoice__c> PaidInvoiceNumberList = new\nList<apex_invoice__c>(); // initializing the custom object records list to store\n // the Invoice Records\nList<string> InvoiceNumberList = new List<string>();\n\n// List to store the Invoice Number of Paid invoices\nfor (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM\n APEX_Invoice__c WHERE CreatedDate = today]) {\n \n // this loop will iterate and will process the each record returned by the Query\n if (objInvoice.APEX_Status__c == 'Paid') {\n \n // Condition to check the current record in context values\n System.debug('Value of Current Record on which Loop is iterating is '+objInvoice);\n \n //current record on which loop is iterating\n InvoiceNumberList.add(objInvoice.Name);\n // if Status value is paid then it will the invoice number into List of String\n }\n}\n\nSystem.debug('Value of InvoiceNumberList with Invoice Name:'+InvoiceNumberList);" }, { "code": null, "e": 3765, "s": 3732, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 3778, "s": 3765, "text": " Vijay Thapa" }, { "code": null, "e": 3810, "s": 3778, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 3818, "s": 3810, "text": " Uplatz" }, { "code": null, "e": 3851, "s": 3818, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 3876, "s": 3851, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 3909, "s": 3876, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 3924, "s": 3909, "text": " Ali Saleh Ali" }, { "code": null, "e": 3957, "s": 3924, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 3970, "s": 3957, "text": " Soham Ghosh" }, { "code": null, "e": 4005, "s": 3970, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4017, "s": 4005, "text": " GUHARAJANM" }, { "code": null, "e": 4024, "s": 4017, "text": " Print" }, { "code": null, "e": 4035, "s": 4024, "text": " Add Notes" } ]
Read all Files in Directory using R
06 Jun, 2021 To list all files in a directory in R programming language we use list.files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories. If no files are present in the directory, it returns “”. If a path does not exist it is skipped and a warning is shown. Note: File naming conventions depend on the platform. Syntax: list.files(path, pattern, all.files, full.names) Parameter: Path: It is a character vector that contains pathname to directories. Pattern: It is an optional regular expression. If this argument is provided then the function only returns the files that have given pattern in their name. all.files: It is a logical value. FALSE: Only the names of visible files are returned. TRUE: All file names will be returned irrespective of whether they are visible or hidden. full.names: It is a logical value. TRUE: The filename also contains the full path to the directory. FALSE: The filename doesn’t contain the path to the directory. Directory in use: Directory used Example 1: R list.files(path=".", pattern=NULL, all.files=FALSE, full.names=FALSE) Output: Output It is also possible to produce only some specific files for that the extension of those files is passed as the value to parameter pattern. Example 2: R list.files(path=".", pattern=".pdf", all.files=TRUE, full.names=TRUE) Output: Output Picked R-FileHandling 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 Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? Logistic Regression in R Programming R - if statement Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jun, 2021" }, { "code": null, "e": 433, "s": 54, "text": "To list all files in a directory in R programming language we use list.files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories. If no files are present in the directory, it returns “”. If a path does not exist it is skipped and a warning is shown. " }, { "code": null, "e": 487, "s": 433, "text": "Note: File naming conventions depend on the platform." }, { "code": null, "e": 495, "s": 487, "text": "Syntax:" }, { "code": null, "e": 544, "s": 495, "text": "list.files(path, pattern, all.files, full.names)" }, { "code": null, "e": 555, "s": 544, "text": "Parameter:" }, { "code": null, "e": 626, "s": 555, "text": "Path: It is a character vector that contains pathname to directories." }, { "code": null, "e": 783, "s": 626, "text": "Pattern: It is an optional regular expression. If this argument is provided then the function only returns the files that have given pattern in their name." }, { "code": null, "e": 818, "s": 783, "text": "all.files: It is a logical value. " }, { "code": null, "e": 871, "s": 818, "text": "FALSE: Only the names of visible files are returned." }, { "code": null, "e": 962, "s": 871, "text": "TRUE: All file names will be returned irrespective of whether they are visible or hidden." }, { "code": null, "e": 998, "s": 962, "text": "full.names: It is a logical value." }, { "code": null, "e": 1063, "s": 998, "text": "TRUE: The filename also contains the full path to the directory." }, { "code": null, "e": 1126, "s": 1063, "text": "FALSE: The filename doesn’t contain the path to the directory." }, { "code": null, "e": 1144, "s": 1126, "text": "Directory in use:" }, { "code": null, "e": 1159, "s": 1144, "text": "Directory used" }, { "code": null, "e": 1170, "s": 1159, "text": "Example 1:" }, { "code": null, "e": 1172, "s": 1170, "text": "R" }, { "code": "list.files(path=\".\", pattern=NULL, all.files=FALSE, full.names=FALSE)", "e": 1245, "s": 1172, "text": null }, { "code": null, "e": 1253, "s": 1245, "text": "Output:" }, { "code": null, "e": 1260, "s": 1253, "text": "Output" }, { "code": null, "e": 1399, "s": 1260, "text": "It is also possible to produce only some specific files for that the extension of those files is passed as the value to parameter pattern." }, { "code": null, "e": 1410, "s": 1399, "text": "Example 2:" }, { "code": null, "e": 1412, "s": 1410, "text": "R" }, { "code": "list.files(path=\".\", pattern=\".pdf\", all.files=TRUE, full.names=TRUE)", "e": 1485, "s": 1412, "text": null }, { "code": null, "e": 1493, "s": 1485, "text": "Output:" }, { "code": null, "e": 1500, "s": 1493, "text": "Output" }, { "code": null, "e": 1507, "s": 1500, "text": "Picked" }, { "code": null, "e": 1522, "s": 1507, "text": "R-FileHandling" }, { "code": null, "e": 1533, "s": 1522, "text": "R Language" }, { "code": null, "e": 1631, "s": 1533, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1683, "s": 1631, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1741, "s": 1683, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1776, "s": 1741, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1814, "s": 1776, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1863, "s": 1814, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1900, "s": 1863, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 1917, "s": 1900, "text": "R - if statement" }, { "code": null, "e": 1960, "s": 1917, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1997, "s": 1960, "text": "How to import an Excel File into R ?" } ]
ROT13 cipher
27 Jan, 2022 ROT13 cipher(read as – “rotate by 13 places”) is a special case of the Ceaser cipher in which the shift is always 13. So every letter is shifted 13 places to encrypt or to decrypt the message. I You must think that it is just another caesar cipher so what’s different this time? Well the difference is in its implementation. The approach is to use two separate python dictionaries. First one to lookup the various letters according to their place in the English alphabets to get the shifted numberSecond one to get the letters which correspond to those shifted numbers. First one to lookup the various letters according to their place in the English alphabets to get the shifted number Second one to get the letters which correspond to those shifted numbers. Code : Python3 C++ # Python program to implement# ROT13 Caesar cipher '''This script uses dictionaries instead of 'chr()' & 'ord()' function''' # Dictionary to lookup the index of alphabetsdict1 = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4, 'E' : 5, 'F' : 6, 'G' : 7, 'H' : 8, 'I' : 9, 'J' : 10, 'K' : 11, 'L' : 12, 'M' : 13, 'N' : 14, 'O' : 15, 'P' : 16, 'Q' : 17, 'R' : 18, 'S' : 19, 'T' : 20, 'U' : 21, 'V' : 22, 'W' : 23, 'X' : 24, 'Y' : 25, 'Z' : 26} # Dictionary to lookup alphabets# corresponding to the index after shiftdict2 = {0 : 'Z', 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'D', 5 : 'E', 6 : 'F', 7 : 'G', 8 : 'H', 9 : 'I', 10 : 'J', 11 : 'K', 12 : 'L', 13 : 'M', 14 : 'N', 15 : 'O', 16 : 'P', 17 : 'Q', 18 : 'R', 19 : 'S', 20 : 'T', 21 : 'U', 22 : 'V', 23 : 'W', 24 : 'X', 25 : 'Y'} # Function to encrypt the string# according to the shift provideddef encrypt(message, shift): cipher = '' for letter in message: # checking for space if(letter != ' '): # looks up the dictionary and # adds the shift to the index num = ( dict1[letter] + shift ) % 26 # looks up the second dictionary for # the shifted alphabets and adds them cipher += dict2[num] else: # adds space cipher += ' ' return cipher # Function to decrypt the string# according to the shift provideddef decrypt(message, shift): decipher = '' for letter in message: # checks for space if(letter != ' '): # looks up the dictionary and # subtracts the shift to the index num = ( dict1[letter] - shift + 26) % 26 # looks up the second dictionary for the # shifted alphabets and adds them decipher += dict2[num] else: # adds space decipher += ' ' return decipher # driver function to run the programdef main(): # use 'upper()' function to convert any lowercase characters to uppercase message = "GEEKS FOR GEEKS" shift = 13 result = encrypt(message.upper(), shift) print (result) message = "TRRXF SBE TRRXF" shift = 13 result = decrypt(message.upper(), shift) print (result) # Executes the main functionif __name__ == '__main__': main() // CPP program to implement// ROT13 Caesar Cipher #include<bits/stdc++.h>using namespace std; // Map to lookup the index of alphabetsmap <char,int> dict1; // Map to lookup alphabets corresponding// to the index after shiftmap <int,char> dict2; // Function to create map to lookupvoid create_dict(){ for(int i = 1; i < 27; i++) dict1[char(64 + i)] = i; dict2[0] = 'Z'; for(int i = 1; i < 26; i++) dict2[i] = char(64 + i); return;} // Function to encrypt the string// according to the shift providedstring encrypt(string message, int shift){ string cipher = ""; for(int i = 0; i < message.size(); i++) { // Checking for namespace if(message[i] != ' ') { // looks up the map and // adds the shift to the index int num = (dict1[message[i]] + shift) % 26; // looks up the second map for the // shifted alphabets and adds them cipher += dict2[num]; } else { // adds space cipher += " "; } } return cipher;} // Function to decrypt the string// according to the shift providedstring decrypt(string message, int shift){ string decipher = ""; for(int i = 0; i < message.size(); i++) { // checks for space if(message[i] != ' ') { // looks up the map and // subtracts the shift to the index int num = (dict1[message[i]] - shift + 26) % 26; // looks up the second map for the // shifted alphabets and adds them decipher += dict2[num]; } else { // adds space decipher += " "; } } return decipher;} // Driver codeint main(){ create_dict(); string message = "GEEKS FOR GEEKS"; int shift = 13; cout << encrypt(message, shift) << "\n"; message = "TRRXF SBE TRRXF"; shift = 13; cout << decrypt(message, shift) << "\n"; return 0;}// This code is contributed by Sachin Bisht Output : TRRXF SBE TRRXF GEEKS FOR GEEKS Analysis: The ROT13 cipher is not very secure as it is just a special case of the Caesar cipher. The Caesar cipher can be broken by either frequency analysis or by just trying out all 25 keys whereas the ROT13 cipher can be broken by just shifting the letters 13 places. Therefore it has no practical use.Application: ROT13 was in use in the net.jokes newsgroup by the early 1980s. This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai surinderdawra388 simmytarika5 amartyaghoshgfg cryptography Strings Strings cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Remove first and last character of a string in Java Find the smallest window in a string containing all characters of another string Program to count occurrence of a given character in a string Return maximum occurring character in an input string
[ { "code": null, "e": 53, "s": 25, "text": "\n27 Jan, 2022" }, { "code": null, "e": 247, "s": 53, "text": "ROT13 cipher(read as – “rotate by 13 places”) is a special case of the Ceaser cipher in which the shift is always 13. So every letter is shifted 13 places to encrypt or to decrypt the message. " }, { "code": null, "e": 438, "s": 247, "text": "I You must think that it is just another caesar cipher so what’s different this time? Well the difference is in its implementation. The approach is to use two separate python dictionaries. " }, { "code": null, "e": 626, "s": 438, "text": "First one to lookup the various letters according to their place in the English alphabets to get the shifted numberSecond one to get the letters which correspond to those shifted numbers." }, { "code": null, "e": 742, "s": 626, "text": "First one to lookup the various letters according to their place in the English alphabets to get the shifted number" }, { "code": null, "e": 815, "s": 742, "text": "Second one to get the letters which correspond to those shifted numbers." }, { "code": null, "e": 825, "s": 817, "text": "Code : " }, { "code": null, "e": 833, "s": 825, "text": "Python3" }, { "code": null, "e": 837, "s": 833, "text": "C++" }, { "code": "# Python program to implement# ROT13 Caesar cipher '''This script uses dictionaries instead of 'chr()' & 'ord()' function''' # Dictionary to lookup the index of alphabetsdict1 = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4, 'E' : 5, 'F' : 6, 'G' : 7, 'H' : 8, 'I' : 9, 'J' : 10, 'K' : 11, 'L' : 12, 'M' : 13, 'N' : 14, 'O' : 15, 'P' : 16, 'Q' : 17, 'R' : 18, 'S' : 19, 'T' : 20, 'U' : 21, 'V' : 22, 'W' : 23, 'X' : 24, 'Y' : 25, 'Z' : 26} # Dictionary to lookup alphabets# corresponding to the index after shiftdict2 = {0 : 'Z', 1 : 'A', 2 : 'B', 3 : 'C', 4 : 'D', 5 : 'E', 6 : 'F', 7 : 'G', 8 : 'H', 9 : 'I', 10 : 'J', 11 : 'K', 12 : 'L', 13 : 'M', 14 : 'N', 15 : 'O', 16 : 'P', 17 : 'Q', 18 : 'R', 19 : 'S', 20 : 'T', 21 : 'U', 22 : 'V', 23 : 'W', 24 : 'X', 25 : 'Y'} # Function to encrypt the string# according to the shift provideddef encrypt(message, shift): cipher = '' for letter in message: # checking for space if(letter != ' '): # looks up the dictionary and # adds the shift to the index num = ( dict1[letter] + shift ) % 26 # looks up the second dictionary for # the shifted alphabets and adds them cipher += dict2[num] else: # adds space cipher += ' ' return cipher # Function to decrypt the string# according to the shift provideddef decrypt(message, shift): decipher = '' for letter in message: # checks for space if(letter != ' '): # looks up the dictionary and # subtracts the shift to the index num = ( dict1[letter] - shift + 26) % 26 # looks up the second dictionary for the # shifted alphabets and adds them decipher += dict2[num] else: # adds space decipher += ' ' return decipher # driver function to run the programdef main(): # use 'upper()' function to convert any lowercase characters to uppercase message = \"GEEKS FOR GEEKS\" shift = 13 result = encrypt(message.upper(), shift) print (result) message = \"TRRXF SBE TRRXF\" shift = 13 result = decrypt(message.upper(), shift) print (result) # Executes the main functionif __name__ == '__main__': main()", "e": 3130, "s": 837, "text": null }, { "code": "// CPP program to implement// ROT13 Caesar Cipher #include<bits/stdc++.h>using namespace std; // Map to lookup the index of alphabetsmap <char,int> dict1; // Map to lookup alphabets corresponding// to the index after shiftmap <int,char> dict2; // Function to create map to lookupvoid create_dict(){ for(int i = 1; i < 27; i++) dict1[char(64 + i)] = i; dict2[0] = 'Z'; for(int i = 1; i < 26; i++) dict2[i] = char(64 + i); return;} // Function to encrypt the string// according to the shift providedstring encrypt(string message, int shift){ string cipher = \"\"; for(int i = 0; i < message.size(); i++) { // Checking for namespace if(message[i] != ' ') { // looks up the map and // adds the shift to the index int num = (dict1[message[i]] + shift) % 26; // looks up the second map for the // shifted alphabets and adds them cipher += dict2[num]; } else { // adds space cipher += \" \"; } } return cipher;} // Function to decrypt the string// according to the shift providedstring decrypt(string message, int shift){ string decipher = \"\"; for(int i = 0; i < message.size(); i++) { // checks for space if(message[i] != ' ') { // looks up the map and // subtracts the shift to the index int num = (dict1[message[i]] - shift + 26) % 26; // looks up the second map for the // shifted alphabets and adds them decipher += dict2[num]; } else { // adds space decipher += \" \"; } } return decipher;} // Driver codeint main(){ create_dict(); string message = \"GEEKS FOR GEEKS\"; int shift = 13; cout << encrypt(message, shift) << \"\\n\"; message = \"TRRXF SBE TRRXF\"; shift = 13; cout << decrypt(message, shift) << \"\\n\"; return 0;}// This code is contributed by Sachin Bisht", "e": 5194, "s": 3130, "text": null }, { "code": null, "e": 5235, "s": 5194, "text": "Output :\nTRRXF SBE TRRXF\nGEEKS FOR GEEKS" }, { "code": null, "e": 6043, "s": 5235, "text": "Analysis: The ROT13 cipher is not very secure as it is just a special case of the Caesar cipher. The Caesar cipher can be broken by either frequency analysis or by just trying out all 25 keys whereas the ROT13 cipher can be broken by just shifting the letters 13 places. Therefore it has no practical use.Application: ROT13 was in use in the net.jokes newsgroup by the early 1980s. This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6056, "s": 6043, "text": "Akanksha_Rai" }, { "code": null, "e": 6073, "s": 6056, "text": "surinderdawra388" }, { "code": null, "e": 6086, "s": 6073, "text": "simmytarika5" }, { "code": null, "e": 6102, "s": 6086, "text": "amartyaghoshgfg" }, { "code": null, "e": 6115, "s": 6102, "text": "cryptography" }, { "code": null, "e": 6123, "s": 6115, "text": "Strings" }, { "code": null, "e": 6131, "s": 6123, "text": "Strings" }, { "code": null, "e": 6144, "s": 6131, "text": "cryptography" }, { "code": null, "e": 6242, "s": 6144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6287, "s": 6242, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 6351, "s": 6287, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6396, "s": 6351, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 6431, "s": 6396, "text": "Print all subsequences of a string" }, { "code": null, "e": 6496, "s": 6431, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 6525, "s": 6496, "text": "String class in Java | Set 1" }, { "code": null, "e": 6577, "s": 6525, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 6658, "s": 6577, "text": "Find the smallest window in a string containing all characters of another string" }, { "code": null, "e": 6719, "s": 6658, "text": "Program to count occurrence of a given character in a string" } ]
vector::front() and vector::back() in C++ STL
23 Jun, 2022 Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. This function can be used to fetch the first element of a vector container.Syntax : vectorname.front() Parameters : No value is needed to pass as the parameter. Returns : Direct reference to the first element of the vector container. Examples: Input : myvector = 1, 2, 3 myvector.front(); Output : 1 Input : myvector = 3, 4, 1, 7, 3 myvector.front(); Output : 3 Errors and Exceptions1. If the vector container is empty, it causes undefined behavior. 2. It has a no exception throw guarantee if the vector is not empty. Time Complexity – Constant O(1) CPP // CPP program to illustrate// Implementation of front() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(3); // Vector becomes 3, 4, 1, 7, 3 cout << myvector.front(); return 0;} Output: 3 This function can be used to fetch the last element of a vector container.Syntax : vectorname.back() Parameters : No value is needed to pass as the parameter. Returns : Direct reference to the last element of the vector container. Examples: Input : myvector = 1, 2, 3 myvector.back(); Output : 3 Input : myvector = 3, 4, 1, 7, 2 myvector.back(); Output : 2 Errors and Exceptions1. If the vector container is empty, it causes undefined behavior. 2. It has a no exception throw guarantee if the vector is not empty. Time Complexity – Constant O(1) CPP // CPP program to illustrate// Implementation of back() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(2); // Vector becomes 3, 4, 1, 7, 2 cout << myvector.back(); return 0;} Output: 2 Difference between front(), back() and begin, end() function begin() and end() function return an iterator(like a pointer) initialized to the first or the last element of the container that can be used to iterate through the collection, while front() and back() function just return a reference to the first or the last element of the container.Application : Given an empty vector of integers, add numbers to the vector, then print the difference between the first and the last element. Input : 1, 2, 3, 4, 5, 6, 7, 8 Output : 7 Explanation - Last element = 8, First element = 1, Difference = 7 Algorithm 1. Add numbers to the vector using push_back() function 2. Compare the first and the last element. 3. If first element is larger, subtract last element from it and print it. 4. Else subtract first element from the last element and print it. CPP // CPP program to illustrate// application Of front() and back() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(8); myvector.push_back(7); myvector.push_back(6); myvector.push_back(5); myvector.push_back(4); myvector.push_back(3); myvector.push_back(2); myvector.push_back(1); // Vector becomes 8, 7, 6, 5, 4, 3, 2, 1 if (myvector.front() > myvector.back()) { cout << myvector.front() - myvector.back(); } else if (myvector.front() < myvector.back()) { cout << myvector.back() - myvector.front(); } else cout << "0";} Output: 7 Let us see the differences in a tabular form -: Its syntax is -: reference front(); Its syntax is -: reference back(); as5853535 shailendramaheshwari17 utkarshgupta110092 mayank007rawa CPP-Library cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) unordered_map in C++ STL vector erase() and clear() in C++ C++ Classes and Objects Substring in C++ Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ Virtual Function in C++ C++ Data Types Templates in C++ with Examples
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 242, "s": 53, "text": "Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. " }, { "code": null, "e": 328, "s": 242, "text": "This function can be used to fetch the first element of a vector container.Syntax : " }, { "code": null, "e": 478, "s": 328, "text": "vectorname.front()\nParameters :\nNo value is needed to pass as the parameter.\nReturns :\nDirect reference to the first element of the vector container." }, { "code": null, "e": 489, "s": 478, "text": "Examples: " }, { "code": null, "e": 634, "s": 489, "text": "Input : myvector = 1, 2, 3\n myvector.front();\nOutput : 1\n\nInput : myvector = 3, 4, 1, 7, 3\n myvector.front();\nOutput : 3" }, { "code": null, "e": 791, "s": 634, "text": "Errors and Exceptions1. If the vector container is empty, it causes undefined behavior. 2. It has a no exception throw guarantee if the vector is not empty." }, { "code": null, "e": 823, "s": 791, "text": "Time Complexity – Constant O(1)" }, { "code": null, "e": 827, "s": 823, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of front() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(3); // Vector becomes 3, 4, 1, 7, 3 cout << myvector.front(); return 0;}", "e": 1195, "s": 827, "text": null }, { "code": null, "e": 1204, "s": 1195, "text": "Output: " }, { "code": null, "e": 1206, "s": 1204, "text": "3" }, { "code": null, "e": 1290, "s": 1206, "text": "This function can be used to fetch the last element of a vector container.Syntax : " }, { "code": null, "e": 1438, "s": 1290, "text": "vectorname.back()\nParameters :\nNo value is needed to pass as the parameter.\nReturns :\nDirect reference to the last element of the vector container." }, { "code": null, "e": 1449, "s": 1438, "text": "Examples: " }, { "code": null, "e": 1592, "s": 1449, "text": "Input : myvector = 1, 2, 3\n myvector.back();\nOutput : 3\n\nInput : myvector = 3, 4, 1, 7, 2\n myvector.back();\nOutput : 2" }, { "code": null, "e": 1749, "s": 1592, "text": "Errors and Exceptions1. If the vector container is empty, it causes undefined behavior. 2. It has a no exception throw guarantee if the vector is not empty." }, { "code": null, "e": 1782, "s": 1749, "text": "Time Complexity – Constant O(1) " }, { "code": null, "e": 1786, "s": 1782, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of back() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(2); // Vector becomes 3, 4, 1, 7, 2 cout << myvector.back(); return 0;}", "e": 2152, "s": 1786, "text": null }, { "code": null, "e": 2162, "s": 2152, "text": "Output: " }, { "code": null, "e": 2164, "s": 2162, "text": "2" }, { "code": null, "e": 2225, "s": 2164, "text": "Difference between front(), back() and begin, end() function" }, { "code": null, "e": 2652, "s": 2225, "text": "begin() and end() function return an iterator(like a pointer) initialized to the first or the last element of the container that can be used to iterate through the collection, while front() and back() function just return a reference to the first or the last element of the container.Application : Given an empty vector of integers, add numbers to the vector, then print the difference between the first and the last element. " }, { "code": null, "e": 2761, "s": 2652, "text": "Input : 1, 2, 3, 4, 5, 6, 7, 8\nOutput : 7\nExplanation - Last element = 8, First element = 1, Difference = 7" }, { "code": null, "e": 3013, "s": 2761, "text": "Algorithm 1. Add numbers to the vector using push_back() function 2. Compare the first and the last element. 3. If first element is larger, subtract last element from it and print it. 4. Else subtract first element from the last element and print it. " }, { "code": null, "e": 3017, "s": 3013, "text": "CPP" }, { "code": "// CPP program to illustrate// application Of front() and back() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(8); myvector.push_back(7); myvector.push_back(6); myvector.push_back(5); myvector.push_back(4); myvector.push_back(3); myvector.push_back(2); myvector.push_back(1); // Vector becomes 8, 7, 6, 5, 4, 3, 2, 1 if (myvector.front() > myvector.back()) { cout << myvector.front() - myvector.back(); } else if (myvector.front() < myvector.back()) { cout << myvector.back() - myvector.front(); } else cout << \"0\";}", "e": 3674, "s": 3017, "text": null }, { "code": null, "e": 3683, "s": 3674, "text": "Output: " }, { "code": null, "e": 3685, "s": 3683, "text": "7" }, { "code": null, "e": 3733, "s": 3685, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 3750, "s": 3733, "text": "Its syntax is -:" }, { "code": null, "e": 3769, "s": 3750, "text": "reference front();" }, { "code": null, "e": 3786, "s": 3769, "text": "Its syntax is -:" }, { "code": null, "e": 3804, "s": 3786, "text": "reference back();" }, { "code": null, "e": 3816, "s": 3806, "text": "as5853535" }, { "code": null, "e": 3839, "s": 3816, "text": "shailendramaheshwari17" }, { "code": null, "e": 3858, "s": 3839, "text": "utkarshgupta110092" }, { "code": null, "e": 3872, "s": 3858, "text": "mayank007rawa" }, { "code": null, "e": 3884, "s": 3872, "text": "CPP-Library" }, { "code": null, "e": 3895, "s": 3884, "text": "cpp-vector" }, { "code": null, "e": 3899, "s": 3895, "text": "STL" }, { "code": null, "e": 3903, "s": 3899, "text": "C++" }, { "code": null, "e": 3907, "s": 3903, "text": "STL" }, { "code": null, "e": 3911, "s": 3907, "text": "CPP" }, { "code": null, "e": 4009, "s": 3911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4052, "s": 4009, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4077, "s": 4052, "text": "unordered_map in C++ STL" }, { "code": null, "e": 4111, "s": 4077, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 4135, "s": 4111, "text": "C++ Classes and Objects" }, { "code": null, "e": 4152, "s": 4135, "text": "Substring in C++" }, { "code": null, "e": 4206, "s": 4152, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4230, "s": 4206, "text": "Sorting a vector in C++" }, { "code": null, "e": 4254, "s": 4230, "text": "Virtual Function in C++" }, { "code": null, "e": 4269, "s": 4254, "text": "C++ Data Types" } ]
How to rename multiple columns in PySpark dataframe ?
04 Jul, 2021 In this article, we are going to see how to rename multiple columns in PySpark Dataframe. Before starting let’s create a dataframe using pyspark: Python3 # importing moduleimport pysparkfrom pyspark.sql.functions import col # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [["1", "sravan", "vignan"], ["2", "ojaswi", "vvit"], ["3", "rohith", "vvit"], ["4", "sridevi", "vignan"], ["1", "sravan", "vignan"], ["5", "gnanesh", "iit"]] # specify column namescolumns = ['student ID', 'student NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print("Actual data in dataframe") # show dataframedataframe.show() Output: Method 1: Using withColumnRenamed. Here we will use withColumnRenamed() to rename the existing columns name. Syntax: withColumnRenamed( Existing_col, New_col) Parameters: Existing_col: Old column name. New_col: New column name. Example 1: Renaming single columns. Python3 dataframe.withColumnRenamed("college", "College Name").show() Output: Example 2: Renaming multiple columns. Python3 df2 = dataframe.withColumnRenamed("student ID", "Id").withColumnRenamed("college", "College_Name")df2.show() Output: Method 2: Using toDF() This function returns a new DataFrame that with new specified column names. Syntax: toDF(*col) Where, col is a new column name In this example, we will create an order list of new column names and pass it into toDF function. Python3 Data_list = ["College Id"," Name"," College"]new_df = dataframe.toDF(*Data_list)new_df.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2021" }, { "code": null, "e": 118, "s": 28, "text": "In this article, we are going to see how to rename multiple columns in PySpark Dataframe." }, { "code": null, "e": 174, "s": 118, "text": "Before starting let’s create a dataframe using pyspark:" }, { "code": null, "e": 182, "s": 174, "text": "Python3" }, { "code": "# importing moduleimport pysparkfrom pyspark.sql.functions import col # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students datadata = [[\"1\", \"sravan\", \"vignan\"], [\"2\", \"ojaswi\", \"vvit\"], [\"3\", \"rohith\", \"vvit\"], [\"4\", \"sridevi\", \"vignan\"], [\"1\", \"sravan\", \"vignan\"], [\"5\", \"gnanesh\", \"iit\"]] # specify column namescolumns = ['student ID', 'student NAME', 'college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) print(\"Actual data in dataframe\") # show dataframedataframe.show()", "e": 912, "s": 182, "text": null }, { "code": null, "e": 920, "s": 912, "text": "Output:" }, { "code": null, "e": 955, "s": 920, "text": "Method 1: Using withColumnRenamed." }, { "code": null, "e": 1029, "s": 955, "text": "Here we will use withColumnRenamed() to rename the existing columns name." }, { "code": null, "e": 1079, "s": 1029, "text": "Syntax: withColumnRenamed( Existing_col, New_col)" }, { "code": null, "e": 1091, "s": 1079, "text": "Parameters:" }, { "code": null, "e": 1122, "s": 1091, "text": "Existing_col: Old column name." }, { "code": null, "e": 1148, "s": 1122, "text": "New_col: New column name." }, { "code": null, "e": 1184, "s": 1148, "text": "Example 1: Renaming single columns." }, { "code": null, "e": 1192, "s": 1184, "text": "Python3" }, { "code": "dataframe.withColumnRenamed(\"college\", \"College Name\").show()", "e": 1282, "s": 1192, "text": null }, { "code": null, "e": 1290, "s": 1282, "text": "Output:" }, { "code": null, "e": 1328, "s": 1290, "text": "Example 2: Renaming multiple columns." }, { "code": null, "e": 1336, "s": 1328, "text": "Python3" }, { "code": "df2 = dataframe.withColumnRenamed(\"student ID\", \"Id\").withColumnRenamed(\"college\", \"College_Name\")df2.show()", "e": 1535, "s": 1336, "text": null }, { "code": null, "e": 1543, "s": 1535, "text": "Output:" }, { "code": null, "e": 1566, "s": 1543, "text": "Method 2: Using toDF()" }, { "code": null, "e": 1642, "s": 1566, "text": "This function returns a new DataFrame that with new specified column names." }, { "code": null, "e": 1661, "s": 1642, "text": "Syntax: toDF(*col)" }, { "code": null, "e": 1693, "s": 1661, "text": "Where, col is a new column name" }, { "code": null, "e": 1791, "s": 1693, "text": "In this example, we will create an order list of new column names and pass it into toDF function." }, { "code": null, "e": 1799, "s": 1791, "text": "Python3" }, { "code": "Data_list = [\"College Id\",\" Name\",\" College\"]new_df = dataframe.toDF(*Data_list)new_df.show()", "e": 1893, "s": 1799, "text": null }, { "code": null, "e": 1901, "s": 1893, "text": "Output:" }, { "code": null, "e": 1908, "s": 1901, "text": "Picked" }, { "code": null, "e": 1923, "s": 1908, "text": "Python-Pyspark" }, { "code": null, "e": 1930, "s": 1923, "text": "Python" }, { "code": null, "e": 2028, "s": 1930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2060, "s": 2028, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2087, "s": 2060, "text": "Python Classes and Objects" }, { "code": null, "e": 2108, "s": 2087, "text": "Python OOPs Concepts" }, { "code": null, "e": 2131, "s": 2108, "text": "Introduction To PYTHON" }, { "code": null, "e": 2187, "s": 2131, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2218, "s": 2187, "text": "Python | os.path.join() method" }, { "code": null, "e": 2260, "s": 2218, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2302, "s": 2260, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2341, "s": 2302, "text": "Python | Get unique values from a list" } ]
Print prime numbers from 1 to N in reverse order
12 May, 2021 Given a number N, print all prime number smaller than or equal to N in reverse order . For example, if N is 9, the output should be “7, 5, 3, 2”. Examples: Input : N = 5 Output : 5 3 2 Input : N = 20 Output : 19 17 13 11 7 5 3 2 A simple solution is to traverse from N to 1. For every number, check if it is a prime using school method to check for prime. Print the number if it is prime.An efficient solution is to use Sieve of Eratosthenes. We efficiently find all number from 1 to N, then print them. C++ Java Python3 C# PHP Javascript // C++ program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenes#include <bits/stdc++.h>using namespace std; void Reverseorder(int n){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i // is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers in reverse order for (int p = n; p >= 2; p--) if (prime[p]) cout << p << " ";} // Driver Programint main(){ // static input int N = 25; // to display cout << "Prime number in reverse order" << endl; if (N == 1) cout << "No prime no exist in this range"; else Reverseorder(N); // calling the function return 0;} // Java program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenesimport java.io.*;import java.util.*; class GFG { static void reverseorder(int n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i // is Not a prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = n; i >= 2; i--) if (prime[i] == true) System.out.print(i + " "); } // Driver Program to test above function public static void main(String args[]) { // static input int N = 25; // To display System.out.println("Prime number in reverse order"); if (N == 1) System.out.println("No prime no exist in this range"); else reverseorder(N); // calling the function }} # Python3 program to print all primes# between 1 to N in reverse order# using Sieve of Eratosthenesdef Reverseorder(n): # Create a boolean array "prime[0..n]" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True] * (n + 1); p = 2; while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range((p * 2), (n + 1), p): prime[i] = False; p += 1; # Print all prime numbers in # reverse order for p in range(n, 1, -1): if (prime[p]): print(p, end = " "); # Driver Code # static inputN = 25; # to displayprint("Prime number in reverse order"); if (N == 1): print("No prime no exist in this range");else: Reverseorder(N); # calling the function # This code is contributed by mits // C# program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenesusing System; class GFG { static void reverseorder(int n) { // Create a boolean array "prime[0..n]" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. bool []prime = new bool[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = n; i >= 2; i--) if (prime[i] == true) Console.Write(i + " "); } // Driver code public static void Main() { // static input int N = 25; // To display Console.WriteLine("Prime number in" + " reverse order"); if (N == 1) Console.WriteLine("No prime no" + " exist in this range"); else // calling the function reverseorder(N); }} // This code is contributed by Sam007. <?php// PHP program to print all primes// between 1 to N in reverse order// using Sieve of Eratosthenes function Reverseorder($n){ // Create a boolean array "prime[0..n]" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Print all prime numbers in // reverse order for ($p = $n; $p >= 2; $p--) if ($prime[$p]) echo $p." ";} // Driver Code // static input$N = 25; // to displayecho "Prime number in reverse order\n"; if ($N == 1) echo "No prime no exist in this range";else Reverseorder($N); // calling the function // This code is contributed by mits?> <script> // Javascript program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenes function Reverseorder( n){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i // is Not a prime, else true. let prime = new Array(n + 1); for (let i = 0; i < n; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers in reverse order for (let p = n; p >= 2; p--) if (prime[p]) document.write(p + " ");} // Driver Code // static inputlet N = 25; // to displaydocument.write("Prime number in reverse order" + "</br>"); if (N == 1) document.write("No prime no exist in this range");else Reverseorder(N); // calling the function </script> Prime number in reverse order 23 19 17 13 11 7 5 3 2 Sam007 Mithun Kumar jana_sayantan Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Merge two sorted arrays with O(1) extra space Segment Tree | Set 1 (Sum of given range) Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Product of Array except itself Find Union and Intersection of two unsorted arrays Median of two sorted arrays of same size
[ { "code": null, "e": 52, "s": 24, "text": "\n12 May, 2021" }, { "code": null, "e": 210, "s": 52, "text": "Given a number N, print all prime number smaller than or equal to N in reverse order . For example, if N is 9, the output should be “7, 5, 3, 2”. Examples: " }, { "code": null, "e": 285, "s": 210, "text": "Input : N = 5\nOutput : 5 3 2\n\nInput : N = 20\nOutput : 19 17 13 11 7 5 3 2" }, { "code": null, "e": 563, "s": 287, "text": "A simple solution is to traverse from N to 1. For every number, check if it is a prime using school method to check for prime. Print the number if it is prime.An efficient solution is to use Sieve of Eratosthenes. We efficiently find all number from 1 to N, then print them. " }, { "code": null, "e": 567, "s": 563, "text": "C++" }, { "code": null, "e": 572, "s": 567, "text": "Java" }, { "code": null, "e": 580, "s": 572, "text": "Python3" }, { "code": null, "e": 583, "s": 580, "text": "C#" }, { "code": null, "e": 587, "s": 583, "text": "PHP" }, { "code": null, "e": 598, "s": 587, "text": "Javascript" }, { "code": "// C++ program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenes#include <bits/stdc++.h>using namespace std; void Reverseorder(int n){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i // is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers in reverse order for (int p = n; p >= 2; p--) if (prime[p]) cout << p << \" \";} // Driver Programint main(){ // static input int N = 25; // to display cout << \"Prime number in reverse order\" << endl; if (N == 1) cout << \"No prime no exist in this range\"; else Reverseorder(N); // calling the function return 0;}", "e": 1676, "s": 598, "text": null }, { "code": "// Java program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenesimport java.io.*;import java.util.*; class GFG { static void reverseorder(int n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i // is Not a prime, else true. boolean prime[] = new boolean[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = n; i >= 2; i--) if (prime[i] == true) System.out.print(i + \" \"); } // Driver Program to test above function public static void main(String args[]) { // static input int N = 25; // To display System.out.println(\"Prime number in reverse order\"); if (N == 1) System.out.println(\"No prime no exist in this range\"); else reverseorder(N); // calling the function }}", "e": 2994, "s": 1676, "text": null }, { "code": "# Python3 program to print all primes# between 1 to N in reverse order# using Sieve of Eratosthenesdef Reverseorder(n): # Create a boolean array \"prime[0..n]\" # and initialize all entries it as true. # A value in prime[i] will finally be # false if i is Not a prime, else true. prime = [True] * (n + 1); p = 2; while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range((p * 2), (n + 1), p): prime[i] = False; p += 1; # Print all prime numbers in # reverse order for p in range(n, 1, -1): if (prime[p]): print(p, end = \" \"); # Driver Code # static inputN = 25; # to displayprint(\"Prime number in reverse order\"); if (N == 1): print(\"No prime no exist in this range\");else: Reverseorder(N); # calling the function # This code is contributed by mits", "e": 3943, "s": 2994, "text": null }, { "code": "// C# program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenesusing System; class GFG { static void reverseorder(int n) { // Create a boolean array \"prime[0..n]\" // and initialize all entries it as // true. A value in prime[i] will // finally be false if i is Not a // prime, else true. bool []prime = new bool[n + 1]; for (int i = 0; i < n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int i = n; i >= 2; i--) if (prime[i] == true) Console.Write(i + \" \"); } // Driver code public static void Main() { // static input int N = 25; // To display Console.WriteLine(\"Prime number in\" + \" reverse order\"); if (N == 1) Console.WriteLine(\"No prime no\" + \" exist in this range\"); else // calling the function reverseorder(N); }} // This code is contributed by Sam007.", "e": 5370, "s": 3943, "text": null }, { "code": "<?php// PHP program to print all primes// between 1 to N in reverse order// using Sieve of Eratosthenes function Reverseorder($n){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as true. // A value in prime[i] will finally be // false if i is Not a prime, else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // Print all prime numbers in // reverse order for ($p = $n; $p >= 2; $p--) if ($prime[$p]) echo $p.\" \";} // Driver Code // static input$N = 25; // to displayecho \"Prime number in reverse order\\n\"; if ($N == 1) echo \"No prime no exist in this range\";else Reverseorder($N); // calling the function // This code is contributed by mits?>", "e": 6375, "s": 5370, "text": null }, { "code": "<script> // Javascript program to print all primes between 1// to N in reverse order using Sieve of// Eratosthenes function Reverseorder( n){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i // is Not a prime, else true. let prime = new Array(n + 1); for (let i = 0; i < n; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } // Print all prime numbers in reverse order for (let p = n; p >= 2; p--) if (prime[p]) document.write(p + \" \");} // Driver Code // static inputlet N = 25; // to displaydocument.write(\"Prime number in reverse order\" + \"</br>\"); if (N == 1) document.write(\"No prime no exist in this range\");else Reverseorder(N); // calling the function </script>", "e": 7438, "s": 6375, "text": null }, { "code": null, "e": 7491, "s": 7438, "text": "Prime number in reverse order\n23 19 17 13 11 7 5 3 2" }, { "code": null, "e": 7500, "s": 7493, "text": "Sam007" }, { "code": null, "e": 7513, "s": 7500, "text": "Mithun Kumar" }, { "code": null, "e": 7527, "s": 7513, "text": "jana_sayantan" }, { "code": null, "e": 7540, "s": 7527, "text": "Prime Number" }, { "code": null, "e": 7546, "s": 7540, "text": "sieve" }, { "code": null, "e": 7559, "s": 7546, "text": "Mathematical" }, { "code": null, "e": 7572, "s": 7559, "text": "Mathematical" }, { "code": null, "e": 7585, "s": 7572, "text": "Prime Number" }, { "code": null, "e": 7591, "s": 7585, "text": "sieve" }, { "code": null, "e": 7689, "s": 7591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7721, "s": 7689, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7765, "s": 7721, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 7811, "s": 7765, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 7853, "s": 7811, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 7878, "s": 7853, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 7910, "s": 7878, "text": "Check if a number is Palindrome" }, { "code": null, "e": 7945, "s": 7910, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 7976, "s": 7945, "text": "Product of Array except itself" }, { "code": null, "e": 8027, "s": 7976, "text": "Find Union and Intersection of two unsorted arrays" } ]
Java - exp() Method
The method returns the base of the natural logarithms, e, to the power of the argument. double exp(double d) Here is the detail of parameters − d − Any primitive data type. d − Any primitive data type. This method returns the base of the natural logarithms, e, to the power of the argument. This method returns the base of the natural logarithms, e, to the power of the argument. public class Test { public static void main(String args[]) { double x = 11.635; double y = 2.76; System.out.printf("The value of e is %.4f%n", Math.E); System.out.printf("exp(%.3f) is %.3f%n", x, Math.exp(x)); } } This will produce the following result − The value of e is 2.7183 exp(11.635) is 112983.831
[ { "code": null, "e": 2599, "s": 2511, "text": "The method returns the base of the natural logarithms, e, to the power of the argument." }, { "code": null, "e": 2621, "s": 2599, "text": "double exp(double d)\n" }, { "code": null, "e": 2656, "s": 2621, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2685, "s": 2656, "text": "d − Any primitive data type." }, { "code": null, "e": 2714, "s": 2685, "text": "d − Any primitive data type." }, { "code": null, "e": 2803, "s": 2714, "text": "This method returns the base of the natural logarithms, e, to the power of the argument." }, { "code": null, "e": 2892, "s": 2803, "text": "This method returns the base of the natural logarithms, e, to the power of the argument." }, { "code": null, "e": 3141, "s": 2892, "text": "public class Test { \n\n public static void main(String args[]) {\n double x = 11.635;\n double y = 2.76;\n\n System.out.printf(\"The value of e is %.4f%n\", Math.E);\n System.out.printf(\"exp(%.3f) is %.3f%n\", x, Math.exp(x)); \n }\n}" }, { "code": null, "e": 3182, "s": 3141, "text": "This will produce the following result −" } ]
MySQL - INSERT Statement
You can add new rows to an existing table of MySQL using the INSERT statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names). Following is the syntax of the INSERT statement of MySQL. INSERT INTO table_name (column1, column2, column3,...columnN) VALUES (value1, value2, value3,...valueN); Where, table_name is the name of the table into which you need to insert data, (column1, column2, column3,...columnN) are the names of the columns and (value1, value2, value3,...valueN) are the values in the record. Assume we have created a table with name Sales in MySQL database using CREATE TABLE statement as shown below mysql> CREATE TABLE sales( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255) ); Query OK, 0 rows affected (2.22 sec) Following query inserts a row in the above created table − insert into sales (ID, ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); If you pass the values to the INSERT statement in the same order as in the table you can omit the column names − insert into sales values(2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); Now, let us insert 3 more records in Sales table. insert into sales values(3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into sales values(4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into sales values(5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); If you verify the contents of the Sales table using the SELECT statement you can observe the inserted records as shown below − mysql> SELECT * FROM SALES; +------+-------------+--------------+--------------+--------------+-------+----------------+ | ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | +------+-------------+--------------+--------------+--------------+-------+----------------+ | 1 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | Hyderabad | | 2 | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | Vishakhapatnam | | 3 | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | Vijayawada | | 4 | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | Chennai | | 5 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | Goa | +------+-------------+--------------+--------------+--------------+-------+----------------+ 5 rows in set (0.00 sec) You can insert a record by setting values to selected columns using the INSERT...SET statement. Following is the syntax of this statement − INSERT INTO table_name SET column_name1 = value1, column_name2 = value2 ......; Where, table_name is the name of the table into which you need to insert the record and column_name1 = value1, column_name2 = value2 ...... are the selected column names and the respective values. If you insert record using this statement the values of other columns will be null. Following query inserts a record into the SALES table using the INSERT.... SET statement. Here, we are passing values only to the ProductName, CustomerName and Price columns (remaining values will be NULL) − mysql> INSERT INTO SALES SET ID = 6, ProductName = 'Speaker', CustomerName = 'Rahman', Price = 5500; Query OK, 1 row affected (0.13 sec) If you retrieve the contents of the SALES table using the SELECT statement you can observe the inserted row as shown below mysql> SELECT * FROM SALES; +------+-------------+--------------+--------------+--------------+-------+----------------+ | ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | +------+-------------+--------------+--------------+--------------+-------+----------------+ | 1 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | Hyderabad | | 2 | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | Vishakhapatnam | | 3 | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | Vijayawada | | 4 | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | Chennai | | 5 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | Goa | | 6 | Speaker | Rahman | NULL | NULL | 5500 | NULL | +------+-------------+--------------+--------------+--------------+-------+----------------+ 6 rows in set (0.24 sec) You can select desired column values from one table and insert them as a record into another table using the INSERT .... SELECT statement following is the syntax to do so − INSERT INTO table_to (column1, column2, ..........) SELECT Column1, column2 ........... FROM Table_from WHERE condition Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below − mysql> CREATE TABLE SALES_DETAILS ( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255), CustomerAge INT, CustomrtPhone BIGINT, DispatchAddress VARCHAR(255), Email VARCHAR(50) ); Now, let’s insert 2 records into the above created table using the INSERT statement as − mysql> insert into SALES_DETAILS values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', '[email protected]'); Query OK, 1 row affected (0.84 sec) mysql> insert into SALES_DETAILS values(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai', 30, '90000123654', 'Chennai- TNagar', '[email protected]'); Query OK, 1 row affected (1.84 sec) If we want another table with just the contact details of the customer create a table as − mysql> CREATE TABLE CustContactDetails ( ID INT, Name VARCHAR(255), Age INT, Phone BIGINT, Address VARCHAR(255), Email VARCHAR(50) ); Following query insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table − mysql> INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SALES_DETAILS WHERE ID = 1 AND CustomerName = 'Raja'; Query OK, 1 row affected (0.16 sec) Records: 1 Duplicates: 0 Warnings: 0 INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SALES_DETAILS WHERE ID = 2 AND CustomerName = 'Vanaja'; Query OK, 1 row affected (0.16 sec) You can verify the contents of the CustContactDetails table as shown below − mysql> SELECT * FROM CustContactDetails; +------+--------+------+-------------+----------------------+----------------------+ | ID | Name | Age | Phone | Address | Email | +------+--------+------+-------------+----------------------+----------------------+ | 1 | Raja | 25 | 9000012345 | Hyderabad – Madhapur | [email protected] | | 2 | Vanaja | 30 | 90000123654 | Chennai- TNagar | [email protected] | +------+--------+------+-------------+----------------------+----------------------+ 2 rows in set (0.00 sec) On the other hand, instead of selecting specific columns you can insert the contents of one table into another using the INSERT .... TABLE statement. Following is the syntax to do so − INSERT INTO table1 TABLE table2; Assume we have created a table with name student and inserted 4 records int it as shown below − mysql> Create table Student(Name Varchar(35), age INT, Score INT); Query OK, 0 rows affected (1.28 sec) mysql> INSERT INTO student values ('Jeevan', 22, 8); mysql> INSERT INTO student values ('Raghav', 26, –3); mysql> INSERT INTO student values ('Khaleel', 21, –9); mysql> INSERT INTO student values ('Deva', 30, 9); Suppose we have another table with name columns and types created as − mysql> Create table Data(Name Varchar(35), age INT, Score INT); Query OK, 0 rows affected (0.94 sec) Following query inserts the contents of the Student table into the table Data − mysql> INSERT INTO Data TABLE Student; Query OK, 4 rows affected (0.33 sec) Records: 4 Duplicates: 0 Warnings: 0 If you verify the contents of the Data table using the SELECT statement you can observe the inserted data as − mysql> SELECT * FROM data; +---------+------+-------+ | Name | age | Score | +---------+------+-------+ | Jeevan | 22 | 8 | | Raghav | 26 | –3 | | Khaleel | 21 | –9 | | Deva | 30 | 9 | +---------+------+-------+ 4 rows in set (0.00 sec) If one of the columns of a table is has a UNIQUE of PRIMARY KEY constraint and, If you use ON DUPLICATE KEY UPDATE clause along with the INSERT statement to insert a record in that particular table, if the value passed under the column with the either of the constrains is duplicate, instead of adding a new record the old record will be updated. Following is the syntax of the INSERT ... ON DUPLICATE KEY UPDATE Statement − INSERT INTO table_name (column1, column2, ......) VALUES (value1, value2, .....) ON DUPLICATE KEY UPDATE update_statement; Assume we have created a table name empData and declare the ID column as UNIQUE as − mysql> CREATE TABLE empData (ID INT UNIQUE, Name VARCHAR(15), email VARCHAR(15), salary INT); Query OK, 0 rows affected (2.09 sec) Following query inserts the records in the above table using the update clause − mysql> INSERT INTO empData VALUES (1, 'Raja', '[email protected]', 2215) ON DUPLICATE KEY UPDATE salary = salary+ salary; Query OK, 1 row affected (0.14 sec) After this insert contents of the empData table will be as shown below − mysql> SELECT * FROM empData; +------+------+----------------+--------+ | ID | Name | email | salary | +------+------+----------------+--------+ | 1 | Raja | [email protected] | 2215 | +------+------+----------------+--------+ 1 row in set (0.07 sec) If you execute the above statement again, since the record with ID value 1 already exists instead of inserting new record the salary value in the statement will be added to the existing salary − mysql> INSERT INTO empData VALUES (1, 'Raja', '[email protected]', 2215) ON DUPLICATE KEY UPDATE salary = salary+ salary; Query OK, 2 rows affected (0.16 sec) After this insert contents of the empData table will be as shown below − mysql> SELECT * FROM empData; +------+------+----------------+--------+ | ID | Name | email | salary | +------+------+----------------+--------+ | 1 | Raja | [email protected] | 4430 | +------+------+----------------+--------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 2634, "s": 2441, "text": "You can add new rows to an existing table of MySQL using the INSERT statement. In this, you need to specify the name of the table, column names, and values (in the same order as column names)." }, { "code": null, "e": 2692, "s": 2634, "text": "Following is the syntax of the INSERT statement of MySQL." }, { "code": null, "e": 2798, "s": 2692, "text": "INSERT INTO table_name (column1, column2, column3,...columnN)\nVALUES (value1, value2, value3,...valueN);\n" }, { "code": null, "e": 3014, "s": 2798, "text": "Where, table_name is the name of the table into which you need to insert data, (column1, column2, column3,...columnN) are the names of the columns and (value1, value2, value3,...valueN) are the values in the record." }, { "code": null, "e": 3123, "s": 3014, "text": "Assume we have created a table with name Sales in MySQL database using CREATE TABLE statement as shown below" }, { "code": null, "e": 3343, "s": 3123, "text": "mysql> CREATE TABLE sales(\n ID INT,\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255)\n);\nQuery OK, 0 rows affected (2.22 sec)" }, { "code": null, "e": 3402, "s": 3343, "text": "Following query inserts a row in the above created table −" }, { "code": null, "e": 3587, "s": 3402, "text": "insert into sales (ID, ProductName, CustomerName, DispatchDate, DeliveryTime, Price, Location) values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\n" }, { "code": null, "e": 3700, "s": 3587, "text": "If you pass the values to the INSERT statement in the same order as in the table you can omit the column names −" }, { "code": null, "e": 3813, "s": 3700, "text": "insert into sales values(2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\n" }, { "code": null, "e": 3863, "s": 3813, "text": "Now, let us insert 3 more records in Sales table." }, { "code": null, "e": 4172, "s": 3863, "text": "insert into sales values(3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into sales values(4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into sales values(5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 4299, "s": 4172, "text": "If you verify the contents of the Sales table using the SELECT statement you can observe the inserted records as shown below −" }, { "code": null, "e": 5189, "s": 4299, "text": "mysql> SELECT * FROM SALES;\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n| ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location |\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n| 1 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | Hyderabad |\n| 2 | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | Vishakhapatnam |\n| 3 | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | Vijayawada |\n| 4 | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | Chennai |\n| 5 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | Goa |\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 5329, "s": 5189, "text": "You can insert a record by setting values to selected columns using the INSERT...SET statement. Following is the syntax of this statement −" }, { "code": null, "e": 5410, "s": 5329, "text": "INSERT INTO table_name SET column_name1 = value1, column_name2 = value2 ......;\n" }, { "code": null, "e": 5607, "s": 5410, "text": "Where, table_name is the name of the table into which you need to insert the record and column_name1 = value1, column_name2 = value2 ...... are the selected column names and the respective values." }, { "code": null, "e": 5691, "s": 5607, "text": "If you insert record using this statement the values of other columns will be null." }, { "code": null, "e": 5899, "s": 5691, "text": "Following query inserts a record into the SALES table using the INSERT.... SET statement. Here, we are passing values only to the ProductName, CustomerName and Price columns (remaining values will be NULL) −" }, { "code": null, "e": 6036, "s": 5899, "text": "mysql> INSERT INTO\nSALES SET ID = 6,\nProductName = 'Speaker',\nCustomerName = 'Rahman',\nPrice = 5500;\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 6159, "s": 6036, "text": "If you retrieve the contents of the SALES table using the SELECT statement you can observe the inserted row as shown below" }, { "code": null, "e": 7142, "s": 6159, "text": "mysql> SELECT * FROM SALES;\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n| ID | ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location |\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n| 1 | Key-Board | Raja | 2019-09-01 | 11:00:00 | 7000 | Hyderabad |\n| 2 | Earphones | Roja | 2019-05-01 | 11:00:00 | 2000 | Vishakhapatnam |\n| 3 | Mouse | Puja | 2019-03-01 | 10:59:59 | 3000 | Vijayawada |\n| 4 | Mobile | Vanaja | 2019-03-01 | 10:10:52 | 9000 | Chennai |\n| 5 | Headset | Jalaja | 2019-04-06 | 11:08:59 | 6000 | Goa |\n| 6 | Speaker | Rahman | NULL | NULL | 5500 | NULL |\n+------+-------------+--------------+--------------+--------------+-------+----------------+\n6 rows in set (0.24 sec)" }, { "code": null, "e": 7315, "s": 7142, "text": "You can select desired column values from one table and insert them as a record into another table using the INSERT .... SELECT statement following is the syntax to do so −" }, { "code": null, "e": 7463, "s": 7315, "text": "INSERT INTO table_to (column1, column2, ..........)\n SELECT\n Column1, column2 ...........\n FROM\n Table_from\n WHERE\n condition\n" }, { "code": null, "e": 7592, "s": 7463, "text": "Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below −" }, { "code": null, "e": 7884, "s": 7592, "text": "mysql> CREATE TABLE SALES_DETAILS (\n ID INT,\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255),\n CustomerAge INT,\n CustomrtPhone BIGINT,\n DispatchAddress VARCHAR(255),\n Email VARCHAR(50)\n);" }, { "code": null, "e": 7973, "s": 7884, "text": "Now, let’s insert 2 records into the above created table using the INSERT statement as −" }, { "code": null, "e": 8416, "s": 7973, "text": "mysql> insert into SALES_DETAILS values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), \nTIME('11:00:00'), 7000, 'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', '[email protected]');\nQuery OK, 1 row affected (0.84 sec)\nmysql> insert into SALES_DETAILS values(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, \n'Chennai', 30, '90000123654', 'Chennai- TNagar', '[email protected]');\nQuery OK, 1 row affected (1.84 sec)" }, { "code": null, "e": 8507, "s": 8416, "text": "If we want another table with just the contact details of the customer create a table as −" }, { "code": null, "e": 8659, "s": 8507, "text": "mysql> CREATE TABLE CustContactDetails (\n ID INT,\n Name VARCHAR(255),\n Age INT,\n Phone BIGINT,\n Address VARCHAR(255),\n Email VARCHAR(50)\n);" }, { "code": null, "e": 8861, "s": 8659, "text": "Following query insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table −" }, { "code": null, "e": 9443, "s": 8861, "text": "mysql> INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)\n SELECT\n ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email\n FROM\n SALES_DETAILS\n WHERE\n ID = 1 AND CustomerName = 'Raja';\nQuery OK, 1 row affected (0.16 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\nINSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)\n SELECT\n ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email\n FROM\n SALES_DETAILS\n WHERE\n ID = 2 AND CustomerName = 'Vanaja';\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 9520, "s": 9443, "text": "You can verify the contents of the CustContactDetails table as shown below −" }, { "code": null, "e": 10096, "s": 9520, "text": "mysql> SELECT * FROM CustContactDetails;\n+------+--------+------+-------------+----------------------+----------------------+\n| ID | Name | Age | Phone | Address | Email |\n+------+--------+------+-------------+----------------------+----------------------+\n| 1 | Raja | 25 | 9000012345 | Hyderabad – Madhapur | [email protected] |\n| 2 | Vanaja | 30 | 90000123654 | Chennai- TNagar | [email protected] |\n+------+--------+------+-------------+----------------------+----------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 10281, "s": 10096, "text": "On the other hand, instead of selecting specific columns you can insert the contents of one table into another using the INSERT .... TABLE statement. Following is the syntax to do so −" }, { "code": null, "e": 10315, "s": 10281, "text": "INSERT INTO table1 TABLE table2;\n" }, { "code": null, "e": 10411, "s": 10315, "text": "Assume we have created a table with name student and inserted 4 records int it as shown below −" }, { "code": null, "e": 10728, "s": 10411, "text": "mysql> Create table Student(Name Varchar(35), age INT, Score INT);\nQuery OK, 0 rows affected (1.28 sec)\nmysql> INSERT INTO student values ('Jeevan', 22, 8);\nmysql> INSERT INTO student values ('Raghav', 26, –3);\nmysql> INSERT INTO student values ('Khaleel', 21, –9);\nmysql> INSERT INTO student values ('Deva', 30, 9);" }, { "code": null, "e": 10799, "s": 10728, "text": "Suppose we have another table with name columns and types created as −" }, { "code": null, "e": 10901, "s": 10799, "text": "mysql> Create table Data(Name Varchar(35), age INT, Score INT);\nQuery OK, 0 rows affected (0.94 sec)\n" }, { "code": null, "e": 10981, "s": 10901, "text": "Following query inserts the contents of the Student table into the table Data −" }, { "code": null, "e": 11095, "s": 10981, "text": "mysql> INSERT INTO Data TABLE Student;\nQuery OK, 4 rows affected (0.33 sec)\nRecords: 4 Duplicates: 0 Warnings: 0\n" }, { "code": null, "e": 11206, "s": 11095, "text": "If you verify the contents of the Data table using the SELECT statement you can observe the inserted data as −" }, { "code": null, "e": 11474, "s": 11206, "text": "mysql> SELECT * FROM data;\n+---------+------+-------+\n| Name | age | Score |\n+---------+------+-------+\n| Jeevan | 22 | 8 |\n| Raghav | 26 | –3 |\n| Khaleel | 21 | –9 |\n| Deva | 30 | 9 |\n+---------+------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 11821, "s": 11474, "text": "If one of the columns of a table is has a UNIQUE of PRIMARY KEY constraint and, If you use ON DUPLICATE KEY UPDATE clause along with the INSERT statement to insert a record in that particular table, if the value passed under the column with the either of the constrains is duplicate, instead of adding a new record the old record will be updated." }, { "code": null, "e": 11899, "s": 11821, "text": "Following is the syntax of the INSERT ... ON DUPLICATE KEY UPDATE Statement −" }, { "code": null, "e": 12023, "s": 11899, "text": "INSERT INTO table_name (column1, column2, ......) VALUES (value1, value2, .....) ON DUPLICATE KEY UPDATE update_statement;\n" }, { "code": null, "e": 12108, "s": 12023, "text": "Assume we have created a table name empData and declare the ID column as UNIQUE as −" }, { "code": null, "e": 12240, "s": 12108, "text": "mysql> CREATE TABLE empData (ID INT UNIQUE, Name VARCHAR(15), email VARCHAR(15), salary INT);\nQuery OK, 0 rows affected (2.09 sec)\n" }, { "code": null, "e": 12321, "s": 12240, "text": "Following query inserts the records in the above table using the update clause −" }, { "code": null, "e": 12477, "s": 12321, "text": "mysql> INSERT INTO empData VALUES (1, 'Raja', '[email protected]', 2215)\nON DUPLICATE KEY UPDATE salary = salary+ salary;\nQuery OK, 1 row affected (0.14 sec)\n" }, { "code": null, "e": 12550, "s": 12477, "text": "After this insert contents of the empData table will be as shown below −" }, { "code": null, "e": 12815, "s": 12550, "text": "mysql> SELECT * FROM empData;\n+------+------+----------------+--------+\n| ID | Name | email | salary |\n+------+------+----------------+--------+\n| 1 | Raja | [email protected] | 2215 |\n+------+------+----------------+--------+\n1 row in set (0.07 sec)\n" }, { "code": null, "e": 13010, "s": 12815, "text": "If you execute the above statement again, since the record with ID value 1 already exists instead of inserting new record the salary value in the statement will be added to the existing salary −" }, { "code": null, "e": 13167, "s": 13010, "text": "mysql> INSERT INTO empData VALUES (1, 'Raja', '[email protected]', 2215)\nON DUPLICATE KEY UPDATE salary = salary+ salary;\nQuery OK, 2 rows affected (0.16 sec)\n" }, { "code": null, "e": 13240, "s": 13167, "text": "After this insert contents of the empData table will be as shown below −" } ]
How to scroll down followers popup in Instagram ?
26 Mar, 2021 Here, in this article, we are going to discuss How to scroll down followers popup on Instagram Using Python. With the selenium, we will automate our browsers and performs automation on Instagram’s Social Website. Before going to practical implementation, we need to install the Selenium Library using the pip command. pip install Selenium Now, Let’s check whether our selenium is installed or not. If the below command did not give any error that means selenium is successfully installed. Python3 import seleniumprint(selenium.__version__) Output: 3.141.0 Now, Let’s discuss the approach to how we can perform scrolling down functionality. Using while loop, We will scroll down the followers pop-up window until our program reached till the last follower. First, we will automate the login process with our login id and password and then go to the GeeksforGeeks Instagram page. Click on the follower’s button and then perform the scrolling down operation on the popup window. First, we need to import the time module and all necessary classes or methods from the Selenium Library. Installing Chrome Web Driver through which we will perform all tasks on Chrome Web Browser. Same as Chrome, we can install any other browsers such as Edge, IE, Firefox, and many more. driver = webdriver.Chrome(ChromeDriverManager().install()) Using the above line, we do not require to have any physical driver present in our system. This line will automatically install the required chrome web driver using the web. Open the Website using the driver object and get() method with the given URL. driver.get("http://www.instagram.com") WebDriverWait is also called Explicit Wait. Explicit Wait is code which defines to wait for a certain condition to occur before proceeding further. in this code, With the help of CSS_SELECTOR, we will find the username and password fields for login purpose. username = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “input[name=’username’]”))) password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “input[name=’password’]”))) Now, before putting the username and password in the selected field, first, clear the username and password fields using the clear() method. Then, Put the username and password value using send_keys() method. username.clear() username.send_keys("<Enter_Your_Username") password.clear() password.send_keys("<Enter_Your_Password>") Click on the Login button using CSS_SELECTOR. button = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “button[type=’submit’]”))).click() We are done with Instagram Login. Now, We can open our target profile URL on which we will perform the scrolling. driver.get("https://www.instagram.com/geeks_for_geeks/followers/") Here, in this practical implementation, we are using geeksforgeeks followers pop up for scrolling. Click on followers button using find_element_by_partial_link_text method. Find the pop-up window element from a webpage using XPATH. On the pop-up window, we will use a while loop for performing the scrolling until the program gets reached to the last followers. That’s why we take our loop as TRUE always. Finally, Once we are done with our task. We will use the quit() method for closing the resources. Below is the full implementation: Python3 import timefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.support.wait import WebDriverWaitfrom webdriver_manager.chrome import ChromeDriverManagerfrom selenium.webdriver.support import expected_conditions as ECfrom webdriver_manager.microsoft import EdgeChromiumDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) # open the webpagedriver.get("http://www.instagram.com") # target usernameusername = WebDriverWait( driver, 10).until(EC.element_to_be_clickable( (By.CSS_SELECTOR, "input[name='username']"))) # target Passwordpassword = WebDriverWait( driver, 10).until(EC.element_to_be_clickable( (By.CSS_SELECTOR, "input[name='password']"))) # enter username and passwordusername.clear()username.send_keys("<Enter_Your_Username>")password.clear()password.send_keys("<Enter_Your_Password>") # target the login button and click itbutton = WebDriverWait( driver, 2).until(EC.element_to_be_clickable( (By.CSS_SELECTOR, "button[type='submit']"))).click() time.sleep(5) driver.get("https://www.instagram.com/geeks_for_geeks/followers/") driver.find_element_by_partial_link_text("follower").click() pop_up_window = WebDriverWait( driver, 2).until(EC.element_to_be_clickable( (By.XPATH, "//div[@class='isgrP']"))) # Scroll till Followers list is therewhile True: driver.execute_script( 'arguments[0].scrollTop = arguments[0].scrollTop + arguments[0].offsetHeight;', pop_up_window) time.sleep(1) driver.quit() Output: Picked Python Selenium-Exercises Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2021" }, { "code": null, "e": 346, "s": 28, "text": "Here, in this article, we are going to discuss How to scroll down followers popup on Instagram Using Python. With the selenium, we will automate our browsers and performs automation on Instagram’s Social Website. Before going to practical implementation, we need to install the Selenium Library using the pip command." }, { "code": null, "e": 367, "s": 346, "text": "pip install Selenium" }, { "code": null, "e": 517, "s": 367, "text": "Now, Let’s check whether our selenium is installed or not. If the below command did not give any error that means selenium is successfully installed." }, { "code": null, "e": 525, "s": 517, "text": "Python3" }, { "code": "import seleniumprint(selenium.__version__)", "e": 568, "s": 525, "text": null }, { "code": null, "e": 576, "s": 568, "text": "Output:" }, { "code": null, "e": 584, "s": 576, "text": "3.141.0" }, { "code": null, "e": 1005, "s": 584, "text": "Now, Let’s discuss the approach to how we can perform scrolling down functionality. Using while loop, We will scroll down the followers pop-up window until our program reached till the last follower. First, we will automate the login process with our login id and password and then go to the GeeksforGeeks Instagram page. Click on the follower’s button and then perform the scrolling down operation on the popup window. " }, { "code": null, "e": 1110, "s": 1005, "text": "First, we need to import the time module and all necessary classes or methods from the Selenium Library." }, { "code": null, "e": 1294, "s": 1110, "text": "Installing Chrome Web Driver through which we will perform all tasks on Chrome Web Browser. Same as Chrome, we can install any other browsers such as Edge, IE, Firefox, and many more." }, { "code": null, "e": 1353, "s": 1294, "text": "driver = webdriver.Chrome(ChromeDriverManager().install())" }, { "code": null, "e": 1527, "s": 1353, "text": "Using the above line, we do not require to have any physical driver present in our system. This line will automatically install the required chrome web driver using the web." }, { "code": null, "e": 1605, "s": 1527, "text": "Open the Website using the driver object and get() method with the given URL." }, { "code": null, "e": 1644, "s": 1605, "text": "driver.get(\"http://www.instagram.com\")" }, { "code": null, "e": 1902, "s": 1644, "text": "WebDriverWait is also called Explicit Wait. Explicit Wait is code which defines to wait for a certain condition to occur before proceeding further. in this code, With the help of CSS_SELECTOR, we will find the username and password fields for login purpose." }, { "code": null, "e": 2018, "s": 1902, "text": "username = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “input[name=’username’]”)))" }, { "code": null, "e": 2134, "s": 2018, "text": "password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “input[name=’password’]”)))" }, { "code": null, "e": 2343, "s": 2134, "text": "Now, before putting the username and password in the selected field, first, clear the username and password fields using the clear() method. Then, Put the username and password value using send_keys() method." }, { "code": null, "e": 2464, "s": 2343, "text": "username.clear()\nusername.send_keys(\"<Enter_Your_Username\")\npassword.clear()\npassword.send_keys(\"<Enter_Your_Password>\")" }, { "code": null, "e": 2510, "s": 2464, "text": "Click on the Login button using CSS_SELECTOR." }, { "code": null, "e": 2630, "s": 2510, "text": "button = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “button[type=’submit’]”))).click()" }, { "code": null, "e": 2744, "s": 2630, "text": "We are done with Instagram Login. Now, We can open our target profile URL on which we will perform the scrolling." }, { "code": null, "e": 2811, "s": 2744, "text": "driver.get(\"https://www.instagram.com/geeks_for_geeks/followers/\")" }, { "code": null, "e": 2910, "s": 2811, "text": "Here, in this practical implementation, we are using geeksforgeeks followers pop up for scrolling." }, { "code": null, "e": 2984, "s": 2910, "text": "Click on followers button using find_element_by_partial_link_text method." }, { "code": null, "e": 3217, "s": 2984, "text": "Find the pop-up window element from a webpage using XPATH. On the pop-up window, we will use a while loop for performing the scrolling until the program gets reached to the last followers. That’s why we take our loop as TRUE always." }, { "code": null, "e": 3315, "s": 3217, "text": "Finally, Once we are done with our task. We will use the quit() method for closing the resources." }, { "code": null, "e": 3349, "s": 3315, "text": "Below is the full implementation:" }, { "code": null, "e": 3357, "s": 3349, "text": "Python3" }, { "code": "import timefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.support.wait import WebDriverWaitfrom webdriver_manager.chrome import ChromeDriverManagerfrom selenium.webdriver.support import expected_conditions as ECfrom webdriver_manager.microsoft import EdgeChromiumDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) # open the webpagedriver.get(\"http://www.instagram.com\") # target usernameusername = WebDriverWait( driver, 10).until(EC.element_to_be_clickable( (By.CSS_SELECTOR, \"input[name='username']\"))) # target Passwordpassword = WebDriverWait( driver, 10).until(EC.element_to_be_clickable( (By.CSS_SELECTOR, \"input[name='password']\"))) # enter username and passwordusername.clear()username.send_keys(\"<Enter_Your_Username>\")password.clear()password.send_keys(\"<Enter_Your_Password>\") # target the login button and click itbutton = WebDriverWait( driver, 2).until(EC.element_to_be_clickable( (By.CSS_SELECTOR, \"button[type='submit']\"))).click() time.sleep(5) driver.get(\"https://www.instagram.com/geeks_for_geeks/followers/\") driver.find_element_by_partial_link_text(\"follower\").click() pop_up_window = WebDriverWait( driver, 2).until(EC.element_to_be_clickable( (By.XPATH, \"//div[@class='isgrP']\"))) # Scroll till Followers list is therewhile True: driver.execute_script( 'arguments[0].scrollTop = arguments[0].scrollTop + arguments[0].offsetHeight;', pop_up_window) time.sleep(1) driver.quit()", "e": 4947, "s": 3357, "text": null }, { "code": null, "e": 4955, "s": 4947, "text": "Output:" }, { "code": null, "e": 4962, "s": 4955, "text": "Picked" }, { "code": null, "e": 4988, "s": 4962, "text": "Python Selenium-Exercises" }, { "code": null, "e": 5004, "s": 4988, "text": "Python-selenium" }, { "code": null, "e": 5011, "s": 5004, "text": "Python" }, { "code": null, "e": 5109, "s": 5011, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5154, "s": 5109, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 5204, "s": 5154, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 5220, "s": 5204, "text": "Deque in Python" }, { "code": null, "e": 5236, "s": 5220, "text": "Queue in Python" }, { "code": null, "e": 5258, "s": 5236, "text": "Defaultdict in Python" }, { "code": null, "e": 5300, "s": 5258, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5327, "s": 5300, "text": "Python Classes and Objects" }, { "code": null, "e": 5350, "s": 5327, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 5369, "s": 5350, "text": "reduce() in Python" } ]
Word Ladder – Set 2 ( Bi-directional BFS )
01 Dec, 2021 Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the target word exists in the dictionary and the lengths of all the dictionary words are equal.Examples: Input: Dictionary = {POON, PLEE, SAME, POIE, PLEA, PLIE, POIN} start = “TOON” target = “PLEA” Output: 7 TOON -> POON –> POIN –> POIE –> PLIE –> PLEE –> PLEA Approach: This problem can be solved using the standard BFS approach as discussed here but its performance can be improved by using bi-directional BFS. Bi-directional BFS doesn’t reduce the time complexity of the solution but it definitely optimizes the performance in many cases. This approach can also be used in many other shortest pathfinding problems where we have sufficient information about the source and the target node. The basic idea involved in bi-directional BFS is to start the search from both the ends of the path. Therefore, two queues and two visited arrays are needed to be maintained to track both the paths. So, whenever a node (say A) is present in the source queue, encounters a node (say B) which is present in the target queue, then we can calculate the answer by adding the distance of A from source and the distance of B from target minus 1 (one node is common). This way we can calculate the answer in half the time as compared to the standard BFS approach. This method is also known as the meet-in-the-middle BFS approach.Below is the implementation of the above approach: C++ Java C# Python3 // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Structure for queuestruct node { string word; int len;}; // Function that returns true if a and b// differ in only a single characterbool isAdj(string a, string b){ int count = 0; for (int i = 0; i < a.length(); i++) { if (a[i] != b[i]) count++; } if (count == 1) return true; return false;} // Function to return the length of the shortest// chain from ‘beginWord’ to ‘endWord’int ladderLength(string beginWord, string endWord, vector<string>& wordList){ /* q1 is used to traverse the graph from beginWord and q2 is used to traverse the graph from endWord. vis1 and vis2 are used to keep track of the visited states from respective directions */ queue<node> q1; queue<node> q2; unordered_map<string, int> vis1; unordered_map<string, int> vis2; node start = { beginWord, 1 }; node end = { endWord, 1 }; vis1[beginWord] = 1; q1.push(start); vis2[endWord] = 1; q2.push(end); while (!q1.empty() && !q2.empty()) { // Fetch the current node // from the source queue node curr1 = q1.front(); q1.pop(); // Fetch the current node from // the destination queue node curr2 = q2.front(); q2.pop(); // Check all the neighbors of curr1 for (auto it = wordList.begin(); it != wordList.end(); it++) { // If any one of them is adjacent to curr1 // and is not present in vis1 // then push it in the queue if (isAdj(curr1.word, *it) && vis1.count(*it) == false) { node temp = { *it, curr1.len + 1 }; q1.push(temp); vis1[*it] = curr1.len + 1; // If temp is the destination node // then return the answer if (temp.word == endWord) { return temp.len; } // If temp is present in vis2 i.e. distance from // temp and the destination is already calculated if (vis2.count(temp.word)) { return temp.len + vis2[temp.word] - 1; } } } // Check all the neighbors of curr2 for (auto it = wordList.begin(); it != wordList.end(); it++) { // If any one of them is adjacent to curr2 // and is not present in vis1 then push it in the queue. if (isAdj(curr2.word, *it) && vis2.count(*it) == false) { node temp = { *it, curr2.len + 1 }; q2.push(temp); vis2[*it] = curr2.len + 1; // If temp is the destination node // then return the answer if (temp.word == beginWord) { return temp.len; } // If temp is present in vis1 i.e. distance from // temp and the source is already calculated if (vis1.count(temp.word)) { return temp.len + vis1[temp.word] - 1; } } } } return 0;} // Driver codeint main(){ vector<string> wordList; wordList.push_back("poon"); wordList.push_back("plee"); wordList.push_back("same"); wordList.push_back("poie"); wordList.push_back("plie"); wordList.push_back("poin"); wordList.push_back("plea"); string start = "toon"; string target = "plea"; cout << ladderLength(start, target, wordList); return 0;} import java.util.*;public class GFG{public static class node{ String word; int len; public node(String word, int len) { this.word = word; this.len = len; }} public static boolean isAdj(String a, String b){ int count = 0; for (int i = 0; i < a.length(); i++) { if (a.charAt(i) != b.charAt(i)) count++; } if (count == 1) return true; return false;} // Function to return the length of the shortest// chain from 'beginWord' to 'endWord'public static int ladderLength(String beginWord, String endWord, ArrayList<String> wordList){ /* q1 is used to traverse the graph from beginWord and q2 is used to traverse the graph from endWord. vis1 and vis2 are used to keep track of the visited states from respective directions */ Queue<node> q1 = new LinkedList<>(); Queue<node> q2 = new LinkedList<>(); HashMap<String, Integer> vis1 = new HashMap<>(); HashMap<String, Integer> vis2 = new HashMap<>(); node start = new node(beginWord, 1); node end = new node(endWord, 1); vis1.put(beginWord, 1); q1.add(start); vis2.put(endWord, 1); q2.add(end); while (q1.size() > 0 && q2.size() > 0) { // Fetch the current node // from the source queue node curr1 = q1.remove(); // Fetch the current node from // the destination queue node curr2 = q2.remove(); // Check all the neighbors of curr1 for (int i = 0; i < wordList.size(); i++) { // If any one of them is adjacent to curr1 // and is not present in vis1 // then push it in the queue if (isAdj(curr1.word,wordList.get(i)) && vis1.containsKey(wordList.get(i)) == false) { node temp = new node(wordList.get(i), curr1.len + 1); q1.add(temp); vis1.put(wordList.get(i), curr1.len + 1); // If temp is the destination node // then return the answer if (temp.word.equals(endWord)) { return temp.len; } // If temp is present in vis2 i.e. distance from // temp and the destination is already calculated if (vis2.containsKey(temp.word)) { return temp.len + vis2.get(temp.word) - 1; } } } // Check all the neighbors of curr2 for (int i = 0; i < wordList.size(); i++) { // If any one of them is adjacent to curr2 // and is not present in vis1 then push it in the queue. if (isAdj(curr2.word,wordList.get(i)) && vis2.containsKey(wordList.get(i)) == false) { node temp = new node(wordList.get(i), curr2.len + 1 ); q2.add(temp); vis2.put(wordList.get(i), curr2.len + 1); // If temp is the destination node // then return the answer if (temp.word.equals(beginWord)) { return temp.len; } // If temp is present in vis1 i.e. distance from // temp and the source is already calculated if (vis1.containsKey(temp.word)) { return temp.len + vis1.get(temp.word) - 1; } } } } return 0;} // Driver codepublic static void main(String args[]){ ArrayList<String> wordList = new ArrayList<>(); wordList.add("poon"); wordList.add("plee"); wordList.add("same"); wordList.add("poie"); wordList.add("plie"); wordList.add("poin"); wordList.add("plea"); String start = "toon"; String target = "plea"; System.out.println(ladderLength(start, target, wordList));}} // This code is contributed by Sambhav Jain // C# implementation of the approach using System;using System.Collections.Generic; class GFG{ class node{ public String word; public int len; public node(String word, int len) { this.word = word; this.len = len; }} public static bool isAdj(String a, String b){ int count = 0; for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) count++; } if (count == 1) return true; return false;} // Function to return the length of the shortest// chain from 'beginWord' to 'endWord'public static int ladderLength(String beginWord, String endWord, List<String> wordList){ /* q1 is used to traverse the graph from beginWord and q2 is used to traverse the graph from endWord. vis1 and vis2 are used to keep track of the visited states from respective directions */ Queue<node> q1 = new Queue<node>(); Queue<node> q2 = new Queue<node>(); Dictionary<String, int> vis1 = new Dictionary<String, int>(); Dictionary<String, int> vis2 = new Dictionary<String, int>(); node start = new node(beginWord, 1); node end = new node(endWord, 1); vis1.Add(beginWord, 1); q1.Enqueue(start); vis2.Add(endWord, 1); q2.Enqueue(end); while (q1.Count > 0 && q2.Count > 0) { // Fetch the current node // from the source queue node curr1 = q1.Dequeue(); // Fetch the current node from // the destination queue node curr2 = q2.Dequeue(); // Check all the neighbors of curr1 for (int i = 0; i < wordList.Count; i++) { // If any one of them is adjacent to curr1 // and is not present in vis1 // then push it in the queue if (isAdj(curr1.word,wordList[i]) && vis1.ContainsKey(wordList[i]) == false) { node temp = new node(wordList[i], curr1.len + 1); q1.Enqueue(temp); vis1.Add(wordList[i], curr1.len + 1); // If temp is the destination node // then return the answer if (temp.word.Equals(endWord)) { return temp.len; } // If temp is present in vis2 i.e. distance from // temp and the destination is already calculated if (vis2.ContainsKey(temp.word)) { return temp.len + vis2[temp.word] - 1; } } } // Check all the neighbors of curr2 for (int i = 0; i < wordList.Count; i++) { // If any one of them is adjacent to curr2 // and is not present in vis1 then push it in the queue. if (isAdj(curr2.word,wordList[i]) && vis2.ContainsKey(wordList[i]) == false) { node temp = new node(wordList[i], curr2.len + 1 ); q2.Enqueue(temp); vis2.Add(wordList[i], curr2.len + 1); // If temp is the destination node // then return the answer if (temp.word.Equals(beginWord)) { return temp.len; } // If temp is present in vis1 i.e. distance from // temp and the source is already calculated if (vis1.ContainsKey(temp.word)) { return temp.len + vis1[temp.word] - 1; } } } } return 0;} // Driver codepublic static void Main(String []args){ List<String> wordList = new List<String>(); wordList.Add("poon"); wordList.Add("plee"); wordList.Add("same"); wordList.Add("poie"); wordList.Add("plie"); wordList.Add("poin"); wordList.Add("plea"); String start = "toon"; String target = "plea"; Console.WriteLine(ladderLength(start, target, wordList));}} // This code is contributed by Rajput-Ji # Python 3 implementation of the approachfrom collections import deque as dq # class for queueclass node : def __init__(self, w, l): self.word=w self.len=l # Function that returns true if a and b# differ in only a single characterdef isAdj(a, b): count = 0 for i in range(len(a)): if (a[i] != b[i]): count+=1 if (count == 1): return True return False # Function to return the length of the shortest# chain from ‘beginWord’ to ‘endWord’def ladderLength(beginWord, endWord, wordList): # q1 is used to traverse the graph from beginWord # and q2 is used to traverse the graph from endWord. # vis1 and vis2 are used to keep track of the # visited states from respective directions q1=dq([]) q2=dq([]) vis1=dict() vis2=dict() start = node(beginWord, 1) end = node(endWord, 1) vis1[beginWord] = 1 q1.append(start) vis2[endWord] = 1 q2.append(end) while (q1 and q2): # Fetch the current node # from the source queue curr1 = q1.popleft() # Fetch the current node from # the destination queue curr2 = q2.popleft() # Check all the neighbors of curr1 for it in wordList: # If any one of them is adjacent to curr1 # and is not present in vis1 # then push it in the queue if (isAdj(curr1.word, it) and it not in vis1) : temp = node(it, curr1.len + 1) q1.append(temp) vis1[it] = curr1.len + 1 # If temp is the destination node # then return the answer if (temp.word == endWord) : return temp.len # If temp is present in vis2 i.e. distance from # temp and the destination is already calculated if temp.word in vis2 : return temp.len + vis2[temp.word] - 1 # Check all the neighbors of curr2 for it in wordList: # If any one of them is adjacent to curr2 # and is not present in vis1 then push it in the queue. if (isAdj(curr2.word, it) and it not in vis2) : temp = node(it, curr2.len + 1) q2.append(temp) vis2[it] = curr2.len + 1 # If temp is the destination node # then return the answer if (temp.word == beginWord) : return temp.len # If temp is present in vis1 i.e. distance from # temp and the source is already calculated if temp.word in vis1: return temp.len + vis1[temp.word] - 1 return 0 # Driver codeif __name__=='__main__': wordList=[] wordList.append("poon") wordList.append("plee") wordList.append("same") wordList.append("poie") wordList.append("plie") wordList.append("poin") wordList.append("plea") start = "toon" target = "plea" print(ladderLength(start, target, wordList)) 7 Time Complexity: O(N^2), where N is the length of the string.Auxiliary Space: O(N). sambhavjain3 Rajput-Ji pankajsharmagfg amartyaghoshgfg BFS Data Structures Graph Hash Queue Data Structures Hash Graph Queue BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Introduction to Data Structures What is Hashing | A Complete Tutorial Introduction to Tree Data Structure What is Data Structure: Types, Classifications and Applications Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations Topological Sorting Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Dec, 2021" }, { "code": null, "e": 476, "s": 54, "text": "Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the target word exists in the dictionary and the lengths of all the dictionary words are equal.Examples: " }, { "code": null, "e": 635, "s": 476, "text": "Input: Dictionary = {POON, PLEE, SAME, POIE, PLEA, PLIE, POIN} start = “TOON” target = “PLEA” Output: 7 TOON -> POON –> POIN –> POIE –> PLIE –> PLEE –> PLEA " }, { "code": null, "e": 1741, "s": 637, "text": "Approach: This problem can be solved using the standard BFS approach as discussed here but its performance can be improved by using bi-directional BFS. Bi-directional BFS doesn’t reduce the time complexity of the solution but it definitely optimizes the performance in many cases. This approach can also be used in many other shortest pathfinding problems where we have sufficient information about the source and the target node. The basic idea involved in bi-directional BFS is to start the search from both the ends of the path. Therefore, two queues and two visited arrays are needed to be maintained to track both the paths. So, whenever a node (say A) is present in the source queue, encounters a node (say B) which is present in the target queue, then we can calculate the answer by adding the distance of A from source and the distance of B from target minus 1 (one node is common). This way we can calculate the answer in half the time as compared to the standard BFS approach. This method is also known as the meet-in-the-middle BFS approach.Below is the implementation of the above approach: " }, { "code": null, "e": 1745, "s": 1741, "text": "C++" }, { "code": null, "e": 1750, "s": 1745, "text": "Java" }, { "code": null, "e": 1753, "s": 1750, "text": "C#" }, { "code": null, "e": 1761, "s": 1753, "text": "Python3" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Structure for queuestruct node { string word; int len;}; // Function that returns true if a and b// differ in only a single characterbool isAdj(string a, string b){ int count = 0; for (int i = 0; i < a.length(); i++) { if (a[i] != b[i]) count++; } if (count == 1) return true; return false;} // Function to return the length of the shortest// chain from ‘beginWord’ to ‘endWord’int ladderLength(string beginWord, string endWord, vector<string>& wordList){ /* q1 is used to traverse the graph from beginWord and q2 is used to traverse the graph from endWord. vis1 and vis2 are used to keep track of the visited states from respective directions */ queue<node> q1; queue<node> q2; unordered_map<string, int> vis1; unordered_map<string, int> vis2; node start = { beginWord, 1 }; node end = { endWord, 1 }; vis1[beginWord] = 1; q1.push(start); vis2[endWord] = 1; q2.push(end); while (!q1.empty() && !q2.empty()) { // Fetch the current node // from the source queue node curr1 = q1.front(); q1.pop(); // Fetch the current node from // the destination queue node curr2 = q2.front(); q2.pop(); // Check all the neighbors of curr1 for (auto it = wordList.begin(); it != wordList.end(); it++) { // If any one of them is adjacent to curr1 // and is not present in vis1 // then push it in the queue if (isAdj(curr1.word, *it) && vis1.count(*it) == false) { node temp = { *it, curr1.len + 1 }; q1.push(temp); vis1[*it] = curr1.len + 1; // If temp is the destination node // then return the answer if (temp.word == endWord) { return temp.len; } // If temp is present in vis2 i.e. distance from // temp and the destination is already calculated if (vis2.count(temp.word)) { return temp.len + vis2[temp.word] - 1; } } } // Check all the neighbors of curr2 for (auto it = wordList.begin(); it != wordList.end(); it++) { // If any one of them is adjacent to curr2 // and is not present in vis1 then push it in the queue. if (isAdj(curr2.word, *it) && vis2.count(*it) == false) { node temp = { *it, curr2.len + 1 }; q2.push(temp); vis2[*it] = curr2.len + 1; // If temp is the destination node // then return the answer if (temp.word == beginWord) { return temp.len; } // If temp is present in vis1 i.e. distance from // temp and the source is already calculated if (vis1.count(temp.word)) { return temp.len + vis1[temp.word] - 1; } } } } return 0;} // Driver codeint main(){ vector<string> wordList; wordList.push_back(\"poon\"); wordList.push_back(\"plee\"); wordList.push_back(\"same\"); wordList.push_back(\"poie\"); wordList.push_back(\"plie\"); wordList.push_back(\"poin\"); wordList.push_back(\"plea\"); string start = \"toon\"; string target = \"plea\"; cout << ladderLength(start, target, wordList); return 0;}", "e": 5313, "s": 1761, "text": null }, { "code": "import java.util.*;public class GFG{public static class node{ String word; int len; public node(String word, int len) { this.word = word; this.len = len; }} public static boolean isAdj(String a, String b){ int count = 0; for (int i = 0; i < a.length(); i++) { if (a.charAt(i) != b.charAt(i)) count++; } if (count == 1) return true; return false;} // Function to return the length of the shortest// chain from 'beginWord' to 'endWord'public static int ladderLength(String beginWord, String endWord, ArrayList<String> wordList){ /* q1 is used to traverse the graph from beginWord and q2 is used to traverse the graph from endWord. vis1 and vis2 are used to keep track of the visited states from respective directions */ Queue<node> q1 = new LinkedList<>(); Queue<node> q2 = new LinkedList<>(); HashMap<String, Integer> vis1 = new HashMap<>(); HashMap<String, Integer> vis2 = new HashMap<>(); node start = new node(beginWord, 1); node end = new node(endWord, 1); vis1.put(beginWord, 1); q1.add(start); vis2.put(endWord, 1); q2.add(end); while (q1.size() > 0 && q2.size() > 0) { // Fetch the current node // from the source queue node curr1 = q1.remove(); // Fetch the current node from // the destination queue node curr2 = q2.remove(); // Check all the neighbors of curr1 for (int i = 0; i < wordList.size(); i++) { // If any one of them is adjacent to curr1 // and is not present in vis1 // then push it in the queue if (isAdj(curr1.word,wordList.get(i)) && vis1.containsKey(wordList.get(i)) == false) { node temp = new node(wordList.get(i), curr1.len + 1); q1.add(temp); vis1.put(wordList.get(i), curr1.len + 1); // If temp is the destination node // then return the answer if (temp.word.equals(endWord)) { return temp.len; } // If temp is present in vis2 i.e. distance from // temp and the destination is already calculated if (vis2.containsKey(temp.word)) { return temp.len + vis2.get(temp.word) - 1; } } } // Check all the neighbors of curr2 for (int i = 0; i < wordList.size(); i++) { // If any one of them is adjacent to curr2 // and is not present in vis1 then push it in the queue. if (isAdj(curr2.word,wordList.get(i)) && vis2.containsKey(wordList.get(i)) == false) { node temp = new node(wordList.get(i), curr2.len + 1 ); q2.add(temp); vis2.put(wordList.get(i), curr2.len + 1); // If temp is the destination node // then return the answer if (temp.word.equals(beginWord)) { return temp.len; } // If temp is present in vis1 i.e. distance from // temp and the source is already calculated if (vis1.containsKey(temp.word)) { return temp.len + vis1.get(temp.word) - 1; } } } } return 0;} // Driver codepublic static void main(String args[]){ ArrayList<String> wordList = new ArrayList<>(); wordList.add(\"poon\"); wordList.add(\"plee\"); wordList.add(\"same\"); wordList.add(\"poie\"); wordList.add(\"plie\"); wordList.add(\"poin\"); wordList.add(\"plea\"); String start = \"toon\"; String target = \"plea\"; System.out.println(ladderLength(start, target, wordList));}} // This code is contributed by Sambhav Jain", "e": 9321, "s": 5313, "text": null }, { "code": "// C# implementation of the approach using System;using System.Collections.Generic; class GFG{ class node{ public String word; public int len; public node(String word, int len) { this.word = word; this.len = len; }} public static bool isAdj(String a, String b){ int count = 0; for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) count++; } if (count == 1) return true; return false;} // Function to return the length of the shortest// chain from 'beginWord' to 'endWord'public static int ladderLength(String beginWord, String endWord, List<String> wordList){ /* q1 is used to traverse the graph from beginWord and q2 is used to traverse the graph from endWord. vis1 and vis2 are used to keep track of the visited states from respective directions */ Queue<node> q1 = new Queue<node>(); Queue<node> q2 = new Queue<node>(); Dictionary<String, int> vis1 = new Dictionary<String, int>(); Dictionary<String, int> vis2 = new Dictionary<String, int>(); node start = new node(beginWord, 1); node end = new node(endWord, 1); vis1.Add(beginWord, 1); q1.Enqueue(start); vis2.Add(endWord, 1); q2.Enqueue(end); while (q1.Count > 0 && q2.Count > 0) { // Fetch the current node // from the source queue node curr1 = q1.Dequeue(); // Fetch the current node from // the destination queue node curr2 = q2.Dequeue(); // Check all the neighbors of curr1 for (int i = 0; i < wordList.Count; i++) { // If any one of them is adjacent to curr1 // and is not present in vis1 // then push it in the queue if (isAdj(curr1.word,wordList[i]) && vis1.ContainsKey(wordList[i]) == false) { node temp = new node(wordList[i], curr1.len + 1); q1.Enqueue(temp); vis1.Add(wordList[i], curr1.len + 1); // If temp is the destination node // then return the answer if (temp.word.Equals(endWord)) { return temp.len; } // If temp is present in vis2 i.e. distance from // temp and the destination is already calculated if (vis2.ContainsKey(temp.word)) { return temp.len + vis2[temp.word] - 1; } } } // Check all the neighbors of curr2 for (int i = 0; i < wordList.Count; i++) { // If any one of them is adjacent to curr2 // and is not present in vis1 then push it in the queue. if (isAdj(curr2.word,wordList[i]) && vis2.ContainsKey(wordList[i]) == false) { node temp = new node(wordList[i], curr2.len + 1 ); q2.Enqueue(temp); vis2.Add(wordList[i], curr2.len + 1); // If temp is the destination node // then return the answer if (temp.word.Equals(beginWord)) { return temp.len; } // If temp is present in vis1 i.e. distance from // temp and the source is already calculated if (vis1.ContainsKey(temp.word)) { return temp.len + vis1[temp.word] - 1; } } } } return 0;} // Driver codepublic static void Main(String []args){ List<String> wordList = new List<String>(); wordList.Add(\"poon\"); wordList.Add(\"plee\"); wordList.Add(\"same\"); wordList.Add(\"poie\"); wordList.Add(\"plie\"); wordList.Add(\"poin\"); wordList.Add(\"plea\"); String start = \"toon\"; String target = \"plea\"; Console.WriteLine(ladderLength(start, target, wordList));}} // This code is contributed by Rajput-Ji", "e": 13354, "s": 9321, "text": null }, { "code": "# Python 3 implementation of the approachfrom collections import deque as dq # class for queueclass node : def __init__(self, w, l): self.word=w self.len=l # Function that returns true if a and b# differ in only a single characterdef isAdj(a, b): count = 0 for i in range(len(a)): if (a[i] != b[i]): count+=1 if (count == 1): return True return False # Function to return the length of the shortest# chain from ‘beginWord’ to ‘endWord’def ladderLength(beginWord, endWord, wordList): # q1 is used to traverse the graph from beginWord # and q2 is used to traverse the graph from endWord. # vis1 and vis2 are used to keep track of the # visited states from respective directions q1=dq([]) q2=dq([]) vis1=dict() vis2=dict() start = node(beginWord, 1) end = node(endWord, 1) vis1[beginWord] = 1 q1.append(start) vis2[endWord] = 1 q2.append(end) while (q1 and q2): # Fetch the current node # from the source queue curr1 = q1.popleft() # Fetch the current node from # the destination queue curr2 = q2.popleft() # Check all the neighbors of curr1 for it in wordList: # If any one of them is adjacent to curr1 # and is not present in vis1 # then push it in the queue if (isAdj(curr1.word, it) and it not in vis1) : temp = node(it, curr1.len + 1) q1.append(temp) vis1[it] = curr1.len + 1 # If temp is the destination node # then return the answer if (temp.word == endWord) : return temp.len # If temp is present in vis2 i.e. distance from # temp and the destination is already calculated if temp.word in vis2 : return temp.len + vis2[temp.word] - 1 # Check all the neighbors of curr2 for it in wordList: # If any one of them is adjacent to curr2 # and is not present in vis1 then push it in the queue. if (isAdj(curr2.word, it) and it not in vis2) : temp = node(it, curr2.len + 1) q2.append(temp) vis2[it] = curr2.len + 1 # If temp is the destination node # then return the answer if (temp.word == beginWord) : return temp.len # If temp is present in vis1 i.e. distance from # temp and the source is already calculated if temp.word in vis1: return temp.len + vis1[temp.word] - 1 return 0 # Driver codeif __name__=='__main__': wordList=[] wordList.append(\"poon\") wordList.append(\"plee\") wordList.append(\"same\") wordList.append(\"poie\") wordList.append(\"plie\") wordList.append(\"poin\") wordList.append(\"plea\") start = \"toon\" target = \"plea\" print(ladderLength(start, target, wordList))", "e": 16464, "s": 13354, "text": null }, { "code": null, "e": 16466, "s": 16464, "text": "7" }, { "code": null, "e": 16553, "s": 16468, "text": "Time Complexity: O(N^2), where N is the length of the string.Auxiliary Space: O(N). " }, { "code": null, "e": 16566, "s": 16553, "text": "sambhavjain3" }, { "code": null, "e": 16576, "s": 16566, "text": "Rajput-Ji" }, { "code": null, "e": 16592, "s": 16576, "text": "pankajsharmagfg" }, { "code": null, "e": 16608, "s": 16592, "text": "amartyaghoshgfg" }, { "code": null, "e": 16612, "s": 16608, "text": "BFS" }, { "code": null, "e": 16628, "s": 16612, "text": "Data Structures" }, { "code": null, "e": 16634, "s": 16628, "text": "Graph" }, { "code": null, "e": 16639, "s": 16634, "text": "Hash" }, { "code": null, "e": 16645, "s": 16639, "text": "Queue" }, { "code": null, "e": 16661, "s": 16645, "text": "Data Structures" }, { "code": null, "e": 16666, "s": 16661, "text": "Hash" }, { "code": null, "e": 16672, "s": 16666, "text": "Graph" }, { "code": null, "e": 16678, "s": 16672, "text": "Queue" }, { "code": null, "e": 16682, "s": 16678, "text": "BFS" }, { "code": null, "e": 16780, "s": 16682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16805, "s": 16780, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 16837, "s": 16805, "text": "Introduction to Data Structures" }, { "code": null, "e": 16875, "s": 16837, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16911, "s": 16875, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 16975, "s": 16911, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 17026, "s": 16975, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 17077, "s": 17026, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 17107, "s": 17077, "text": "Graph and its representations" }, { "code": null, "e": 17127, "s": 17107, "text": "Topological Sorting" } ]
Database - First Normal Form (1NF)
The First normal form (1NF) sets basic rules for an organized database − Define the data items required, because they become the columns in a table. Define the data items required, because they become the columns in a table. Place the related data items in a table. Place the related data items in a table. Ensure that there are no repeating groups of data. Ensure that there are no repeating groups of data. Ensure that there is a primary key. Ensure that there is a primary key. You must define the data items. This means looking at the data to be stored, organizing the data into columns, defining what type of data each column contains and then finally putting the related columns into their own table. For example, you put all the columns relating to locations of meetings in the Location table, those relating to members in the MemberDetails table and so on. The next step is ensuring that there are no repeating groups of data. Consider we have the following table − CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), ORDERS VARCHAR(155) ); So, if we populate this table for a single customer having multiple orders, then it would be something as shown below − But as per the 1NF, we need to ensure that there are no repeating groups of data. So, let us break the above table into two parts and then join them using a key as shown in the following program − CUSTOMERS table − CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), PRIMARY KEY (ID) ); This table would have the following record − ORDERS table − CREATE TABLE ORDERS( ID INT NOT NULL, CUSTOMER_ID INT NOT NULL, ORDERS VARCHAR(155), PRIMARY KEY (ID) ); This table would have the following records − The final rule of the first normal form, create a primary key for each table which we have already created.
[ { "code": null, "e": 2660, "s": 2587, "text": "The First normal form (1NF) sets basic rules for an organized database −" }, { "code": null, "e": 2736, "s": 2660, "text": "Define the data items required, because they become the columns in a table." }, { "code": null, "e": 2812, "s": 2736, "text": "Define the data items required, because they become the columns in a table." }, { "code": null, "e": 2853, "s": 2812, "text": "Place the related data items in a table." }, { "code": null, "e": 2894, "s": 2853, "text": "Place the related data items in a table." }, { "code": null, "e": 2945, "s": 2894, "text": "Ensure that there are no repeating groups of data." }, { "code": null, "e": 2996, "s": 2945, "text": "Ensure that there are no repeating groups of data." }, { "code": null, "e": 3032, "s": 2996, "text": "Ensure that there is a primary key." }, { "code": null, "e": 3068, "s": 3032, "text": "Ensure that there is a primary key." }, { "code": null, "e": 3294, "s": 3068, "text": "You must define the data items. This means looking at the data to be stored, organizing the data into columns, defining what type of data each column contains and then finally putting the related columns into their own table." }, { "code": null, "e": 3452, "s": 3294, "text": "For example, you put all the columns relating to locations of meetings in the Location table, those relating to members in the MemberDetails table and so on." }, { "code": null, "e": 3561, "s": 3452, "text": "The next step is ensuring that there are no repeating groups of data. Consider we have the following table −" }, { "code": null, "e": 3741, "s": 3561, "text": "CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR (25),\n ORDERS VARCHAR(155)\n);" }, { "code": null, "e": 3861, "s": 3741, "text": "So, if we populate this table for a single customer having multiple orders, then it would be something as shown below −" }, { "code": null, "e": 4058, "s": 3861, "text": "But as per the 1NF, we need to ensure that there are no repeating groups of data. So, let us break the above table into two parts and then join them using a key as shown in the following program −" }, { "code": null, "e": 4076, "s": 4058, "text": "CUSTOMERS table −" }, { "code": null, "e": 4251, "s": 4076, "text": "CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR (25),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 4296, "s": 4251, "text": "This table would have the following record −" }, { "code": null, "e": 4311, "s": 4296, "text": "ORDERS table −" }, { "code": null, "e": 4451, "s": 4311, "text": "CREATE TABLE ORDERS(\n ID INT NOT NULL,\n CUSTOMER_ID INT NOT NULL,\n ORDERS VARCHAR(155),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 4497, "s": 4451, "text": "This table would have the following records −" } ]
Node.js async.queue() Method
11 Jun, 2021 The async module is is designed for working with asynchronous JavaScript in NodeJS. The async.queue returns a queue object which is capable of concurrent processing i.e processing multiple items at a single time. How to use async.queue? Step 1: Create a package.json file. A package.json file is created by the running the following command. npm init Step 2: Installing the async module. The async module can be installed using the following command. npm i async Step 3: Importing the async module. The async module can be imported using the following command. const async = require('async') Step 4: Using the async.queue module. Syntax of async.queue. const queue = async.queue('function', 'concurrency value') The parameter function is executed on the element added to the queue. The concurrency value tells the queue, the number of elements to be processed at a particular time. Example: Have a look at the below example for better understanding. Javascript // Defining The queueconst queue = async.queue((task, completed) => { // Here task is the current element being // processed and completed is the callback function console.log("Currently Busy Processing Task " + task); // Simulating a complex process. setTimeout(()=>{ // Number of elements to be processed. const remaining = queue.length(); completed(null, {task, remaining}); }, 1000); }, 1); // The concurrency value is set to one,// Which means that one element is being// Processed at a particular time Important methods and properties in async.queue: push(element, callback) :The push method is used to add elements to the tail of the queue. The following code demonstrates how push method works. Javascript // Takes in two parameters, the item being pushed and// the callback function// Here the item is the element being added// and other is the callback function with error// and data property(destructured) queue.push(item, (error, {item, remaining}) => { if(error){ console.log(`An error occurred while processing task ${task}`); } else { console.log(`Finished processing task ${task} . ${remaining} tasks remaining`); }}); length(): The length method returns the number of elements currently present in the queue. The following code demonstrates how the length method works. Javascript console.log(queue.length()); started property: The started property returns a boolean value, indicating whether the queue has started processing the data or not. The following code demonstrates how the started property works. Javascript // Returns true if the queue has started processing the data else falseconsole.log(queue.started) unshift(element, callback) :The unshift method is similar to the push method, but the element is added to the head of the queue, indicating that the element to be processed is an important one. The following code demonstrates how the unshift method works :- Javascript // Takes in two parameters, the item being pushed// and the callback function// Here the item is the element being added// and other is the callback function with error// and data property(destructured) queue.unshift(item, (error, {item, remaining}) => { if(error){ console.log(`An error occurred while processing task ${task}`); } else { console.log(`Finished processing task ${task}. ${remaining} tasks remaining`); }}); drain() Method : The drain method runs a callback function when the queue is done executing all the tasks. The following code demonstrates how the drain method works. Note: The drain method only works when the function described is an arrow function. Javascript // Executes when the queue is done processing all the itemsqueue.drain(() => { console.log('Successfully processed all items');}) pause() Method : The pause method pauses the execution of elements in the queue until the resume function is called. The following code demonstrates how the pause method works. Javascript // Pauses the execution of the queuequeue.pause() resume() Method: The resume method resumes the execution of elements in the queue. The following code demonstrates how the resume method works. Javascript // Resumes the execution of the queuequeue.resume() kill() Method: The kill method removes all the elements from the queue, the callback function of the drain method and forces it into idle. The following code demonstrates how the kill method works. Javascript // Forces the queue into idle mode// and removes the drain callbackqueue.kill() idle() Method: The idle() method return a boolean value, indicating whether the queue is idle or processing something. The following code demonstrates how the idle method works. Javascript // Returns whether the queue is idle or notqueue.idle() Complete Code: The following code is a complete demonstration of how the async.queue is actually used. Javascript // Importing the async moduleconst async = require('async'); // Creating a tasks arrayconst tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Defining the queueconst queue = async.queue((task, completed) => { console.log("Currently Busy Processing Task " + task); // Simulating a Complex task setTimeout(()=>{ // The number of tasks to be processed const remaining = queue.length(); completed(null, {task, remaining}); }, 1000); }, 1); // The concurrency value is 1 // The queue is idle as there are no elements// for the queue to processconsole.log(`Did the queue start ? ${queue.started}`) // Adding the each task to the queuetasks.forEach((task)=>{ // Adding the 5th task to the head of the // queue as it is deemed important by us if(task == 5){ queue.unshift(task, (error, {task, remaining})=>{ if(error){ console.log(`An error occurred while processing task ${task}`); }else { console.log(`Finished processing task ${task}. ${remaining} tasks remaining`); } }) // Adding the task to the tail in the order of their appearance } else { queue.push(task, (error, {task, remaining})=>{ if(error){ console.log(`An error occurred while processing task ${task}`); }else { console.log(`Finished processing task ${task}. ${remaining} tasks remaining`); } }) }}); // Executes the callback when the queue is done processing all the tasksqueue.drain(() => { console.log('Successfully processed all items');}) // The queue is not idle it is processing the tasks asynchronouslyconsole.log(`Did the queue start ? ${queue.started}`) Output: anikakapoor Node.js-Methods Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2021" }, { "code": null, "e": 241, "s": 28, "text": "The async module is is designed for working with asynchronous JavaScript in NodeJS. The async.queue returns a queue object which is capable of concurrent processing i.e processing multiple items at a single time." }, { "code": null, "e": 265, "s": 241, "text": "How to use async.queue?" }, { "code": null, "e": 372, "s": 265, "text": "Step 1: Create a package.json file. A package.json file is created by the running the following command. " }, { "code": null, "e": 381, "s": 372, "text": "npm init" }, { "code": null, "e": 483, "s": 381, "text": "Step 2: Installing the async module. The async module can be installed using the following command. " }, { "code": null, "e": 495, "s": 483, "text": "npm i async" }, { "code": null, "e": 595, "s": 495, "text": "Step 3: Importing the async module. The async module can be imported using the following command. " }, { "code": null, "e": 626, "s": 595, "text": "const async = require('async')" }, { "code": null, "e": 688, "s": 626, "text": "Step 4: Using the async.queue module. Syntax of async.queue. " }, { "code": null, "e": 747, "s": 688, "text": "const queue = async.queue('function', 'concurrency value')" }, { "code": null, "e": 917, "s": 747, "text": "The parameter function is executed on the element added to the queue. The concurrency value tells the queue, the number of elements to be processed at a particular time." }, { "code": null, "e": 985, "s": 917, "text": "Example: Have a look at the below example for better understanding." }, { "code": null, "e": 996, "s": 985, "text": "Javascript" }, { "code": "// Defining The queueconst queue = async.queue((task, completed) => { // Here task is the current element being // processed and completed is the callback function console.log(\"Currently Busy Processing Task \" + task); // Simulating a complex process. setTimeout(()=>{ // Number of elements to be processed. const remaining = queue.length(); completed(null, {task, remaining}); }, 1000); }, 1); // The concurrency value is set to one,// Which means that one element is being// Processed at a particular time", "e": 1553, "s": 996, "text": null }, { "code": null, "e": 1606, "s": 1557, "text": "Important methods and properties in async.queue:" }, { "code": null, "e": 1754, "s": 1608, "text": "push(element, callback) :The push method is used to add elements to the tail of the queue. The following code demonstrates how push method works." }, { "code": null, "e": 1769, "s": 1758, "text": "Javascript" }, { "code": "// Takes in two parameters, the item being pushed and// the callback function// Here the item is the element being added// and other is the callback function with error// and data property(destructured) queue.push(item, (error, {item, remaining}) => { if(error){ console.log(`An error occurred while processing task ${task}`); } else { console.log(`Finished processing task ${task} . ${remaining} tasks remaining`); }});", "e": 2215, "s": 1769, "text": null }, { "code": null, "e": 2373, "s": 2221, "text": "length(): The length method returns the number of elements currently present in the queue. The following code demonstrates how the length method works." }, { "code": null, "e": 2388, "s": 2377, "text": "Javascript" }, { "code": "console.log(queue.length());", "e": 2417, "s": 2388, "text": null }, { "code": null, "e": 2620, "s": 2423, "text": "started property: The started property returns a boolean value, indicating whether the queue has started processing the data or not. The following code demonstrates how the started property works." }, { "code": null, "e": 2635, "s": 2624, "text": "Javascript" }, { "code": "// Returns true if the queue has started processing the data else falseconsole.log(queue.started)", "e": 2733, "s": 2635, "text": null }, { "code": null, "e": 2997, "s": 2739, "text": "unshift(element, callback) :The unshift method is similar to the push method, but the element is added to the head of the queue, indicating that the element to be processed is an important one. The following code demonstrates how the unshift method works :-" }, { "code": null, "e": 3012, "s": 3001, "text": "Javascript" }, { "code": "// Takes in two parameters, the item being pushed// and the callback function// Here the item is the element being added// and other is the callback function with error// and data property(destructured) queue.unshift(item, (error, {item, remaining}) => { if(error){ console.log(`An error occurred while processing task ${task}`); } else { console.log(`Finished processing task ${task}. ${remaining} tasks remaining`); }});", "e": 3442, "s": 3012, "text": null }, { "code": null, "e": 3615, "s": 3448, "text": "drain() Method : The drain method runs a callback function when the queue is done executing all the tasks. The following code demonstrates how the drain method works." }, { "code": null, "e": 3703, "s": 3619, "text": "Note: The drain method only works when the function described is an arrow function." }, { "code": null, "e": 3718, "s": 3707, "text": "Javascript" }, { "code": "// Executes when the queue is done processing all the itemsqueue.drain(() => { console.log('Successfully processed all items');})", "e": 3851, "s": 3718, "text": null }, { "code": null, "e": 4032, "s": 3855, "text": "pause() Method : The pause method pauses the execution of elements in the queue until the resume function is called. The following code demonstrates how the pause method works." }, { "code": null, "e": 4047, "s": 4036, "text": "Javascript" }, { "code": "// Pauses the execution of the queuequeue.pause()", "e": 4097, "s": 4047, "text": null }, { "code": null, "e": 4247, "s": 4103, "text": "resume() Method: The resume method resumes the execution of elements in the queue. The following code demonstrates how the resume method works." }, { "code": null, "e": 4262, "s": 4251, "text": "Javascript" }, { "code": "// Resumes the execution of the queuequeue.resume()", "e": 4314, "s": 4262, "text": null }, { "code": null, "e": 4518, "s": 4320, "text": "kill() Method: The kill method removes all the elements from the queue, the callback function of the drain method and forces it into idle. The following code demonstrates how the kill method works." }, { "code": null, "e": 4533, "s": 4522, "text": "Javascript" }, { "code": "// Forces the queue into idle mode// and removes the drain callbackqueue.kill()", "e": 4613, "s": 4533, "text": null }, { "code": null, "e": 4797, "s": 4619, "text": "idle() Method: The idle() method return a boolean value, indicating whether the queue is idle or processing something. The following code demonstrates how the idle method works." }, { "code": null, "e": 4812, "s": 4801, "text": "Javascript" }, { "code": "// Returns whether the queue is idle or notqueue.idle()", "e": 4868, "s": 4812, "text": null }, { "code": null, "e": 4979, "s": 4876, "text": "Complete Code: The following code is a complete demonstration of how the async.queue is actually used." }, { "code": null, "e": 4992, "s": 4981, "text": "Javascript" }, { "code": "// Importing the async moduleconst async = require('async'); // Creating a tasks arrayconst tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Defining the queueconst queue = async.queue((task, completed) => { console.log(\"Currently Busy Processing Task \" + task); // Simulating a Complex task setTimeout(()=>{ // The number of tasks to be processed const remaining = queue.length(); completed(null, {task, remaining}); }, 1000); }, 1); // The concurrency value is 1 // The queue is idle as there are no elements// for the queue to processconsole.log(`Did the queue start ? ${queue.started}`) // Adding the each task to the queuetasks.forEach((task)=>{ // Adding the 5th task to the head of the // queue as it is deemed important by us if(task == 5){ queue.unshift(task, (error, {task, remaining})=>{ if(error){ console.log(`An error occurred while processing task ${task}`); }else { console.log(`Finished processing task ${task}. ${remaining} tasks remaining`); } }) // Adding the task to the tail in the order of their appearance } else { queue.push(task, (error, {task, remaining})=>{ if(error){ console.log(`An error occurred while processing task ${task}`); }else { console.log(`Finished processing task ${task}. ${remaining} tasks remaining`); } }) }}); // Executes the callback when the queue is done processing all the tasksqueue.drain(() => { console.log('Successfully processed all items');}) // The queue is not idle it is processing the tasks asynchronouslyconsole.log(`Did the queue start ? ${queue.started}`)", "e": 6647, "s": 4992, "text": null }, { "code": null, "e": 6659, "s": 6651, "text": "Output:" }, { "code": null, "e": 6675, "s": 6663, "text": "anikakapoor" }, { "code": null, "e": 6691, "s": 6675, "text": "Node.js-Methods" }, { "code": null, "e": 6698, "s": 6691, "text": "Picked" }, { "code": null, "e": 6706, "s": 6698, "text": "Node.js" }, { "code": null, "e": 6723, "s": 6706, "text": "Web Technologies" }, { "code": null, "e": 6821, "s": 6723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6853, "s": 6821, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 6888, "s": 6853, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 6958, "s": 6888, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 6985, "s": 6958, "text": "Mongoose Populate() Method" }, { "code": null, "e": 7010, "s": 6985, "text": "Mongoose find() Function" }, { "code": null, "e": 7072, "s": 7010, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7133, "s": 7072, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7183, "s": 7133, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7226, "s": 7183, "text": "How to fetch data from an API in ReactJS ?" } ]
Generate integer from 1 to 7 with equal probability
21 Oct, 2021 Given a function foo() that returns integers from 1 to 5 with equal probability, write a function that returns integers from 1 to 7 with equal probability using foo() only. Minimize the number of calls to foo() method. Also, use of any other library function is not allowed and no floating point arithmetic allowed.Solution : We know foo() returns integers from 1 to 5. How we can ensure that integers from 1 to 7 occur with equal probability? If we somehow generate integers from 1 to a-multiple-of-7 (like 7, 14, 21, ...) with equal probability, we can use modulo division by 7 followed by adding 1 to get the numbers from 1 to 7 with equal probability.We can generate from 1 to 21 with equal probability using the following expression. 5*foo() + foo() -5 Let us see how above expression can be used. 1. For each value of first foo(), there can be 5 possible combinations for values of second foo(). So, there are total 25 combinations possible. 2. The range of values returned by the above equation is 1 to 25, each integer occurring exactly once. 3. If the value of the equation comes out to be less than 22, return modulo division by 7 followed by adding 1. Else, again call the method recursively. The probability of returning each integer thus becomes 1/7.The below program shows that the expression returns each integer from 1 to 25 exactly once. C++ Java Python3 C# PHP Javascript #include <stdio.h> int main(){ int first, second; for ( first=1; first<=5; ++first ) for ( second=1; second<=5; ++second ) printf ("%d \n", 5*first + second - 5); return 0;} // Java code to demonstrate// expression returns each integer// from 1 to 25 exactly once class GFG { public static void main(String[] args) { int first, second; for ( first=1; first<=5; ++first ) for ( second=1; second<=5; ++second ) System.out.printf ("%d \n", 5*first + second - 5); }} // This code is contributed by// Smitha Dinesh Semwal # Python3 code to demonstrate# expression returns each integer# from 1 to 25 exactly once if name == '__main__': for first in range(1, 6): for second in range(1, 6): print(5 * first + second - 5) # This code is contributed by Smitha Dinesh Semwal. // C# code to demonstrate expression returns// each integer from 1 to 25 exactly onceusing System; class GFG { public static void Main() { int first, second; for ( first = 1; first <= 5; ++first ) for ( second = 1; second <= 5; ++second ) Console.WriteLine ( 5*first + second - 5); }} // This code is contributed by Sam007. <?php// PHP program to Generate integer// from 1 to 7 with equal probability $first; $second; for ( $first = 1; $first <= 5; ++$first ) for ( $second = 1; $second <= 5; ++$second ) echo 5 * $first + $second - 5, "\n"; // This code is contributed by ajit.?> <script> // Javascript Program to demonstrate// expression returns each integer// from 1 to 25 exactly once // Driver Code let first, second; for ( first=1; first<=5; ++first ) for ( second=1; second<=5; ++second ) { document.write( 5*first + second - 5); document.write("<br />"); } </script> Output : 1 2 . . 24 25 Time Complexity: O(1) Auxiliary Space: O(1) The below program depicts how we can use foo() to return 1 to 7 with equal probability. C++ Java Python3 C# PHP Javascript // C++ program to Generate integer from// 1 to 5 with equal probability#include <stdio.h> // given method that returns 1 to 5 with equal probabilityint foo(){ // some code here} int my_rand() // returns 1 to 7 with equal probability{ int i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand();}// Driver codeint main(){ printf ("%d ", my_rand()); return 0;} // Java program to Generate integer from// 1 to 5 with equal probabilityclass GfG{ // given method that returns 1 to 5 with equal probabilitystatic int foo(){ // some code here return 0;} // returns 1 to 7 with equal probabilitypublic static int my_rand() { int i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand();} // Driver codepublic static void main (String[] args) { System.out.println(my_rand());}} # Python3 program to Generate integer# from 1 to 5 with equal probability# given method that returns 1 to 5# with equal probabilitydef foo(): # some code here return 0; # returns 1 to 7 with equal probabilitydef my_rand(): i = 0; i = (5 * foo()) + (foo() - 5); if (i < 22): if(i < 0): return (i % 7 - 7) + 1; else: return (i % 7) + 1; return my_rand(); # Driver codeif __name__ == '__main__': print(my_rand()); # This code contributed by PrinciRaj1992 // C# program to Generate integer from// 1 to 5 with equal probabilityusing System;class GfG{ // given method that returns 1 to 5 with equal probabilitystatic int foo(){ // some code here return 0;} // returns 1 to 7 with equal probabilitypublic static int my_rand() { int i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand();} // Driver codepublic static void Main () { Console.Write(my_rand()+"\n");}} <?php// PHP program to Generate integer from// 1 to 5 with equal probability// given method that returns 1 to 5// with equal probabilityfunction foo(){ // some code here} // returns 1 to 7 with equal probabilityfunction my_rand(){ $i; $i = 5 * foo() + foo() - 5; if ($i < 22) return $i % 7 + 1; return my_rand();} // Driver codeecho my_rand(); // This code is contributed by Tushil.?> <script> // Javascript program to Generate integer from// 1 to 5 with equal probability // given method that returns 1 to 5 with equal probability function foo() { // some code here return 0; } // returns 1 to 7 with equal probability function my_rand() { let i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand(); } // Driver code document.write(my_rand()); // This code is contributed by rag2127 </script> Output: -4 Time Complexity: O(1) Auxiliary Space: O(1) This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t prerna saini ukasp princiraj1992 code_hunt rag2127 subhammahato348 subham348 Mathematical Randomized Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) Shuffle a given array using Fisher–Yates shuffle Algorithm QuickSort using Random Pivoting Shuffle or Randomize a list in Java Generating Random String Using PHP
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Oct, 2021" }, { "code": null, "e": 791, "s": 52, "text": "Given a function foo() that returns integers from 1 to 5 with equal probability, write a function that returns integers from 1 to 7 with equal probability using foo() only. Minimize the number of calls to foo() method. Also, use of any other library function is not allowed and no floating point arithmetic allowed.Solution : We know foo() returns integers from 1 to 5. How we can ensure that integers from 1 to 7 occur with equal probability? If we somehow generate integers from 1 to a-multiple-of-7 (like 7, 14, 21, ...) with equal probability, we can use modulo division by 7 followed by adding 1 to get the numbers from 1 to 7 with equal probability.We can generate from 1 to 21 with equal probability using the following expression." }, { "code": null, "e": 812, "s": 791, "text": " 5*foo() + foo() -5 " }, { "code": null, "e": 1411, "s": 812, "text": "Let us see how above expression can be used. 1. For each value of first foo(), there can be 5 possible combinations for values of second foo(). So, there are total 25 combinations possible. 2. The range of values returned by the above equation is 1 to 25, each integer occurring exactly once. 3. If the value of the equation comes out to be less than 22, return modulo division by 7 followed by adding 1. Else, again call the method recursively. The probability of returning each integer thus becomes 1/7.The below program shows that the expression returns each integer from 1 to 25 exactly once. " }, { "code": null, "e": 1415, "s": 1411, "text": "C++" }, { "code": null, "e": 1420, "s": 1415, "text": "Java" }, { "code": null, "e": 1428, "s": 1420, "text": "Python3" }, { "code": null, "e": 1431, "s": 1428, "text": "C#" }, { "code": null, "e": 1435, "s": 1431, "text": "PHP" }, { "code": null, "e": 1446, "s": 1435, "text": "Javascript" }, { "code": "#include <stdio.h> int main(){ int first, second; for ( first=1; first<=5; ++first ) for ( second=1; second<=5; ++second ) printf (\"%d \\n\", 5*first + second - 5); return 0;}", "e": 1647, "s": 1446, "text": null }, { "code": "// Java code to demonstrate// expression returns each integer// from 1 to 25 exactly once class GFG { public static void main(String[] args) { int first, second; for ( first=1; first<=5; ++first ) for ( second=1; second<=5; ++second ) System.out.printf (\"%d \\n\", 5*first + second - 5); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 2035, "s": 1647, "text": null }, { "code": "# Python3 code to demonstrate# expression returns each integer# from 1 to 25 exactly once if name == '__main__': for first in range(1, 6): for second in range(1, 6): print(5 * first + second - 5) # This code is contributed by Smitha Dinesh Semwal.", "e": 2313, "s": 2035, "text": null }, { "code": "// C# code to demonstrate expression returns// each integer from 1 to 25 exactly onceusing System; class GFG { public static void Main() { int first, second; for ( first = 1; first <= 5; ++first ) for ( second = 1; second <= 5; ++second ) Console.WriteLine ( 5*first + second - 5); }} // This code is contributed by Sam007.", "e": 2692, "s": 2313, "text": null }, { "code": "<?php// PHP program to Generate integer// from 1 to 7 with equal probability $first; $second; for ( $first = 1; $first <= 5; ++$first ) for ( $second = 1; $second <= 5; ++$second ) echo 5 * $first + $second - 5, \"\\n\"; // This code is contributed by ajit.?>", "e": 2977, "s": 2692, "text": null }, { "code": "<script> // Javascript Program to demonstrate// expression returns each integer// from 1 to 25 exactly once // Driver Code let first, second; for ( first=1; first<=5; ++first ) for ( second=1; second<=5; ++second ) { document.write( 5*first + second - 5); document.write(\"<br />\"); } </script>", "e": 3317, "s": 2977, "text": null }, { "code": null, "e": 3328, "s": 3317, "text": "Output : " }, { "code": null, "e": 3342, "s": 3328, "text": "1\n2\n.\n.\n24\n25" }, { "code": null, "e": 3364, "s": 3342, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3386, "s": 3364, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3476, "s": 3386, "text": "The below program depicts how we can use foo() to return 1 to 7 with equal probability. " }, { "code": null, "e": 3480, "s": 3476, "text": "C++" }, { "code": null, "e": 3485, "s": 3480, "text": "Java" }, { "code": null, "e": 3493, "s": 3485, "text": "Python3" }, { "code": null, "e": 3496, "s": 3493, "text": "C#" }, { "code": null, "e": 3500, "s": 3496, "text": "PHP" }, { "code": null, "e": 3511, "s": 3500, "text": "Javascript" }, { "code": "// C++ program to Generate integer from// 1 to 5 with equal probability#include <stdio.h> // given method that returns 1 to 5 with equal probabilityint foo(){ // some code here} int my_rand() // returns 1 to 7 with equal probability{ int i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand();}// Driver codeint main(){ printf (\"%d \", my_rand()); return 0;}", "e": 3915, "s": 3511, "text": null }, { "code": "// Java program to Generate integer from// 1 to 5 with equal probabilityclass GfG{ // given method that returns 1 to 5 with equal probabilitystatic int foo(){ // some code here return 0;} // returns 1 to 7 with equal probabilitypublic static int my_rand() { int i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand();} // Driver codepublic static void main (String[] args) { System.out.println(my_rand());}}", "e": 4370, "s": 3915, "text": null }, { "code": "# Python3 program to Generate integer# from 1 to 5 with equal probability# given method that returns 1 to 5# with equal probabilitydef foo(): # some code here return 0; # returns 1 to 7 with equal probabilitydef my_rand(): i = 0; i = (5 * foo()) + (foo() - 5); if (i < 22): if(i < 0): return (i % 7 - 7) + 1; else: return (i % 7) + 1; return my_rand(); # Driver codeif __name__ == '__main__': print(my_rand()); # This code contributed by PrinciRaj1992", "e": 4893, "s": 4370, "text": null }, { "code": "// C# program to Generate integer from// 1 to 5 with equal probabilityusing System;class GfG{ // given method that returns 1 to 5 with equal probabilitystatic int foo(){ // some code here return 0;} // returns 1 to 7 with equal probabilitypublic static int my_rand() { int i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand();} // Driver codepublic static void Main () { Console.Write(my_rand()+\"\\n\");}}", "e": 5350, "s": 4893, "text": null }, { "code": "<?php// PHP program to Generate integer from// 1 to 5 with equal probability// given method that returns 1 to 5// with equal probabilityfunction foo(){ // some code here} // returns 1 to 7 with equal probabilityfunction my_rand(){ $i; $i = 5 * foo() + foo() - 5; if ($i < 22) return $i % 7 + 1; return my_rand();} // Driver codeecho my_rand(); // This code is contributed by Tushil.?>", "e": 5757, "s": 5350, "text": null }, { "code": "<script> // Javascript program to Generate integer from// 1 to 5 with equal probability // given method that returns 1 to 5 with equal probability function foo() { // some code here return 0; } // returns 1 to 7 with equal probability function my_rand() { let i; i = 5*foo() + foo() - 5; if (i < 22) return i%7 + 1; return my_rand(); } // Driver code document.write(my_rand()); // This code is contributed by rag2127 </script>", "e": 6290, "s": 5757, "text": null }, { "code": null, "e": 6299, "s": 6290, "text": "Output: " }, { "code": null, "e": 6302, "s": 6299, "text": "-4" }, { "code": null, "e": 6324, "s": 6302, "text": "Time Complexity: O(1)" }, { "code": null, "e": 6346, "s": 6324, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6551, "s": 6346, "text": "This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 6557, "s": 6551, "text": "jit_t" }, { "code": null, "e": 6570, "s": 6557, "text": "prerna saini" }, { "code": null, "e": 6576, "s": 6570, "text": "ukasp" }, { "code": null, "e": 6590, "s": 6576, "text": "princiraj1992" }, { "code": null, "e": 6600, "s": 6590, "text": "code_hunt" }, { "code": null, "e": 6608, "s": 6600, "text": "rag2127" }, { "code": null, "e": 6624, "s": 6608, "text": "subhammahato348" }, { "code": null, "e": 6634, "s": 6624, "text": "subham348" }, { "code": null, "e": 6647, "s": 6634, "text": "Mathematical" }, { "code": null, "e": 6658, "s": 6647, "text": "Randomized" }, { "code": null, "e": 6671, "s": 6658, "text": "Mathematical" }, { "code": null, "e": 6769, "s": 6671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6799, "s": 6769, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 6842, "s": 6799, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6902, "s": 6842, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6917, "s": 6902, "text": "C++ Data Types" }, { "code": null, "e": 6941, "s": 6917, "text": "Merge two sorted arrays" }, { "code": null, "e": 7020, "s": 6941, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 7079, "s": 7020, "text": "Shuffle a given array using Fisher–Yates shuffle Algorithm" }, { "code": null, "e": 7111, "s": 7079, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 7147, "s": 7111, "text": "Shuffle or Randomize a list in Java" } ]
Python | Pandas Series.str.count()
24 Sep, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.count() method is used to count occurrence of a string or regex pattern in each string of a series. Additional flags arguments can also be passed to handle to modify some aspects of regex like case sensitivity, multi line matching etc. Since this is a pandas string method, it’s only applicable on Series of strings and .str has to be prefixed every time before calling this method. Otherwise, it will give an error. Syntax: Series.str.count(pat, flags=0) Parameters:pat: String or regex to be searched in the strings present in seriesflags: Regex flags that can be passed (A, S, L, M, I, X), default is 0 which means None. For this regex module (re) has to be imported too. Return type: Series with count of occurrence of passed characters in each string. To download the CSV used in code, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below. Example #1: Counting word occurrenceIn this example, a Pandas series is made from a list and occurrence of gfg is counted using str.count() method. # importing pandas packageimport pandas as pd # making listlist =["GeeksforGeeks", "Geeksforgeeks", "geeksforgeeks", "geeksforgeeks is a great platform", "for tech geeks"] # making seriesseries = pd.Series(list) # counting occurrence of geekscount = series.str.count("geeks") # displaycount Output:As shown in the output image, the occurrence of geeks in each string was displayed and Geeks wasn’t counted due to first upper case letter. Example #2: Using Flags In this example, occurrence of “a” is counted in the Name column. The flag parameter is also used and re.I is passed to it, which means IGNORECASE. Hence, a and A both will be considered during count. # importing pandas module import pandas as pd # importing module for regeximport re # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # String to be searched in start of string search ="a" # count of occurrence of a and creating new columndata["count"]= data["Name"].str.count(search, re.I) # displaydata Output:As shown in the output image, it can be clearly compared by looking at the first index itself, the count for a in Avery Bradely is 2, which means both upper case and lower case was considered. Python pandas-series Python pandas-series-methods Python-pandas Python-pandas-series-str Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 489, "s": 242, "text": "Pandas str.count() method is used to count occurrence of a string or regex pattern in each string of a series. Additional flags arguments can also be passed to handle to modify some aspects of regex like case sensitivity, multi line matching etc." }, { "code": null, "e": 670, "s": 489, "text": "Since this is a pandas string method, it’s only applicable on Series of strings and .str has to be prefixed every time before calling this method. Otherwise, it will give an error." }, { "code": null, "e": 709, "s": 670, "text": "Syntax: Series.str.count(pat, flags=0)" }, { "code": null, "e": 928, "s": 709, "text": "Parameters:pat: String or regex to be searched in the strings present in seriesflags: Regex flags that can be passed (A, S, L, M, I, X), default is 0 which means None. For this regex module (re) has to be imported too." }, { "code": null, "e": 1010, "s": 928, "text": "Return type: Series with count of occurrence of passed characters in each string." }, { "code": null, "e": 1056, "s": 1010, "text": "To download the CSV used in code, click here." }, { "code": null, "e": 1203, "s": 1056, "text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below." }, { "code": null, "e": 1351, "s": 1203, "text": "Example #1: Counting word occurrenceIn this example, a Pandas series is made from a list and occurrence of gfg is counted using str.count() method." }, { "code": "# importing pandas packageimport pandas as pd # making listlist =[\"GeeksforGeeks\", \"Geeksforgeeks\", \"geeksforgeeks\", \"geeksforgeeks is a great platform\", \"for tech geeks\"] # making seriesseries = pd.Series(list) # counting occurrence of geekscount = series.str.count(\"geeks\") # displaycount", "e": 1652, "s": 1351, "text": null }, { "code": null, "e": 1823, "s": 1652, "text": "Output:As shown in the output image, the occurrence of geeks in each string was displayed and Geeks wasn’t counted due to first upper case letter. Example #2: Using Flags" }, { "code": null, "e": 2024, "s": 1823, "text": "In this example, occurrence of “a” is counted in the Name column. The flag parameter is also used and re.I is passed to it, which means IGNORECASE. Hence, a and A both will be considered during count." }, { "code": "# importing pandas module import pandas as pd # importing module for regeximport re # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # String to be searched in start of string search =\"a\" # count of occurrence of a and creating new columndata[\"count\"]= data[\"Name\"].str.count(search, re.I) # displaydata", "e": 2393, "s": 2024, "text": null }, { "code": null, "e": 2593, "s": 2393, "text": "Output:As shown in the output image, it can be clearly compared by looking at the first index itself, the count for a in Avery Bradely is 2, which means both upper case and lower case was considered." }, { "code": null, "e": 2614, "s": 2593, "text": "Python pandas-series" }, { "code": null, "e": 2643, "s": 2614, "text": "Python pandas-series-methods" }, { "code": null, "e": 2657, "s": 2643, "text": "Python-pandas" }, { "code": null, "e": 2682, "s": 2657, "text": "Python-pandas-series-str" }, { "code": null, "e": 2689, "s": 2682, "text": "Python" }, { "code": null, "e": 2787, "s": 2689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2805, "s": 2787, "text": "Python Dictionary" }, { "code": null, "e": 2847, "s": 2805, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2869, "s": 2847, "text": "Enumerate() in Python" }, { "code": null, "e": 2901, "s": 2869, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2930, "s": 2901, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2957, "s": 2930, "text": "Python Classes and Objects" }, { "code": null, "e": 2987, "s": 2957, "text": "Iterate over a list in Python" }, { "code": null, "e": 3008, "s": 2987, "text": "Python OOPs Concepts" }, { "code": null, "e": 3044, "s": 3008, "text": "Convert integer to string in Python" } ]
Themes and Color Palettes in KivyMD
06 Jun, 2021 KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we are going to see themes and color palettes in KivyMD. In order to make our application more attractive and simple to use we can use themes and different colors for our app. For changing Theme color the App Module has inbuilt function theme_cls. theme_cls.theme_style: It has 2 options-dark and light Syntax: self.theme_cls.theme_style=”Dark” or “Light” Code: Python3 # importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.theme_style="Dark" btn = MDRectangleFlatButton(text="HI", pos_hint={ 'center_x': 0.5, 'center_y': 0.5}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print("button is pressed!!") if __name__ == "__main__": Demo().run() Output: Now, let’s see we will change the background of the theme in a light color: Python3 # importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.theme_style = "Light" # defining Button with all the parameters btn = MDRectangleFlatButton(text="HI", pos_hint={ 'center_x': 0.5, 'center_y': 0.3}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print("button is pressed!!") if __name__ == "__main__": Demo().run() Output: For changing colors the App Module has inbuilt function theme_cls. theme_cls.primary_palette: It has a variety of colors. It accepts a string of color name. theme_cls.primary_hue: It defines opaqueness of color 100 for light and A700 for dark. Syntax: theme_cls.primary_palette=string of color name(Eg-“blue”) theme_cls.primary_hue=opaqueness of color Example 1: Here we will color with the color green and opaqueness 100 Python3 # importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.primary_palette = "Green" self.theme_cls.primary_hue = "100" self.theme_cls.theme_style = "Light" btn = MDRectangleFlatButton(text="HI", pos_hint={ 'center_x': 0.5, 'center_y': 0.5}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print("button is pressed!!") if __name__ == "__main__": Demo().run() Output: Example 2: with the color cyan and opaqueness A700 Python3 # importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.primary_palette = "Cyan" self.theme_cls.primary_hue = "A700" self.theme_cls.theme_style = "Light" btn = MDRectangleFlatButton(text="HI", pos_hint={ 'center_x': 0.5, 'center_y': 0.5}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print("button is pressed!!") if __name__ == "__main__": Demo().run() Output: Python-gui python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 337, "s": 28, "text": "KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we are going to see themes and color palettes in KivyMD." }, { "code": null, "e": 528, "s": 337, "text": "In order to make our application more attractive and simple to use we can use themes and different colors for our app. For changing Theme color the App Module has inbuilt function theme_cls." }, { "code": null, "e": 583, "s": 528, "text": "theme_cls.theme_style: It has 2 options-dark and light" }, { "code": null, "e": 636, "s": 583, "text": "Syntax: self.theme_cls.theme_style=”Dark” or “Light”" }, { "code": null, "e": 642, "s": 636, "text": "Code:" }, { "code": null, "e": 650, "s": 642, "text": "Python3" }, { "code": "# importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.theme_style=\"Dark\" btn = MDRectangleFlatButton(text=\"HI\", pos_hint={ 'center_x': 0.5, 'center_y': 0.5}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print(\"button is pressed!!\") if __name__ == \"__main__\": Demo().run()", "e": 1551, "s": 650, "text": null }, { "code": null, "e": 1559, "s": 1551, "text": "Output:" }, { "code": null, "e": 1635, "s": 1559, "text": "Now, let’s see we will change the background of the theme in a light color:" }, { "code": null, "e": 1643, "s": 1635, "text": "Python3" }, { "code": "# importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.theme_style = \"Light\" # defining Button with all the parameters btn = MDRectangleFlatButton(text=\"HI\", pos_hint={ 'center_x': 0.5, 'center_y': 0.3}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print(\"button is pressed!!\") if __name__ == \"__main__\": Demo().run()", "e": 2557, "s": 1643, "text": null }, { "code": null, "e": 2565, "s": 2557, "text": "Output:" }, { "code": null, "e": 2632, "s": 2565, "text": "For changing colors the App Module has inbuilt function theme_cls." }, { "code": null, "e": 2722, "s": 2632, "text": "theme_cls.primary_palette: It has a variety of colors. It accepts a string of color name." }, { "code": null, "e": 2809, "s": 2722, "text": "theme_cls.primary_hue: It defines opaqueness of color 100 for light and A700 for dark." }, { "code": null, "e": 2875, "s": 2809, "text": "Syntax: theme_cls.primary_palette=string of color name(Eg-“blue”)" }, { "code": null, "e": 2931, "s": 2875, "text": " theme_cls.primary_hue=opaqueness of color" }, { "code": null, "e": 3001, "s": 2931, "text": "Example 1: Here we will color with the color green and opaqueness 100" }, { "code": null, "e": 3009, "s": 3001, "text": "Python3" }, { "code": "# importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.primary_palette = \"Green\" self.theme_cls.primary_hue = \"100\" self.theme_cls.theme_style = \"Light\" btn = MDRectangleFlatButton(text=\"HI\", pos_hint={ 'center_x': 0.5, 'center_y': 0.5}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print(\"button is pressed!!\") if __name__ == \"__main__\": Demo().run()", "e": 3959, "s": 3009, "text": null }, { "code": null, "e": 3967, "s": 3959, "text": "Output:" }, { "code": null, "e": 4018, "s": 3967, "text": "Example 2: with the color cyan and opaqueness A700" }, { "code": null, "e": 4026, "s": 4018, "text": "Python3" }, { "code": "# importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.screen import Screenfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # adding theme_color self.theme_cls.primary_palette = \"Cyan\" self.theme_cls.primary_hue = \"A700\" self.theme_cls.theme_style = \"Light\" btn = MDRectangleFlatButton(text=\"HI\", pos_hint={ 'center_x': 0.5, 'center_y': 0.5}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(btn) # returning the screen return screen # defining a btnfun() for the button to # call when clicked on it def btnfunc(self, obj): print(\"button is pressed!!\") if __name__ == \"__main__\": Demo().run()", "e": 4970, "s": 4026, "text": null }, { "code": null, "e": 4978, "s": 4970, "text": "Output:" }, { "code": null, "e": 4989, "s": 4978, "text": "Python-gui" }, { "code": null, "e": 5004, "s": 4989, "text": "python-modules" }, { "code": null, "e": 5011, "s": 5004, "text": "Python" }, { "code": null, "e": 5109, "s": 5011, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5141, "s": 5109, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5168, "s": 5141, "text": "Python Classes and Objects" }, { "code": null, "e": 5189, "s": 5168, "text": "Python OOPs Concepts" }, { "code": null, "e": 5212, "s": 5189, "text": "Introduction To PYTHON" }, { "code": null, "e": 5268, "s": 5212, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5299, "s": 5268, "text": "Python | os.path.join() method" }, { "code": null, "e": 5341, "s": 5299, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5383, "s": 5341, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5422, "s": 5383, "text": "Python | Get unique values from a list" } ]
How to capture out of memory exception in C#?
The System.OutOfMemoryException occurs when the CLR fail in allocating enough memory that is needed. System.OutOfMemoryException is inherited from the System.SystemException class. Set the strings − string StudentName = "Tom"; string StudentSubject = "Maths"; Now you need to initialize with allocated Capacity that is the length of initial value − StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length); Now, if you will try to insert additional value, the exception occurs. sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1); The following exception occurs − System.OutOfMemoryException: Out of memory To capture the error, try the following code − Live Demo using System; using System.Text; namespace Demo { class Program { static void Main(string[] args) { try { string StudentName = "Tom"; string StudentSubject = "Maths"; StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length); // Append initial value sBuilder.Append(StudentName); sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1); } catch (System.OutOfMemoryException e) { Console.WriteLine("Error:"); Console.WriteLine(e); } } } } The above handles OutOfMemoryException and generates the following error − Error: System.OutOfMemoryException: Out of memory
[ { "code": null, "e": 1163, "s": 1062, "text": "The System.OutOfMemoryException occurs when the CLR fail in allocating enough memory that is needed." }, { "code": null, "e": 1243, "s": 1163, "text": "System.OutOfMemoryException is inherited from the System.SystemException class." }, { "code": null, "e": 1261, "s": 1243, "text": "Set the strings −" }, { "code": null, "e": 1322, "s": 1261, "text": "string StudentName = \"Tom\";\nstring StudentSubject = \"Maths\";" }, { "code": null, "e": 1411, "s": 1322, "text": "Now you need to initialize with allocated Capacity that is the length of initial value −" }, { "code": null, "e": 1495, "s": 1411, "text": "StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);" }, { "code": null, "e": 1566, "s": 1495, "text": "Now, if you will try to insert additional value, the exception occurs." }, { "code": null, "e": 1647, "s": 1566, "text": "sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);" }, { "code": null, "e": 1680, "s": 1647, "text": "The following exception occurs −" }, { "code": null, "e": 1723, "s": 1680, "text": "System.OutOfMemoryException: Out of memory" }, { "code": null, "e": 1770, "s": 1723, "text": "To capture the error, try the following code −" }, { "code": null, "e": 1781, "s": 1770, "text": " Live Demo" }, { "code": null, "e": 2416, "s": 1781, "text": "using System;\nusing System.Text;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n try {\n string StudentName = \"Tom\";\n string StudentSubject = \"Maths\";\n StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);\n // Append initial value\n sBuilder.Append(StudentName);\n sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);\n } catch (System.OutOfMemoryException e) {\n Console.WriteLine(\"Error:\");\n Console.WriteLine(e);\n }\n }\n }\n}" }, { "code": null, "e": 2491, "s": 2416, "text": "The above handles OutOfMemoryException and generates the following error −" }, { "code": null, "e": 2541, "s": 2491, "text": "Error:\nSystem.OutOfMemoryException: Out of memory" } ]
8 Ways to Filter Pandas Dataframes | by Soner Yıldırım | Towards Data Science
Pandas is a popular data analysis and manipulation library for Python. The core data structure of Pandas is dataframe which stores data in tabular form with labelled rows and columns. A common operation in data analysis is to filter values based on a condition or multiple conditions. Pandas provides a variety of ways to filter data points (i.e. rows). In this article, we will cover 8 different ways to filter a dataframe. We start by importing the libraries. import numpy as npimport pandas as pd Let’s create a sample dataframe for the examples. df = pd.DataFrame({name':['Jane','John','Ashley','Mike','Emily','Jack','Catlin'],'ctg':['A','A','C','B','B','C','B'],'val':np.random.random(7).round(2),'val2':np.random.randint(1,10, size=7)}) We can use the logical operators on column values to filter rows. df[df.val > 0.5] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 4 Emily B 0.99 8 6 Catlin B 1.00 3 We have selected the rows in which the value in “val” column is greater than 0.5. The logical operators also works on strings. df[df.name > 'Jane'] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 Only the names that come after ‘Jane’ in alphabetical order are selected. Pandas allows for combining multiple logical operators. For instance, we can apply conditions on both val and val2 columns as below. df[(df.val > 0.5) & (df.val2 == 1)] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 The “&” signs stands for “and” , the “|” stands for “or”. df[(df.val < 0.5) | (df.val2 == 7)] name ctg val val2 ------------------------------------------- 0 Jane A 0.43 1 2 Ashley C 0.40 7 5 Jack C 0.02 7 The isin method is another way of applying multiple condition for filtering. For instance, we can filter the names that exist in a given list. names = ['John','Catlin','Mike']df[df.name.isin(names)] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 6 Catlin B 1.00 3 Pandas is a highly efficient library on textual data as well. The functions and methods under the str accessor provide flexible ways to filter rows based on strings. For instance, we can select the names that start with the letter “J”. df[df.name.str.startswith('J')] name ctg val val2 ------------------------------------------- 0 Jane A 0.43 1 1 John A 0.67 1 5 Jack C 0.02 7 The contains function under the str accessor returns the values that contain a given set of characters. df[df.name.str.contains('y')] name ctg val val2 ------------------------------------------- 2 Ashley C 0.40 7 4 Emily B 0.99 8 We can pass a longer set of characters to the contains function depending on the strings in the data. The tilde operator is used for “not” logic in filtering. If we add the tilde operator before the filter expression, the rows that do not fit the condition are returned. df[~df.name.str.startswith('J')] name ctg val val2 ------------------------------------------- 2 Ashley C 0.40 7 3 Mike B 0.91 5 4 Emily B 0.99 8 6 Catlin B 1.00 3 We get the names that do not start with the letter “J”. The query function offers a little more flexibility at writing the conditions for filtering. We can pass the conditions as a string. For instance, the following code returns the rows that belong to the B category and have a value higher than 0.5 in the val column. df.query('ctg == "B" and val > 0.5') name ctg val val2 ------------------------------------------- 3 Mike B 0.91 5 4 Emily B 0.99 8 6 Catlin B 1.00 3 In some cases, we do not have a specific range for filtering but just need the largest or smallest values. The nlargest and nsmallest functions allow for selecting rows that have the largest or smallest values in a column, respectively. df.nlargest(3, 'val') name ctg val val2 ------------------------------------------- 6 Catlin B 1.00 3 4 Emily B 0.99 8 3 Mike B 0.91 5 We specify the number of largest or smallest values to be selected and the name of the column. df.nsmallest(2, 'val2') name ctg val val2 ------------------------------------------- 0 Jane A 0.43 1 1 John A 0.67 1 The loc and iloc methods are used to select rows or columns based on index or label. loc: select rows or columns using labels iloc: select rows or columns using indices Thus, they can be used for filtering. However, we can only select a particular part of the dataframe without specifying a condition. df.iloc[3:5, :] #rows 3 and 4, all columns name ctg val val2 ------------------------------------------- 3 Mike B 0.91 5 4 Emily B 0.99 8 If the dataframe has integer index, the indices and labels of the rows are the same. Thus, both loc and iloc accomplished the same thing on the rows. df.loc[3:5, :] #rows 3 and 4, all columns name ctg val val2 ------------------------------------------- 3 Mike B 0.91 5 4 Emily B 0.99 8 Let’s update the index of the dataframe to demonstrate the difference between loc and iloc better. df.index = ['a','b','c','d','e','f','g'] We cannot pass integers to the loc method now because the labels of indices are letters. df.loc['b':'d', :] name ctg val val2 ------------------------------------------- b John A 0.67 1 c Ashley C 0.40 7 d Mike B 0.91 5 We have covered 8 different ways of filtering rows in a dataframe. All of them are useful and come in handy for particular cases. Pandas is a powerful library for both data analysis and manipulation. It provides numerous functions and methods to handle data in tabular form. As with any other tool, the best way to learn Pandas is through practicing. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 355, "s": 171, "text": "Pandas is a popular data analysis and manipulation library for Python. The core data structure of Pandas is dataframe which stores data in tabular form with labelled rows and columns." }, { "code": null, "e": 596, "s": 355, "text": "A common operation in data analysis is to filter values based on a condition or multiple conditions. Pandas provides a variety of ways to filter data points (i.e. rows). In this article, we will cover 8 different ways to filter a dataframe." }, { "code": null, "e": 633, "s": 596, "text": "We start by importing the libraries." }, { "code": null, "e": 671, "s": 633, "text": "import numpy as npimport pandas as pd" }, { "code": null, "e": 721, "s": 671, "text": "Let’s create a sample dataframe for the examples." }, { "code": null, "e": 914, "s": 721, "text": "df = pd.DataFrame({name':['Jane','John','Ashley','Mike','Emily','Jack','Catlin'],'ctg':['A','A','C','B','B','C','B'],'val':np.random.random(7).round(2),'val2':np.random.randint(1,10, size=7)})" }, { "code": null, "e": 980, "s": 914, "text": "We can use the logical operators on column values to filter rows." }, { "code": null, "e": 1316, "s": 980, "text": "df[df.val > 0.5] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 4 Emily B 0.99 8 6 Catlin B 1.00 3" }, { "code": null, "e": 1398, "s": 1316, "text": "We have selected the rows in which the value in “val” column is greater than 0.5." }, { "code": null, "e": 1443, "s": 1398, "text": "The logical operators also works on strings." }, { "code": null, "e": 1686, "s": 1443, "text": "df[df.name > 'Jane'] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 " }, { "code": null, "e": 1760, "s": 1686, "text": "Only the names that come after ‘Jane’ in alphabetical order are selected." }, { "code": null, "e": 1893, "s": 1760, "text": "Pandas allows for combining multiple logical operators. For instance, we can apply conditions on both val and val2 columns as below." }, { "code": null, "e": 2094, "s": 1893, "text": "df[(df.val > 0.5) & (df.val2 == 1)] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 " }, { "code": null, "e": 2152, "s": 2094, "text": "The “&” signs stands for “and” , the “|” stands for “or”." }, { "code": null, "e": 2450, "s": 2152, "text": "df[(df.val < 0.5) | (df.val2 == 7)] name ctg val val2 ------------------------------------------- 0 Jane A 0.43 1 2 Ashley C 0.40 7 5 Jack C 0.02 7" }, { "code": null, "e": 2593, "s": 2450, "text": "The isin method is another way of applying multiple condition for filtering. For instance, we can filter the names that exist in a given list." }, { "code": null, "e": 2907, "s": 2593, "text": "names = ['John','Catlin','Mike']df[df.name.isin(names)] name ctg val val2 ------------------------------------------- 1 John A 0.67 1 3 Mike B 0.91 5 6 Catlin B 1.00 3" }, { "code": null, "e": 3073, "s": 2907, "text": "Pandas is a highly efficient library on textual data as well. The functions and methods under the str accessor provide flexible ways to filter rows based on strings." }, { "code": null, "e": 3143, "s": 3073, "text": "For instance, we can select the names that start with the letter “J”." }, { "code": null, "e": 3433, "s": 3143, "text": "df[df.name.str.startswith('J')] name ctg val val2 ------------------------------------------- 0 Jane A 0.43 1 1 John A 0.67 1 5 Jack C 0.02 7" }, { "code": null, "e": 3537, "s": 3433, "text": "The contains function under the str accessor returns the values that contain a given set of characters." }, { "code": null, "e": 3772, "s": 3537, "text": "df[df.name.str.contains('y')] name ctg val val2 ------------------------------------------- 2 Ashley C 0.40 7 4 Emily B 0.99 8" }, { "code": null, "e": 3874, "s": 3772, "text": "We can pass a longer set of characters to the contains function depending on the strings in the data." }, { "code": null, "e": 4043, "s": 3874, "text": "The tilde operator is used for “not” logic in filtering. If we add the tilde operator before the filter expression, the rows that do not fit the condition are returned." }, { "code": null, "e": 4390, "s": 4043, "text": "df[~df.name.str.startswith('J')] name ctg val val2 ------------------------------------------- 2 Ashley C 0.40 7 3 Mike B 0.91 5 4 Emily B 0.99 8 6 Catlin B 1.00 3" }, { "code": null, "e": 4446, "s": 4390, "text": "We get the names that do not start with the letter “J”." }, { "code": null, "e": 4579, "s": 4446, "text": "The query function offers a little more flexibility at writing the conditions for filtering. We can pass the conditions as a string." }, { "code": null, "e": 4711, "s": 4579, "text": "For instance, the following code returns the rows that belong to the B category and have a value higher than 0.5 in the val column." }, { "code": null, "e": 5005, "s": 4711, "text": "df.query('ctg == \"B\" and val > 0.5') name ctg val val2 ------------------------------------------- 3 Mike B 0.91 5 4 Emily B 0.99 8 6 Catlin B 1.00 3" }, { "code": null, "e": 5242, "s": 5005, "text": "In some cases, we do not have a specific range for filtering but just need the largest or smallest values. The nlargest and nsmallest functions allow for selecting rows that have the largest or smallest values in a column, respectively." }, { "code": null, "e": 5521, "s": 5242, "text": "df.nlargest(3, 'val') name ctg val val2 ------------------------------------------- 6 Catlin B 1.00 3 4 Emily B 0.99 8 3 Mike B 0.91 5" }, { "code": null, "e": 5616, "s": 5521, "text": "We specify the number of largest or smallest values to be selected and the name of the column." }, { "code": null, "e": 5842, "s": 5616, "text": "df.nsmallest(2, 'val2') name ctg val val2 ------------------------------------------- 0 Jane A 0.43 1 1 John A 0.67 1" }, { "code": null, "e": 5927, "s": 5842, "text": "The loc and iloc methods are used to select rows or columns based on index or label." }, { "code": null, "e": 5968, "s": 5927, "text": "loc: select rows or columns using labels" }, { "code": null, "e": 6011, "s": 5968, "text": "iloc: select rows or columns using indices" }, { "code": null, "e": 6144, "s": 6011, "text": "Thus, they can be used for filtering. However, we can only select a particular part of the dataframe without specifying a condition." }, { "code": null, "e": 6389, "s": 6144, "text": "df.iloc[3:5, :] #rows 3 and 4, all columns name ctg val val2 ------------------------------------------- 3 Mike B 0.91 5 4 Emily B 0.99 8" }, { "code": null, "e": 6539, "s": 6389, "text": "If the dataframe has integer index, the indices and labels of the rows are the same. Thus, both loc and iloc accomplished the same thing on the rows." }, { "code": null, "e": 6783, "s": 6539, "text": "df.loc[3:5, :] #rows 3 and 4, all columns name ctg val val2 ------------------------------------------- 3 Mike B 0.91 5 4 Emily B 0.99 8" }, { "code": null, "e": 6882, "s": 6783, "text": "Let’s update the index of the dataframe to demonstrate the difference between loc and iloc better." }, { "code": null, "e": 6923, "s": 6882, "text": "df.index = ['a','b','c','d','e','f','g']" }, { "code": null, "e": 7012, "s": 6923, "text": "We cannot pass integers to the loc method now because the labels of indices are letters." }, { "code": null, "e": 7289, "s": 7012, "text": "df.loc['b':'d', :] name ctg val val2 ------------------------------------------- b John A 0.67 1 c Ashley C 0.40 7 d Mike B 0.91 5" }, { "code": null, "e": 7419, "s": 7289, "text": "We have covered 8 different ways of filtering rows in a dataframe. All of them are useful and come in handy for particular cases." }, { "code": null, "e": 7640, "s": 7419, "text": "Pandas is a powerful library for both data analysis and manipulation. It provides numerous functions and methods to handle data in tabular form. As with any other tool, the best way to learn Pandas is through practicing." } ]
Create a transparent box with CSS
To create a transparent box with CSS, you can try to run the following code Live Demo <!DOCTYPE html> <html> <head> <style> div { background-color: #808000; padding: 20px; } div.myopacity { opacity: 0.4; filter: alpha(opacity=80); } </style> </head> <body> <h1>Heading</h1> <p>Check trensparency in the below box:</p> <div class = "myopacity"> <p>opacity 0.4</p> </div> <div> <p>opacity 1</p> </div> </body> </html>
[ { "code": null, "e": 1138, "s": 1062, "text": "To create a transparent box with CSS, you can try to run the following code" }, { "code": null, "e": 1148, "s": 1138, "text": "Live Demo" }, { "code": null, "e": 1640, "s": 1148, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n background-color: #808000;\n padding: 20px;\n }\n div.myopacity {\n opacity: 0.4;\n filter: alpha(opacity=80);\n }\n </style>\n </head>\n <body>\n <h1>Heading</h1>\n <p>Check trensparency in the below box:</p>\n <div class = \"myopacity\">\n <p>opacity 0.4</p>\n </div>\n <div>\n <p>opacity 1</p>\n </div>\n </body>\n</html>" } ]
F# - Nested Loops
F# programming language allows to use one loop inside another loop. The syntax for a nested for loop statement could be as follows − for var1 = start-expr1 to end-expr1 do for var2 = start-expr2 to end-expr2 do ... // loop body The syntax for a nested while loop statement could be as follows − while test-expression1 do while test-expression2 do body-expression let main() = for i = 1 to 5 do printf "\n" for j = 1 to 3 do printf "*" main() When you compile and execute the program, it yields the following output − *** *** *** *** *** Print Add Notes Bookmark this page
[ { "code": null, "e": 2229, "s": 2161, "text": "F# programming language allows to use one loop inside another loop." }, { "code": null, "e": 2294, "s": 2229, "text": "The syntax for a nested for loop statement could be as follows −" }, { "code": null, "e": 2399, "s": 2294, "text": "for var1 = start-expr1 to end-expr1 do\n for var2 = start-expr2 to end-expr2 do\n ... // loop body\n" }, { "code": null, "e": 2466, "s": 2399, "text": "The syntax for a nested while loop statement could be as follows −" }, { "code": null, "e": 2544, "s": 2466, "text": "while test-expression1 do\n while test-expression2 do\n body-expression\n" }, { "code": null, "e": 2647, "s": 2544, "text": "let main() =\n for i = 1 to 5 do\n printf \"\\n\"\n for j = 1 to 3 do\n printf \"*\"\nmain()" }, { "code": null, "e": 2722, "s": 2647, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 2743, "s": 2722, "text": "***\n***\n***\n***\n***\n" }, { "code": null, "e": 2750, "s": 2743, "text": " Print" }, { "code": null, "e": 2761, "s": 2750, "text": " Add Notes" } ]
How to check for duplicates in MySQL table over multiple columns?
To check for duplicates in MySQL, you can use group by having clause. The syntax is as follows. select yourColumnName1,yourColumnName2,......N,count(*) as anyVariableName from yourTableName group by yourColumnName1,yourColumnName2 having count(*) > 1; To understand the above syntax, let us create a table. The query to create a table is as follows. mysql> create table DuplicateDemo -> ( -> StudentId int not null, -> StudentFirstName varchar(100), -> StudentLastName varchar(100), -> Primary Key(StudentId) -> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command. The query is as follows. mysql> insert into DuplicateDemo values(1,'John','Smith'); Query OK, 1 row affected (0.13 sec) mysql> insert into DuplicateDemo values(2,'Mike','Jones'); Query OK, 1 row affected (0.28 sec) mysql> insert into DuplicateDemo values(3,'David','Smith'); Query OK, 1 row affected (0.15 sec) mysql> insert into DuplicateDemo values(4,'Carol','Taylor'); Query OK, 1 row affected (0.20 sec) mysql> insert into DuplicateDemo values(5,'David','Smith'); Query OK, 1 row affected (0.11 sec) mysql> insert into DuplicateDemo values(6,'John','Smith'); Query OK, 1 row affected (0.16 sec) mysql> insert into DuplicateDemo values(7,'John','Taylor'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. The query is as follows - mysql> select *from DuplicateDemo; The following is the output. +-----------+------------------+-----------------+ | StudentId | StudentFirstName | StudentLastName | +-----------+------------------+-----------------+ | 1 | John | Smith | | 2 | Mike | Jones | | 3 | David | Smith | | 4 | Carol | Taylor | | 5 | David | Smith | | 6 | John | Smith | | 7 | John | Taylor | +-----------+------------------+-----------------+ 7 rows in set (0.00 sec) Here is the query to check the duplicates from the table. mysql> select StudentFirstName,StudentLastName,count(*) as Total from DuplicateDemo -> group by StudentFirstName,StudentLastName -> having count(*) > 1; The following is the output. +------------------+-----------------+-------+ | StudentFirstName | StudentLastName | Total | +------------------+-----------------+-------+ | John | Smith | 2 | | David | Smith | 2 | +------------------+-----------------+-------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1158, "s": 1062, "text": "To check for duplicates in MySQL, you can use group by having clause. The syntax is as follows." }, { "code": null, "e": 1314, "s": 1158, "text": "select yourColumnName1,yourColumnName2,......N,count(*) as anyVariableName from\nyourTableName\ngroup by yourColumnName1,yourColumnName2\nhaving count(*) > 1;" }, { "code": null, "e": 1412, "s": 1314, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows." }, { "code": null, "e": 1614, "s": 1412, "text": "mysql> create table DuplicateDemo\n-> (\n-> StudentId int not null,\n-> StudentFirstName varchar(100),\n-> StudentLastName varchar(100),\n-> Primary Key(StudentId)\n-> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1694, "s": 1614, "text": "Insert some records in the table using insert command. The query is as follows." }, { "code": null, "e": 2370, "s": 1694, "text": "mysql> insert into DuplicateDemo values(1,'John','Smith');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DuplicateDemo values(2,'Mike','Jones');\nQuery OK, 1 row affected (0.28 sec)\n\nmysql> insert into DuplicateDemo values(3,'David','Smith');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DuplicateDemo values(4,'Carol','Taylor');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DuplicateDemo values(5,'David','Smith');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DuplicateDemo values(6,'John','Smith');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into DuplicateDemo values(7,'John','Taylor');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2429, "s": 2370, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2455, "s": 2429, "text": "The query is as follows -" }, { "code": null, "e": 2490, "s": 2455, "text": "mysql> select *from DuplicateDemo;" }, { "code": null, "e": 2519, "s": 2490, "text": "The following is the output." }, { "code": null, "e": 3105, "s": 2519, "text": "+-----------+------------------+-----------------+\n| StudentId | StudentFirstName | StudentLastName |\n+-----------+------------------+-----------------+\n| 1 | John | Smith |\n| 2 | Mike | Jones |\n| 3 | David | Smith |\n| 4 | Carol | Taylor |\n| 5 | David | Smith |\n| 6 | John | Smith |\n| 7 | John | Taylor |\n+-----------+------------------+-----------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3163, "s": 3105, "text": "Here is the query to check the duplicates from the table." }, { "code": null, "e": 3316, "s": 3163, "text": "mysql> select StudentFirstName,StudentLastName,count(*) as Total from DuplicateDemo\n-> group by StudentFirstName,StudentLastName\n-> having count(*) > 1;" }, { "code": null, "e": 3345, "s": 3316, "text": "The following is the output." }, { "code": null, "e": 3652, "s": 3345, "text": "+------------------+-----------------+-------+\n| StudentFirstName | StudentLastName | Total |\n+------------------+-----------------+-------+\n| John | Smith | 2 |\n| David | Smith | 2 |\n+------------------+-----------------+-------+\n2 rows in set (0.00 sec)" } ]
How to rotate a video in OpenCV using C++?
Rotating a video is similar to rotate an image. The only difference is instead of load a still picture into an image matrix, we have loaded a video or take video stream from the camera. Here, we are not loading the video but taking a video using the camera. If you want to use a video file, just put the address of the video file properly. The following program demonstrates how to rotate a video in OpenCV using C++. #include<iostream> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace std; using namespace cv; int main(int argc, char* argv[]) { VideoCapture loadvideo(0);//capture video from default camera// namedWindow("OriginalVideo");//declaring window to show original video stream// namedWindow("RotatedVideo");//declaring window to show rotated video stream// int rotating_angle = 180;//initial rotation angle// createTrackbar("Rotation", "RotatedVideo", &rotating_angle, 360);//creating trackbar for rotation// while (true) { Mat before_Rotating;//declaring matrix for image before rotation// bool temp = loadvideo.read(before_Rotating);//load frames from video source to matrix// imshow("OriginalVideo", before_Rotating);//show image frames before rotation// Mat for_Rotation = getRotationMatrix2D(Point(before_Rotating.cols / 2, before_Rotating.rows / 2), (rotating_angle - 180), 1);//affine transformation matrix for the 2D rotation// Mat after_Rotating;//declaring matrix for image after rotation// warpAffine(before_Rotating, after_Rotating, for_Rotation, before_Rotating.size());//applying affine transformation// imshow("RotatedVideo", after_Rotating);//show image after rotating// if (waitKey(30) == 27){ //wait till Esc key is pressed from keyboard// break; } } return 0; }
[ { "code": null, "e": 1248, "s": 1062, "text": "Rotating a video is similar to rotate an image. The only difference is instead of load a still picture into an image matrix, we have loaded a video or take video stream from the camera." }, { "code": null, "e": 1402, "s": 1248, "text": "Here, we are not loading the video but taking a video using the camera. If you want to use a video file, just put the address of the video file properly." }, { "code": null, "e": 1480, "s": 1402, "text": "The following program demonstrates how to rotate a video in OpenCV using C++." }, { "code": null, "e": 2884, "s": 1480, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace std;\nusing namespace cv;\nint main(int argc, char* argv[]) {\n VideoCapture loadvideo(0);//capture video from default camera//\n namedWindow(\"OriginalVideo\");//declaring window to show original video stream//\n namedWindow(\"RotatedVideo\");//declaring window to show rotated video stream//\n int rotating_angle = 180;//initial rotation angle//\n createTrackbar(\"Rotation\", \"RotatedVideo\", &rotating_angle, 360);//creating trackbar for rotation//\n while (true) {\n Mat before_Rotating;//declaring matrix for image before rotation//\n bool temp = loadvideo.read(before_Rotating);//load frames from video source to matrix//\n imshow(\"OriginalVideo\", before_Rotating);//show image frames before rotation//\n Mat for_Rotation = getRotationMatrix2D(Point(before_Rotating.cols / 2, before_Rotating.rows / 2), (rotating_angle - 180), 1);//affine transformation matrix for the 2D rotation//\n Mat after_Rotating;//declaring matrix for image after rotation//\n warpAffine(before_Rotating, after_Rotating, for_Rotation, before_Rotating.size());//applying affine transformation//\n imshow(\"RotatedVideo\", after_Rotating);//show image after rotating//\n if (waitKey(30) == 27){ //wait till Esc key is pressed from keyboard//\n break;\n }\n }\n return 0;\n}" } ]
How to make a canvas in Java Swing?
To make a canvas with Java Swing, use the Graphics2D class − public void paint(Graphics g) { Graphics2D graphic2d = (Graphics2D) g; graphic2d.setColor(Color.BLUE); graphic2d.fillRect(100, 50, 60, 80); } Above, we have created a rectangle and also added color to it. The following is an example to make a canvas in Java − package my; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingDemo extends JPanel { @Override public void paint(Graphics g) { Graphics2D graphic2d = (Graphics2D) g; graphic2d.setColor(Color.BLUE); graphic2d.fillRect(100, 50, 60, 80); } public static void main(String[] args) { JFrame frame = new JFrame("Demo"); frame.add(new SwingDemo()); frame.setSize(550, 250); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } This will produce the following output −
[ { "code": null, "e": 1123, "s": 1062, "text": "To make a canvas with Java Swing, use the Graphics2D class −" }, { "code": null, "e": 1274, "s": 1123, "text": "public void paint(Graphics g) {\n Graphics2D graphic2d = (Graphics2D) g;\n graphic2d.setColor(Color.BLUE);\n graphic2d.fillRect(100, 50, 60, 80);\n}" }, { "code": null, "e": 1337, "s": 1274, "text": "Above, we have created a rectangle and also added color to it." }, { "code": null, "e": 1392, "s": 1337, "text": "The following is an example to make a canvas in Java −" }, { "code": null, "e": 2001, "s": 1392, "text": "package my;\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\npublic class SwingDemo extends JPanel {\n @Override\n public void paint(Graphics g) {\n Graphics2D graphic2d = (Graphics2D) g;\n graphic2d.setColor(Color.BLUE);\n graphic2d.fillRect(100, 50, 60, 80);\n }\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Demo\");\n frame.add(new SwingDemo());\n frame.setSize(550, 250);\n frame.setVisible(true);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n}" }, { "code": null, "e": 2042, "s": 2001, "text": "This will produce the following output −" } ]
How do threads communicate with each other in Java?
Inter-thread communication involves the communication of threads with each other. The three methods that are used to implement inter-thread communication in Java This method causes the current thread to release the lock. This is done until a specific amount of time has passed or another thread calls the notify() or notifyAll() method for this object. This method wakes a single thread out of multiple threads on the current object’s monitor. The choice of thread is arbitrary. This method wakes up all the threads that are on the current object’s monitor. class BankClient { int balAmount = 5000; synchronized void withdrawMoney(int amount) { System.out.println("Withdrawing money"); balAmount -= amount; System.out.println("The balance amount is: " + balAmount); } synchronized void depositMoney(int amount) { System.out.println("Depositing money"); balAmount += amount; System.out.println("The balance amount is: " + balAmount); notify(); } } public class ThreadCommunicationTest { public static void main(String args[]) { final BankClient client = new BankClient(); new Thread() { public void run() { client.withdrawMoney(3000); } }.start(); new Thread() { public void run() { client.depositMoney(2000); } }.start(); } } Withdrawing money The balance amount is: 2000 Depositing money The balance amount is: 4000
[ { "code": null, "e": 1224, "s": 1062, "text": "Inter-thread communication involves the communication of threads with each other. The three methods that are used to implement inter-thread communication in Java" }, { "code": null, "e": 1415, "s": 1224, "text": "This method causes the current thread to release the lock. This is done until a specific amount of time has passed or another thread calls the notify() or notifyAll() method for this object." }, { "code": null, "e": 1541, "s": 1415, "text": "This method wakes a single thread out of multiple threads on the current object’s monitor. The choice of thread is arbitrary." }, { "code": null, "e": 1620, "s": 1541, "text": "This method wakes up all the threads that are on the current object’s monitor." }, { "code": null, "e": 2440, "s": 1620, "text": "class BankClient {\n int balAmount = 5000;\n synchronized void withdrawMoney(int amount) {\n System.out.println(\"Withdrawing money\");\n balAmount -= amount;\n System.out.println(\"The balance amount is: \" + balAmount);\n }\n synchronized void depositMoney(int amount) {\n System.out.println(\"Depositing money\");\n balAmount += amount;\n System.out.println(\"The balance amount is: \" + balAmount);\n notify();\n }\n}\npublic class ThreadCommunicationTest {\n public static void main(String args[]) {\n final BankClient client = new BankClient();\n new Thread() {\n public void run() {\n client.withdrawMoney(3000);\n }\n }.start();\n new Thread() {\n public void run() {\n client.depositMoney(2000);\n }\n }.start();\n }\n}" }, { "code": null, "e": 2531, "s": 2440, "text": "Withdrawing money\nThe balance amount is: 2000\nDepositing money\nThe balance amount is: 4000" } ]
How to create a simple http server listening at port 3000 to serve video ? - GeeksforGeeks
22 Oct, 2021 We can serve video to the browser/front end using nodeJS with the help of “express” and the in-built nodeJS file system “fs“. Here we would use the HTML video tag to view the video on the webpage. We would use express for routing purposes. We would send the video bytes by creating a read stream and piping the res Object to it. Let’s walk through step by step. Step 1: Create an “app.js” file and initialize the project with npm. Also, keep the video file that you want to stream in the same folder. npm init Step 2: Now install express and create the “index.html” file. npm install express Project Structure: It will look like the following. Project Structure Here “Welcome-To-GeeksforGeeks.mp4” is the mp4 file that we want to stream. Step 3: Let’s code now “app.js” file. The GET request to ‘/stream‘ sends the video as a readable stream. The root of the app loads the “index.html” file. We use res.writeHead() function to send the status message as 200 which means OK and the content type is mp4/video. We would now create a read stream using the fs.createReadStream() function to send the video as the readable stream for the HTML video tag. app.js // Requiring express for routingconst express = require('express') // Creating app from expressconst app = express() // Requiring in-built file systemconst fs = require('fs') // GET request which HTML video tag sendsapp.get('/stream',function(req,res){ // The path of the video from local file system const videoPath = 'Welcome-To-GeeksforGeeks.mp4' // 200 is OK status code and type of file is mp4 res.writeHead(200, {'Content-Type': 'video/mp4'}) // Creating readStream for th HTML video tag fs.createReadStream(videoPath).pipe(res)}) // GET request to the root of the appapp.get('/',function(req,res){ // Sending index.html file for GET request // to the root of the app res.sendFile(__dirname+'/index.html')}) // Creating server at port 3000app.listen(3000,function(req,res){ console.log('Server started at 3000')}) Step 4: Now we will code the “index.html” file. Here we are using the controls attribute for providing various controls of media-player in the video tag. And the autoplay is a Boolean attribute by which the video automatically begins to playback as soon as it can do so without stopping to finish loading the data. The src attribute of the HTML video tag is ‘/stream’ as defined in the app.js file. index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>Video Stream</title></head> <body> <!-- autoplay: A Boolean attribute; if specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data --> <video controls autoplay width="500px" height="500px"> <!-- GET request to the stream route --> <source src="/stream" type="video/mp4" /> </video></body> </html> Step 5: Now run the app using node app.js Output: Head over to your browser and enter http://localhost:3000/ Output NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property How to Convert CSV to JSON file having Comma Separated values in Node.js ? Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24531, "s": 24503, "text": "\n22 Oct, 2021" }, { "code": null, "e": 24893, "s": 24531, "text": "We can serve video to the browser/front end using nodeJS with the help of “express” and the in-built nodeJS file system “fs“. Here we would use the HTML video tag to view the video on the webpage. We would use express for routing purposes. We would send the video bytes by creating a read stream and piping the res Object to it. Let’s walk through step by step." }, { "code": null, "e": 25032, "s": 24893, "text": "Step 1: Create an “app.js” file and initialize the project with npm. Also, keep the video file that you want to stream in the same folder." }, { "code": null, "e": 25041, "s": 25032, "text": "npm init" }, { "code": null, "e": 25103, "s": 25041, "text": "Step 2: Now install express and create the “index.html” file." }, { "code": null, "e": 25123, "s": 25103, "text": "npm install express" }, { "code": null, "e": 25176, "s": 25123, "text": "Project Structure: It will look like the following. " }, { "code": null, "e": 25194, "s": 25176, "text": "Project Structure" }, { "code": null, "e": 25270, "s": 25194, "text": "Here “Welcome-To-GeeksforGeeks.mp4” is the mp4 file that we want to stream." }, { "code": null, "e": 25681, "s": 25270, "text": "Step 3: Let’s code now “app.js” file. The GET request to ‘/stream‘ sends the video as a readable stream. The root of the app loads the “index.html” file. We use res.writeHead() function to send the status message as 200 which means OK and the content type is mp4/video. We would now create a read stream using the fs.createReadStream() function to send the video as the readable stream for the HTML video tag." }, { "code": null, "e": 25688, "s": 25681, "text": "app.js" }, { "code": "// Requiring express for routingconst express = require('express') // Creating app from expressconst app = express() // Requiring in-built file systemconst fs = require('fs') // GET request which HTML video tag sendsapp.get('/stream',function(req,res){ // The path of the video from local file system const videoPath = 'Welcome-To-GeeksforGeeks.mp4' // 200 is OK status code and type of file is mp4 res.writeHead(200, {'Content-Type': 'video/mp4'}) // Creating readStream for th HTML video tag fs.createReadStream(videoPath).pipe(res)}) // GET request to the root of the appapp.get('/',function(req,res){ // Sending index.html file for GET request // to the root of the app res.sendFile(__dirname+'/index.html')}) // Creating server at port 3000app.listen(3000,function(req,res){ console.log('Server started at 3000')})", "e": 26551, "s": 25688, "text": null }, { "code": null, "e": 26950, "s": 26551, "text": "Step 4: Now we will code the “index.html” file. Here we are using the controls attribute for providing various controls of media-player in the video tag. And the autoplay is a Boolean attribute by which the video automatically begins to playback as soon as it can do so without stopping to finish loading the data. The src attribute of the HTML video tag is ‘/stream’ as defined in the app.js file." }, { "code": null, "e": 26961, "s": 26950, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>Video Stream</title></head> <body> <!-- autoplay: A Boolean attribute; if specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data --> <video controls autoplay width=\"500px\" height=\"500px\"> <!-- GET request to the stream route --> <source src=\"/stream\" type=\"video/mp4\" /> </video></body> </html>", "e": 27622, "s": 26961, "text": null }, { "code": null, "e": 27652, "s": 27622, "text": "Step 5: Now run the app using" }, { "code": null, "e": 27664, "s": 27652, "text": "node app.js" }, { "code": null, "e": 27731, "s": 27664, "text": "Output: Head over to your browser and enter http://localhost:3000/" }, { "code": null, "e": 27738, "s": 27731, "text": "Output" }, { "code": null, "e": 27755, "s": 27738, "text": "NodeJS-Questions" }, { "code": null, "e": 27762, "s": 27755, "text": "Picked" }, { "code": null, "e": 27770, "s": 27762, "text": "Node.js" }, { "code": null, "e": 27787, "s": 27770, "text": "Web Technologies" }, { "code": null, "e": 27885, "s": 27787, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27894, "s": 27885, "text": "Comments" }, { "code": null, "e": 27907, "s": 27894, "text": "Old Comments" }, { "code": null, "e": 27964, "s": 27907, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28003, "s": 27964, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28030, "s": 28003, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28061, "s": 28030, "text": "Express.js req.params Property" }, { "code": null, "e": 28136, "s": 28061, "text": "How to Convert CSV to JSON file having Comma Separated values in Node.js ?" }, { "code": null, "e": 28192, "s": 28136, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28254, "s": 28192, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28297, "s": 28254, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28347, "s": 28297, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Find all angles of a given triangle - GeeksforGeeks
17 Feb, 2022 Given coordinates of all three vertices of the triangle in the 2D plane, the task is to find all three angles.Example: Input : A = (0, 0), B = (0, 1), C = (1, 0) Output : 90, 45, 45 To solve this problem we use below Law of cosines. c^2 = a^2 + b^2 - 2(a)(b)(cos beta) After re-arranging beta = acos( ( a^2 + b^2 - c^2 ) / (2ab) ) In trigonometry, the law of cosines (also known as the cosine formula or cosine rule) relates the lengths of the sides of a triangle to the cosine of one of its angles. First, calculate the length of all the sides. Then apply above formula to get all angles in radian. Then convert angles from radian into degrees. Below is implementation of above steps. C++ Java Python3 C# // Code to find all three angles// of a triangle given coordinate// of all three vertices#include <iostream>#include <utility> // for pair#include <cmath> // for math functionsusing namespace std; #define PI 3.1415926535 // returns square of distance b/w two pointsint lengthSquare(pair<int,int> X, pair<int,int> Y){ int xDiff = X.first - Y.first; int yDiff = X.second - Y.second; return xDiff*xDiff + yDiff*yDiff;} void printAngle(pair<int,int> A, pair<int,int> B, pair<int,int> C){ // Square of lengths be a2, b2, c2 int a2 = lengthSquare(B,C); int b2 = lengthSquare(A,C); int c2 = lengthSquare(A,B); // length of sides be a, b, c float a = sqrt(a2); float b = sqrt(b2); float c = sqrt(c2); // From Cosine law float alpha = acos((b2 + c2 - a2)/(2*b*c)); float beta = acos((a2 + c2 - b2)/(2*a*c)); float gamma = acos((a2 + b2 - c2)/(2*a*b)); // Converting to degree alpha = alpha * 180 / PI; beta = beta * 180 / PI; gamma = gamma * 180 / PI; // printing all the angles cout << "alpha : " << alpha << endl; cout << "beta : " << beta << endl; cout << "gamma : " << gamma << endl;} // Driver codeint main(){ pair<int,int> A = make_pair(0,0); pair<int,int> B = make_pair(0,1); pair<int,int> C = make_pair(1,0); printAngle(A,B,C); return 0;} // Java Code to find all three angles// of a triangle given coordinate// of all three vertices import java.awt.Point;import static java.lang.Math.PI;import static java.lang.Math.sqrt;import static java.lang.Math.acos; class Test{ // returns square of distance b/w two points static int lengthSquare(Point p1, Point p2) { int xDiff = p1.x- p2.x; int yDiff = p1.y- p2.y; return xDiff*xDiff + yDiff*yDiff; } static void printAngle(Point A, Point B, Point C) { // Square of lengths be a2, b2, c2 int a2 = lengthSquare(B,C); int b2 = lengthSquare(A,C); int c2 = lengthSquare(A,B); // length of sides be a, b, c float a = (float)sqrt(a2); float b = (float)sqrt(b2); float c = (float)sqrt(c2); // From Cosine law float alpha = (float) acos((b2 + c2 - a2)/(2*b*c)); float betta = (float) acos((a2 + c2 - b2)/(2*a*c)); float gamma = (float) acos((a2 + b2 - c2)/(2*a*b)); // Converting to degree alpha = (float) (alpha * 180 / PI); betta = (float) (betta * 180 / PI); gamma = (float) (gamma * 180 / PI); // printing all the angles System.out.println("alpha : " + alpha); System.out.println("betta : " + betta); System.out.println("gamma : " + gamma); } // Driver method public static void main(String[] args) { Point A = new Point(0,0); Point B = new Point(0,1); Point C = new Point(1,0); printAngle(A,B,C); }} # Python3 code to find all three angles# of a triangle given coordinate# of all three verticesimport math # returns square of distance b/w two pointsdef lengthSquare(X, Y): xDiff = X[0] - Y[0] yDiff = X[1] - Y[1] return xDiff * xDiff + yDiff * yDiff def printAngle(A, B, C): # Square of lengths be a2, b2, c2 a2 = lengthSquare(B, C) b2 = lengthSquare(A, C) c2 = lengthSquare(A, B) # length of sides be a, b, c a = math.sqrt(a2); b = math.sqrt(b2); c = math.sqrt(c2); # From Cosine law alpha = math.acos((b2 + c2 - a2) / (2 * b * c)); betta = math.acos((a2 + c2 - b2) / (2 * a * c)); gamma = math.acos((a2 + b2 - c2) / (2 * a * b)); # Converting to degree alpha = alpha * 180 / math.pi; betta = betta * 180 / math.pi; gamma = gamma * 180 / math.pi; # printing all the angles print("alpha : %f" %(alpha)) print("betta : %f" %(betta)) print("gamma : %f" %(gamma)) # Driver codeA = (0, 0)B = (0, 1)C = (1, 0) printAngle(A, B, C); # This code is contributed# by ApurvaRaj // C# Code to find all three angles// of a triangle given coordinate// of all three verticesusing System; class GFG{ class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } // returns square of distance b/w two points static int lengthSquare(Point p1, Point p2) { int xDiff = p1.x - p2.x; int yDiff = p1.y - p2.y; return xDiff * xDiff + yDiff * yDiff; } static void printAngle(Point A, Point B, Point C) { // Square of lengths be a2, b2, c2 int a2 = lengthSquare(B, C); int b2 = lengthSquare(A, C); int c2 = lengthSquare(A, B); // length of sides be a, b, c float a = (float)Math.Sqrt(a2); float b = (float)Math.Sqrt(b2); float c = (float)Math.Sqrt(c2); // From Cosine law float alpha = (float) Math.Acos((b2 + c2 - a2) / (2 * b * c)); float betta = (float) Math.Acos((a2 + c2 - b2) / (2 * a * c)); float gamma = (float) Math.Acos((a2 + b2 - c2) / (2 * a * b)); // Converting to degree alpha = (float) (alpha * 180 / Math.PI); betta = (float) (betta * 180 / Math.PI); gamma = (float) (gamma * 180 / Math.PI); // printing all the angles Console.WriteLine("alpha : " + alpha); Console.WriteLine("betta : " + betta); Console.WriteLine("gamma : " + gamma); } // Driver Code public static void Main(String[] args) { Point A = new Point(0, 0); Point B = new Point(0, 1); Point C = new Point(1, 0); printAngle(A, B, C); }} // This code is contributed by Rajput-Ji Output: alpha : 90 beta : 45 gamma : 45 Reference : https://en.wikipedia.org/wiki/Law_of_cosinesThis article is contributed by Pratik Chhajer . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. MohitDhariwal Shivam_k Rajput-Ji ApurvaRaj rkbhola5 triangle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect Closest Pair of Points | O(nlogn) Implementation Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25172, "s": 25144, "text": "\n17 Feb, 2022" }, { "code": null, "e": 25293, "s": 25172, "text": "Given coordinates of all three vertices of the triangle in the 2D plane, the task is to find all three angles.Example: " }, { "code": null, "e": 25374, "s": 25293, "text": "Input : A = (0, 0), \n B = (0, 1), \n C = (1, 0)\nOutput : 90, 45, 45" }, { "code": null, "e": 25429, "s": 25376, "text": "To solve this problem we use below Law of cosines. " }, { "code": null, "e": 25467, "s": 25431, "text": "c^2 = a^2 + b^2 - 2(a)(b)(cos beta)" }, { "code": null, "e": 25488, "s": 25467, "text": "After re-arranging " }, { "code": null, "e": 25531, "s": 25488, "text": "beta = acos( ( a^2 + b^2 - c^2 ) / (2ab) )" }, { "code": null, "e": 25701, "s": 25531, "text": "In trigonometry, the law of cosines (also known as the cosine formula or cosine rule) relates the lengths of the sides of a triangle to the cosine of one of its angles. " }, { "code": null, "e": 25850, "s": 25701, "text": "First, calculate the length of all the sides. \nThen apply above formula to get all angles in \nradian. Then convert angles from radian into \ndegrees." }, { "code": null, "e": 25892, "s": 25850, "text": "Below is implementation of above steps. " }, { "code": null, "e": 25896, "s": 25892, "text": "C++" }, { "code": null, "e": 25901, "s": 25896, "text": "Java" }, { "code": null, "e": 25909, "s": 25901, "text": "Python3" }, { "code": null, "e": 25912, "s": 25909, "text": "C#" }, { "code": "// Code to find all three angles// of a triangle given coordinate// of all three vertices#include <iostream>#include <utility> // for pair#include <cmath> // for math functionsusing namespace std; #define PI 3.1415926535 // returns square of distance b/w two pointsint lengthSquare(pair<int,int> X, pair<int,int> Y){ int xDiff = X.first - Y.first; int yDiff = X.second - Y.second; return xDiff*xDiff + yDiff*yDiff;} void printAngle(pair<int,int> A, pair<int,int> B, pair<int,int> C){ // Square of lengths be a2, b2, c2 int a2 = lengthSquare(B,C); int b2 = lengthSquare(A,C); int c2 = lengthSquare(A,B); // length of sides be a, b, c float a = sqrt(a2); float b = sqrt(b2); float c = sqrt(c2); // From Cosine law float alpha = acos((b2 + c2 - a2)/(2*b*c)); float beta = acos((a2 + c2 - b2)/(2*a*c)); float gamma = acos((a2 + b2 - c2)/(2*a*b)); // Converting to degree alpha = alpha * 180 / PI; beta = beta * 180 / PI; gamma = gamma * 180 / PI; // printing all the angles cout << \"alpha : \" << alpha << endl; cout << \"beta : \" << beta << endl; cout << \"gamma : \" << gamma << endl;} // Driver codeint main(){ pair<int,int> A = make_pair(0,0); pair<int,int> B = make_pair(0,1); pair<int,int> C = make_pair(1,0); printAngle(A,B,C); return 0;}", "e": 27255, "s": 25912, "text": null }, { "code": "// Java Code to find all three angles// of a triangle given coordinate// of all three vertices import java.awt.Point;import static java.lang.Math.PI;import static java.lang.Math.sqrt;import static java.lang.Math.acos; class Test{ // returns square of distance b/w two points static int lengthSquare(Point p1, Point p2) { int xDiff = p1.x- p2.x; int yDiff = p1.y- p2.y; return xDiff*xDiff + yDiff*yDiff; } static void printAngle(Point A, Point B, Point C) { // Square of lengths be a2, b2, c2 int a2 = lengthSquare(B,C); int b2 = lengthSquare(A,C); int c2 = lengthSquare(A,B); // length of sides be a, b, c float a = (float)sqrt(a2); float b = (float)sqrt(b2); float c = (float)sqrt(c2); // From Cosine law float alpha = (float) acos((b2 + c2 - a2)/(2*b*c)); float betta = (float) acos((a2 + c2 - b2)/(2*a*c)); float gamma = (float) acos((a2 + b2 - c2)/(2*a*b)); // Converting to degree alpha = (float) (alpha * 180 / PI); betta = (float) (betta * 180 / PI); gamma = (float) (gamma * 180 / PI); // printing all the angles System.out.println(\"alpha : \" + alpha); System.out.println(\"betta : \" + betta); System.out.println(\"gamma : \" + gamma); } // Driver method public static void main(String[] args) { Point A = new Point(0,0); Point B = new Point(0,1); Point C = new Point(1,0); printAngle(A,B,C); }}", "e": 28745, "s": 27255, "text": null }, { "code": "# Python3 code to find all three angles# of a triangle given coordinate# of all three verticesimport math # returns square of distance b/w two pointsdef lengthSquare(X, Y): xDiff = X[0] - Y[0] yDiff = X[1] - Y[1] return xDiff * xDiff + yDiff * yDiff def printAngle(A, B, C): # Square of lengths be a2, b2, c2 a2 = lengthSquare(B, C) b2 = lengthSquare(A, C) c2 = lengthSquare(A, B) # length of sides be a, b, c a = math.sqrt(a2); b = math.sqrt(b2); c = math.sqrt(c2); # From Cosine law alpha = math.acos((b2 + c2 - a2) / (2 * b * c)); betta = math.acos((a2 + c2 - b2) / (2 * a * c)); gamma = math.acos((a2 + b2 - c2) / (2 * a * b)); # Converting to degree alpha = alpha * 180 / math.pi; betta = betta * 180 / math.pi; gamma = gamma * 180 / math.pi; # printing all the angles print(\"alpha : %f\" %(alpha)) print(\"betta : %f\" %(betta)) print(\"gamma : %f\" %(gamma)) # Driver codeA = (0, 0)B = (0, 1)C = (1, 0) printAngle(A, B, C); # This code is contributed# by ApurvaRaj", "e": 29874, "s": 28745, "text": null }, { "code": "// C# Code to find all three angles// of a triangle given coordinate// of all three verticesusing System; class GFG{ class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } // returns square of distance b/w two points static int lengthSquare(Point p1, Point p2) { int xDiff = p1.x - p2.x; int yDiff = p1.y - p2.y; return xDiff * xDiff + yDiff * yDiff; } static void printAngle(Point A, Point B, Point C) { // Square of lengths be a2, b2, c2 int a2 = lengthSquare(B, C); int b2 = lengthSquare(A, C); int c2 = lengthSquare(A, B); // length of sides be a, b, c float a = (float)Math.Sqrt(a2); float b = (float)Math.Sqrt(b2); float c = (float)Math.Sqrt(c2); // From Cosine law float alpha = (float) Math.Acos((b2 + c2 - a2) / (2 * b * c)); float betta = (float) Math.Acos((a2 + c2 - b2) / (2 * a * c)); float gamma = (float) Math.Acos((a2 + b2 - c2) / (2 * a * b)); // Converting to degree alpha = (float) (alpha * 180 / Math.PI); betta = (float) (betta * 180 / Math.PI); gamma = (float) (gamma * 180 / Math.PI); // printing all the angles Console.WriteLine(\"alpha : \" + alpha); Console.WriteLine(\"betta : \" + betta); Console.WriteLine(\"gamma : \" + gamma); } // Driver Code public static void Main(String[] args) { Point A = new Point(0, 0); Point B = new Point(0, 1); Point C = new Point(1, 0); printAngle(A, B, C); }} // This code is contributed by Rajput-Ji", "e": 31730, "s": 29874, "text": null }, { "code": null, "e": 31740, "s": 31730, "text": "Output: " }, { "code": null, "e": 31772, "s": 31740, "text": "alpha : 90\nbeta : 45\ngamma : 45" }, { "code": null, "e": 32252, "s": 31772, "text": "Reference : https://en.wikipedia.org/wiki/Law_of_cosinesThis article is contributed by Pratik Chhajer . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32266, "s": 32252, "text": "MohitDhariwal" }, { "code": null, "e": 32275, "s": 32266, "text": "Shivam_k" }, { "code": null, "e": 32285, "s": 32275, "text": "Rajput-Ji" }, { "code": null, "e": 32295, "s": 32285, "text": "ApurvaRaj" }, { "code": null, "e": 32304, "s": 32295, "text": "rkbhola5" }, { "code": null, "e": 32313, "s": 32304, "text": "triangle" }, { "code": null, "e": 32323, "s": 32313, "text": "Geometric" }, { "code": null, "e": 32342, "s": 32323, "text": "School Programming" }, { "code": null, "e": 32352, "s": 32342, "text": "Geometric" }, { "code": null, "e": 32450, "s": 32352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32499, "s": 32450, "text": "Program for distance between two points on earth" }, { "code": null, "e": 32552, "s": 32499, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 32586, "s": 32552, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 32644, "s": 32586, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 32693, "s": 32644, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 32711, "s": 32693, "text": "Python Dictionary" }, { "code": null, "e": 32727, "s": 32711, "text": "Arrays in C/C++" }, { "code": null, "e": 32746, "s": 32727, "text": "Inheritance in C++" }, { "code": null, "e": 32771, "s": 32746, "text": "Reverse a string in Java" } ]
Appending suffix to numbers in JavaScript
We are required to write a JavaScript function that takes in a number, num, as the first and the only argument. The task of our function is to append ‘st’, ‘nd’, ‘rd’, ‘th’ to the number according to the following rules: st is used with numbers ending in 1 (e.g. 1st, pronounced first) nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second) rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third) As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use - th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth) th is used for all other numbers (e.g. 9th, pronounced ninth). For example, if the input to the function is − Input const num = 4513; Output const output = '4513th'; Output Explanation Even though 4513 ends with three, 13 is an exception case that must be appended with th Following is the code − Live Demo const num = 4513; const appendText = (num = 1) => { let suffix = "th"; if (num == 0) suffix = ""; if (num % 10 == 1 && num % 100 != 11) suffix = "st"; if (num % 10 == 2 && num % 100 != 12) suffix = "nd"; if (num % 10 == 3 && num % 100 != 13) suffix = "rd"; return num + suffix; }; console.log(appendText(num)); 4513th
[ { "code": null, "e": 1174, "s": 1062, "text": "We are required to write a JavaScript function that takes in a number, num, as the first and the\nonly argument." }, { "code": null, "e": 1283, "s": 1174, "text": "The task of our function is to append ‘st’, ‘nd’, ‘rd’, ‘th’ to the number according to the following\nrules:" }, { "code": null, "e": 1348, "s": 1283, "text": "st is used with numbers ending in 1 (e.g. 1st, pronounced first)" }, { "code": null, "e": 1422, "s": 1348, "text": "nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)" }, { "code": null, "e": 1495, "s": 1422, "text": "rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)" }, { "code": null, "e": 1666, "s": 1495, "text": "As an exception to the above rules, all the \"teen\" numbers ending with 11, 12 or 13 use -\nth (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth)" }, { "code": null, "e": 1729, "s": 1666, "text": "th is used for all other numbers (e.g. 9th, pronounced ninth)." }, { "code": null, "e": 1776, "s": 1729, "text": "For example, if the input to the function is −" }, { "code": null, "e": 1782, "s": 1776, "text": "Input" }, { "code": null, "e": 1800, "s": 1782, "text": "const num = 4513;" }, { "code": null, "e": 1807, "s": 1800, "text": "Output" }, { "code": null, "e": 1832, "s": 1807, "text": "const output = '4513th';" }, { "code": null, "e": 1851, "s": 1832, "text": "Output Explanation" }, { "code": null, "e": 1939, "s": 1851, "text": "Even though 4513 ends with three, 13 is an exception case that must be appended with th" }, { "code": null, "e": 1963, "s": 1939, "text": "Following is the code −" }, { "code": null, "e": 1974, "s": 1963, "text": " Live Demo" }, { "code": null, "e": 2304, "s": 1974, "text": "const num = 4513;\nconst appendText = (num = 1) => {\n let suffix = \"th\";\n if (num == 0) suffix = \"\";\n if (num % 10 == 1 && num % 100 != 11) suffix = \"st\";\n if (num % 10 == 2 && num % 100 != 12) suffix = \"nd\";\n if (num % 10 == 3 && num % 100 != 13) suffix = \"rd\";\n\n return num + suffix;\n};\nconsole.log(appendText(num));" }, { "code": null, "e": 2311, "s": 2304, "text": "4513th" } ]
Using QuickUMLS for biomedical named entity recognition | Towards Data Science
At the outset of any new R&D project, I look to match the most appropriate solution to the problem at hand. While there are some very exciting large models available, one of my biggest concerns is bringing the solution into production without compromising on the outcomes I’d like to support. A question I had recently was if a simple string-matching method — coupled with some simple optimizations — could compete with a supervised model on a biomedical Named Entity Recognition (NER) task. I have put these two methods in a head-to-head test. On the string-matching system side, I leveraged the QuickUMLS classifier. QuickUMLS [1] — as a string-matching system — takes a string as input (e.g., a paper or abstract of a paper containing medical concepts), and outputs all spans from the document that match Unified Medical Language System (UMLS) concepts. These concepts can then be re-used in other settings, or as input to other machine learning systems. For this reason, QuickUMLS can be seen as a handy pre-processing tool to get relevant concepts from clinical and biomedical text. In this blog post, however, we will focus on using QuickUMLS as a classifier on the challenging MedMentions dataset. [2] Before we dive into the problem we’re trying to solve, it is useful to describe some idiosyncrasies of biomedical NER. In general, the problem of NER is to find named entities (e.g., notable locations, persons, organizations, etc.) in text. As you can probably surmise, many of these entities can be found through context. For example, in a sentence such as: “Sam and Drew went to the Colosseum”, we can infer that the Colosseum is a location because you generally go to locations. Similarly, we can also surmise that “Sam” is a proper name because words that are in the subject position of “to go” that aren’t commonplace words tend to be names. In contrast, biomedical NER is about finding and disambiguating biomedical terms of interest from text, such as diseases, drug names, but also generic terms such as “hospital”, “ICU ward”, or “alcohol”. This is an important distinction, since there is very little contextual information that determines whether a given word is of medical importance. To give a bit of a loaded example, consider the word “alcohol” in the sentence “the patient drank a lot of alcohol”. The severity of this finding depends on whether it refers to alcohol such as beer or wine, or pure alcohol, such as rubbing alcohol. For a more complete overview of the state of the art of biomedical NER, see this blog post by my colleague at Slimmer AI, Sybren Jansen. Knowing which concepts are of medical importance is difficult to learn without a large amount of training data, which is not typically readily available. Many systems, therefore, use the Unified Medical Language System (UMLS), which is a large ontology containing many different concepts together with their string representations and other information. Please note that a concept is distinct from a string because many strings can refer to more than one concept. The string “alcohol” for example, can refer to rubbing alcohol or to alcoholic drinks. In UMLS, each concept is described by a Concept Unique Identifier (CUI), which is a symbolic ID for any given unique concept, and a Semantic Type (STY), which is a family identifier that groups concepts with similar characteristics. One reason the UMLS is useful, but also challenging to work with, is its sheer size; the 2020AB version of the UMLS, which is the one we will use in what follows, has over 3 million unique English concepts. It is unlikely that a sizable portion of these concepts will show up, even in large, annotated datasets. One such dataset is MedMentions. It consists of 4,392 Pubmed papers (titles and abstracts) from 2016; annotated with 352K concepts (CUI IDs) and semantic types from the UMLS. The papers have about 34K annotated unique concepts, which is still only about 1% of the total number of concepts in the UMLS. This shows that annotating UMLS mentions is a challenging task that cannot necessarily be solved using supervised machine learning. Of particular interest in this regard is that the MedMentions corpus includes CUIs in the test set that do not occur in training. In general, however, this task is still approached as a supervised machine learning task by using the semantic types of the UMLS concepts as labels. As UMLS has 127 semantic types, this still leads to a large label space. The MedMentions dataset also has a smaller version, the st21pv dataset, which consists of the same documents as the regular dataset, but with only the 21 most frequent semantic types annotated. A semi-Markov baseline gets about 45.3 F-score on the entity level. [2] Other approaches, including BlueBERT [3] and BioBERT [4] were tested, and improved the score to 56.3 using exact matching on the entity level. [5] Note that all these approaches are supervised, and thus rely on a certain amount of overlap between the train and test set in terms of concepts. If a concept or label has never been seen during training, a supervised machine learning approach will have a challenging time classifying it correctly. In what follows, we will use the semantic types of the MedMentions dataset as labels. In contrast to BERT, QuickUMLS is inherently an unsupervised method, which means that it doesn’t rely on training data. More accurately, QuickUMLS is a knowledge-based method. This means that the model, instead of having parameters that tell it what to predict, relies on an external knowledge base to predict labels. This implies two things: The quality of the model is limited by the quality of the knowledge base. The model cannot predict things that the knowledge base does not contain.The model can generalize beyond annotated data. A supervised model that has not seen a specific label during training cannot predict those things accurately, in general. An exception to this rule is zero-shot learning methods. The quality of the model is limited by the quality of the knowledge base. The model cannot predict things that the knowledge base does not contain. The model can generalize beyond annotated data. A supervised model that has not seen a specific label during training cannot predict those things accurately, in general. An exception to this rule is zero-shot learning methods. From these two facts, we argue that knowledge-based methods are a good fit for the MedMentions dataset. Regarding the first point, the MedMentions database was annotated using UMLS concepts, so the mapping between the knowledge base and the dataset is an exact mapping. Regarding the second point, the MedMentions dataset contains concepts in test that are not present in the training set. QuickUMLS, as a model, is simple. It first parses the text using a parser, spacy. The model then selects word ngrams, i.e., sequential sequences of words, based on part of speech tag patterns and stopword lists. In brief, this means that the model discards certain word ngrams if they contain unwanted tokens and punctuation marks. Details of these rules can be found in the original paper. [1] After selecting all word ngram candidates, the whole UMLS database is queried for concepts that partially match the word ngrams. Because exact matching on such a huge database is inefficient and difficult, the authors perform approximate string matching using simstring. [6] When given a text, QuickUMLS thus returns a list of concepts in the UMLS, together with their similarity to the query string and other associated information. For example, the text: “The patient had a hemorrhage” returns the following candidates, using a (default) string similarity threshold of 0.7: For the word patient: {‘term’: ‘Inpatient’, ‘cui’: ‘C1548438’, ‘similarity’: 0.71, ‘semtypes’: {‘T078’}, ‘preferred’: 1},{‘term’: ‘Inpatient’, ‘cui’: ‘C1549404’, ‘similarity’: 0.71, ‘semtypes’: {‘T078’}, ‘preferred’: 1},{‘term’: ‘Inpatient’, ‘cui’: ‘C1555324’, ‘similarity’: 0.71, ‘semtypes’: {‘T058’}, ‘preferred’: 1},{‘term’: ‘*^patient’, ‘cui’: ‘C0030705’, ‘similarity’: 0.71, ‘semtypes’: {‘T101’}, ‘preferred’: 1},{‘term’: ‘patient’, ‘cui’: ‘C0030705’, ‘similarity’: 1.0, ‘semtypes’: {‘T101’}, ‘preferred’: 0},{‘term’: ‘inpatient’, ‘cui’: ‘C0021562’, ‘similarity’: 0.71, ‘semtypes’: {‘T101’}, ‘preferred’: 0} For the word hemorrhage: {‘term’: ‘No hemorrhage’, ‘cui’: ‘C1861265’, ‘similarity’: 0.72, ‘semtypes’: {‘T033’}, ‘preferred’: 1},{‘term’: ‘hemorrhagin’, ‘cui’: ‘C0121419’, ‘similarity’: 0.7, ‘semtypes’: {‘T116’, ‘T126’}, ‘preferred’: 1},{‘term’: ‘hemorrhagic’, ‘cui’: ‘C0333275’, ‘similarity’: 0.7, ‘semtypes’: {‘T080’}, ‘preferred’: 1},{‘term’: ‘hemorrhage’, ‘cui’: ‘C0019080’, ‘similarity’: 1.0, ‘semtypes’: {‘T046’}, ‘preferred’: 0},{‘term’: ‘GI hemorrhage’, ‘cui’: ‘C0017181’, ‘similarity’: 0.72, ‘semtypes’: {‘T046’}, ‘preferred’: 0},{‘term’: ‘Hemorrhages’, ‘cui’: ‘C0019080’, ‘similarity’: 0.7, ‘semtypes’: {‘T046’}, ‘preferred’: 0} As you can see, the word “patient” has three matches with the correct semantic type (T101), and two matches with the correct concept (C0030705). The word hemorrhage also has superfluous matches, including the concept for “No hemorrhage”. Nevertheless, the highest ranked candidate, if we go by similarity, is the correct one in both cases. In a default application of QuickUMLS, we only keep preferred terms, i.e., terms for which preferred is 1, and then sort by similarity. We then take the semantic type (i.e., semtype) of the highest ranked candidate as the prediction- we call this the baseline model. We used seqeval with a strict matching paradigm which is comparable to previous work. [5] ╔═══╦══════╦═══════╗║ ║ BERT ║ QUMLS ║╠═══╬══════╬═══════╣║ P ║ .53 ║ .27 ║║ R ║ .58 ║ .36 ║║ F ║ .56 ║ .31 ║╚═══╩══════╩═══════╝Table 1: baseline performance Not too impressive, right? Unfortunately, the baseline suffers from a bad case of not being optimized for specific task. As such, let’s optimize the baseline using simple heuristics. There are a couple of ways to improve QuickUMLS beyond its initial performance. First, we note that the standard parser used by QuickUMLS is the default spacy model, i.e., en_core_web_sm. Given that we are dealing with biomedical text, we are better served by using a biomedical language model. In our case, we swapped out the model to a scispacy [7] model, en_core_sci_sm. This already improves performance a little bit, at no cost. ╔═══╦══════╦═══════╦═════════╗║ ║ BERT ║ QUMLS ║ + Spacy ║╠═══╬══════╬═══════╬═════════╣║ P ║ .53 ║ .27 ║ .29 ║║ R ║ .58 ║ .36 ║ .37 ║║ F ║ .56 ║ .31 ║ .32 ║╚═══╩══════╩═══════╩═════════╝Table 2: adding scispacy Other improvements can be gained by using some information from the training corpus. While this does turn QuickUMLS from a purely unsupervised method into a supervised one, there is still no dependence on a large body of specific annotations. In other words, there is no explicit “fit” step on a specific corpus: the improvements we are going to make can also be estimated using a small set of annotations or prior knowledge by a physician. The default settings for QuickUMLS, include a threshold of 0.7, and a set of metrics. The metric determines how the string similarity is counted, and can be set to “Jaccard”, “cosine”, “overlap” and “dice”. We perform a grid search over the metric and different thresholds. The best results ended up being a threshold of .99, meaning we only perform exact matches using SimString, and the “Jaccard” metric, which outperforms all other options in terms of speed and score. As you can see, we are getting closer and closer to the performance of BERT. ╔═══╦══════╦═══════╦═════════╦════════╗║ ║ BERT ║ QUMLS ║ + Spacy ║ + Grid ║╠═══╬══════╬═══════╬═════════╬════════╣║ P ║ .53 ║ .27 ║ .29 ║ .37 ║║ R ║ .58 ║ .36 ║ .37 ║ .37 ║║ F ║ .56 ║ .31 ║ .32 ║ .37 ║╚═══╩══════╩═══════╩═════════╩════════╝Table 3: Grid searching over settings Recall that above, we simply selected the best matching candidate based on whether it was a preferred string and their similarity. However, in many cases different concepts will have the same string representation, such as in the aforementioned “alcohol” example. This makes it difficult to choose an optimal candidate without having a disambiguation model, which requires context, and again turns the learning problem into a supervised one, or at least one that requires examples of contexts in which terms occur. One easy way out of this conundrum is to consider that, all else being equal, some semantic types are simply more likely, and therefore more likely in the given corpus. This is also called a prior. In our case, we estimate the class prior through the training set, as you would do in the well-known naive bayes classifier. Then, for each semantic type we extract for each set of candidates, we take the maximum similarity, and then multiply it with the prior. In neural network terms, you can think of this of max pooling on the class level. This also means we ignore the preferred term status of any candidates. ╔═══╦══════╦═══════╦═════════╦════════╦══════════╗║ ║ BERT ║ QUMLS ║ + Spacy ║ + Grid ║ + Priors ║╠═══╬══════╬═══════╬═════════╬════════╬══════════╣║ P ║ .53 ║ .27 ║ .29 ║ .37 ║ .39 ║║ R ║ .58 ║ .36 ║ .37 ║ .37 ║ .39 ║║ F ║ .56 ║ .31 ║ .32 ║ .37 ║ .39 ║╚═══╩══════╩═══════╩═════════╩════════╩══════════╝Table 4: adding priors Unfortunately, this is as far as we could get using the simple system in QuickUMLS. Given that we ended up using a threshold of .99 means that we do not use the approximate matching functionality of QuickUMLS at all. Removing the approximate matching would also speed up the entire system immensely, since most of the time of the algorithm is now spent on the matching in QuickUMLS. As we are doing a Named Entity Recognition task, there are a couple of classes of errors we can make. First off, we can extract the right span, but the wrong class. This happens when we find a correct term, but give it the wrong label, e.g., we think “alcohol” refers to the drink when it refers to the disinfectant. Second, we can also extract the span partially, but still match the right label. In this case, we can think of the match as a “partial match”. In our scoring, we only counted exact matches as correct. An example of this is extracting “mild anesthetic” when the gold standard is “anesthetic”. We can also miss spans completely, e.g., because UMLS does not contain the term, or extract spans that do not correspond to gold standard mentions. The figure below shows what kinds of these errors our system makes: This shows that the errors QuickUMLS makes do not belong to one specific category. It extracts too many items, but, when it extracts items, it also often assigns the wrong label to those items. This shows that QuickUMLS could be employed as a pre-extraction system, after which a disambiguation system could be used to assign the correct label. As you can see from the results, an off-the-shelf terminology extraction system can be used as an efficient and effective NER system without training. Getting training data for specific use cases can often be a time-consuming process, hampering R&D speed. The QuickUMLS classifier we built shows that we can go a long way with very few training examples. And by being smart about the way we apply our resources, we have saved lot of time in the R&D process for biomedical NER. Our modified QuickUMLS classifier can be tried out here on github. The benefit of this approach can mean a solution robust enough for the outcome, simple to develop and test, and small enough for easy implementation into product development. [1] L. Soldaini, and N. Goharian. Quickumls: a fast, unsupervised approach for medical concept extraction, (2016), MedIR workshop, SIGIR [2] S. Mohan, and D. Li, Medmentions: a large biomedical corpus annotated with UMLS concepts, (2019), arXiv preprint arXiv:1902.09476 [3] Y. Peng, Q. Chen, and Z. Lu, An empirical study of multi-task learning on BERT for biomedical text mining, (2020), arXiv preprint arXiv:2005.02799 [4] J. Lee, W. Yoon, S. Kim, D. Kim, S. Kim, C.H. So, and J. Kang, BioBERT: a pre-trained biomedical language representation model for biomedical text mining, (2020), Bioinformatics, 36(4) [5] K.C. Fraser, I. Nejadgholi, B. De Bruijn, M. Li, A. LaPlante and K.Z.E. Abidine, Extracting UMLS concepts from medical text using general and domain-specific deep learning models, (2019), arXiv preprint arXiv:1910.01274. [6] N. Okazaki, and J.I. Tsujii, Simple and efficient algorithm for approximate dictionary matching, (2010, August), In Proceedings of the 23rd International Conference on Computational Linguistics (Coling 2010) [7] M. Neumann, D. King, I. Beltagy, and W. Ammar, Scispacy: Fast and robust models for biomedical natural language processing, (2019), arXiv preprint arXiv:1902.07669.
[ { "code": null, "e": 717, "s": 172, "text": "At the outset of any new R&D project, I look to match the most appropriate solution to the problem at hand. While there are some very exciting large models available, one of my biggest concerns is bringing the solution into production without compromising on the outcomes I’d like to support. A question I had recently was if a simple string-matching method — coupled with some simple optimizations — could compete with a supervised model on a biomedical Named Entity Recognition (NER) task. I have put these two methods in a head-to-head test." }, { "code": null, "e": 1381, "s": 717, "text": "On the string-matching system side, I leveraged the QuickUMLS classifier. QuickUMLS [1] — as a string-matching system — takes a string as input (e.g., a paper or abstract of a paper containing medical concepts), and outputs all spans from the document that match Unified Medical Language System (UMLS) concepts. These concepts can then be re-used in other settings, or as input to other machine learning systems. For this reason, QuickUMLS can be seen as a handy pre-processing tool to get relevant concepts from clinical and biomedical text. In this blog post, however, we will focus on using QuickUMLS as a classifier on the challenging MedMentions dataset. [2]" }, { "code": null, "e": 2028, "s": 1381, "text": "Before we dive into the problem we’re trying to solve, it is useful to describe some idiosyncrasies of biomedical NER. In general, the problem of NER is to find named entities (e.g., notable locations, persons, organizations, etc.) in text. As you can probably surmise, many of these entities can be found through context. For example, in a sentence such as: “Sam and Drew went to the Colosseum”, we can infer that the Colosseum is a location because you generally go to locations. Similarly, we can also surmise that “Sam” is a proper name because words that are in the subject position of “to go” that aren’t commonplace words tend to be names." }, { "code": null, "e": 2765, "s": 2028, "text": "In contrast, biomedical NER is about finding and disambiguating biomedical terms of interest from text, such as diseases, drug names, but also generic terms such as “hospital”, “ICU ward”, or “alcohol”. This is an important distinction, since there is very little contextual information that determines whether a given word is of medical importance. To give a bit of a loaded example, consider the word “alcohol” in the sentence “the patient drank a lot of alcohol”. The severity of this finding depends on whether it refers to alcohol such as beer or wine, or pure alcohol, such as rubbing alcohol. For a more complete overview of the state of the art of biomedical NER, see this blog post by my colleague at Slimmer AI, Sybren Jansen." }, { "code": null, "e": 3316, "s": 2765, "text": "Knowing which concepts are of medical importance is difficult to learn without a large amount of training data, which is not typically readily available. Many systems, therefore, use the Unified Medical Language System (UMLS), which is a large ontology containing many different concepts together with their string representations and other information. Please note that a concept is distinct from a string because many strings can refer to more than one concept. The string “alcohol” for example, can refer to rubbing alcohol or to alcoholic drinks." }, { "code": null, "e": 3861, "s": 3316, "text": "In UMLS, each concept is described by a Concept Unique Identifier (CUI), which is a symbolic ID for any given unique concept, and a Semantic Type (STY), which is a family identifier that groups concepts with similar characteristics. One reason the UMLS is useful, but also challenging to work with, is its sheer size; the 2020AB version of the UMLS, which is the one we will use in what follows, has over 3 million unique English concepts. It is unlikely that a sizable portion of these concepts will show up, even in large, annotated datasets." }, { "code": null, "e": 4295, "s": 3861, "text": "One such dataset is MedMentions. It consists of 4,392 Pubmed papers (titles and abstracts) from 2016; annotated with 352K concepts (CUI IDs) and semantic types from the UMLS. The papers have about 34K annotated unique concepts, which is still only about 1% of the total number of concepts in the UMLS. This shows that annotating UMLS mentions is a challenging task that cannot necessarily be solved using supervised machine learning." }, { "code": null, "e": 4841, "s": 4295, "text": "Of particular interest in this regard is that the MedMentions corpus includes CUIs in the test set that do not occur in training. In general, however, this task is still approached as a supervised machine learning task by using the semantic types of the UMLS concepts as labels. As UMLS has 127 semantic types, this still leads to a large label space. The MedMentions dataset also has a smaller version, the st21pv dataset, which consists of the same documents as the regular dataset, but with only the 21 most frequent semantic types annotated." }, { "code": null, "e": 5444, "s": 4841, "text": "A semi-Markov baseline gets about 45.3 F-score on the entity level. [2] Other approaches, including BlueBERT [3] and BioBERT [4] were tested, and improved the score to 56.3 using exact matching on the entity level. [5] Note that all these approaches are supervised, and thus rely on a certain amount of overlap between the train and test set in terms of concepts. If a concept or label has never been seen during training, a supervised machine learning approach will have a challenging time classifying it correctly. In what follows, we will use the semantic types of the MedMentions dataset as labels." }, { "code": null, "e": 5787, "s": 5444, "text": "In contrast to BERT, QuickUMLS is inherently an unsupervised method, which means that it doesn’t rely on training data. More accurately, QuickUMLS is a knowledge-based method. This means that the model, instead of having parameters that tell it what to predict, relies on an external knowledge base to predict labels. This implies two things:" }, { "code": null, "e": 6161, "s": 5787, "text": "The quality of the model is limited by the quality of the knowledge base. The model cannot predict things that the knowledge base does not contain.The model can generalize beyond annotated data. A supervised model that has not seen a specific label during training cannot predict those things accurately, in general. An exception to this rule is zero-shot learning methods." }, { "code": null, "e": 6309, "s": 6161, "text": "The quality of the model is limited by the quality of the knowledge base. The model cannot predict things that the knowledge base does not contain." }, { "code": null, "e": 6536, "s": 6309, "text": "The model can generalize beyond annotated data. A supervised model that has not seen a specific label during training cannot predict those things accurately, in general. An exception to this rule is zero-shot learning methods." }, { "code": null, "e": 6926, "s": 6536, "text": "From these two facts, we argue that knowledge-based methods are a good fit for the MedMentions dataset. Regarding the first point, the MedMentions database was annotated using UMLS concepts, so the mapping between the knowledge base and the dataset is an exact mapping. Regarding the second point, the MedMentions dataset contains concepts in test that are not present in the training set." }, { "code": null, "e": 7897, "s": 6926, "text": "QuickUMLS, as a model, is simple. It first parses the text using a parser, spacy. The model then selects word ngrams, i.e., sequential sequences of words, based on part of speech tag patterns and stopword lists. In brief, this means that the model discards certain word ngrams if they contain unwanted tokens and punctuation marks. Details of these rules can be found in the original paper. [1] After selecting all word ngram candidates, the whole UMLS database is queried for concepts that partially match the word ngrams. Because exact matching on such a huge database is inefficient and difficult, the authors perform approximate string matching using simstring. [6] When given a text, QuickUMLS thus returns a list of concepts in the UMLS, together with their similarity to the query string and other associated information. For example, the text: “The patient had a hemorrhage” returns the following candidates, using a (default) string similarity threshold of 0.7:" }, { "code": null, "e": 7919, "s": 7897, "text": "For the word patient:" }, { "code": null, "e": 8510, "s": 7919, "text": "{‘term’: ‘Inpatient’, ‘cui’: ‘C1548438’, ‘similarity’: 0.71, ‘semtypes’: {‘T078’}, ‘preferred’: 1},{‘term’: ‘Inpatient’, ‘cui’: ‘C1549404’, ‘similarity’: 0.71, ‘semtypes’: {‘T078’}, ‘preferred’: 1},{‘term’: ‘Inpatient’, ‘cui’: ‘C1555324’, ‘similarity’: 0.71, ‘semtypes’: {‘T058’}, ‘preferred’: 1},{‘term’: ‘*^patient’, ‘cui’: ‘C0030705’, ‘similarity’: 0.71, ‘semtypes’: {‘T101’}, ‘preferred’: 1},{‘term’: ‘patient’, ‘cui’: ‘C0030705’, ‘similarity’: 1.0, ‘semtypes’: {‘T101’}, ‘preferred’: 0},{‘term’: ‘inpatient’, ‘cui’: ‘C0021562’, ‘similarity’: 0.71, ‘semtypes’: {‘T101’}, ‘preferred’: 0}" }, { "code": null, "e": 8535, "s": 8510, "text": "For the word hemorrhage:" }, { "code": null, "e": 9148, "s": 8535, "text": "{‘term’: ‘No hemorrhage’, ‘cui’: ‘C1861265’, ‘similarity’: 0.72, ‘semtypes’: {‘T033’}, ‘preferred’: 1},{‘term’: ‘hemorrhagin’, ‘cui’: ‘C0121419’, ‘similarity’: 0.7, ‘semtypes’: {‘T116’, ‘T126’}, ‘preferred’: 1},{‘term’: ‘hemorrhagic’, ‘cui’: ‘C0333275’, ‘similarity’: 0.7, ‘semtypes’: {‘T080’}, ‘preferred’: 1},{‘term’: ‘hemorrhage’, ‘cui’: ‘C0019080’, ‘similarity’: 1.0, ‘semtypes’: {‘T046’}, ‘preferred’: 0},{‘term’: ‘GI hemorrhage’, ‘cui’: ‘C0017181’, ‘similarity’: 0.72, ‘semtypes’: {‘T046’}, ‘preferred’: 0},{‘term’: ‘Hemorrhages’, ‘cui’: ‘C0019080’, ‘similarity’: 0.7, ‘semtypes’: {‘T046’}, ‘preferred’: 0}" }, { "code": null, "e": 9488, "s": 9148, "text": "As you can see, the word “patient” has three matches with the correct semantic type (T101), and two matches with the correct concept (C0030705). The word hemorrhage also has superfluous matches, including the concept for “No hemorrhage”. Nevertheless, the highest ranked candidate, if we go by similarity, is the correct one in both cases." }, { "code": null, "e": 9845, "s": 9488, "text": "In a default application of QuickUMLS, we only keep preferred terms, i.e., terms for which preferred is 1, and then sort by similarity. We then take the semantic type (i.e., semtype) of the highest ranked candidate as the prediction- we call this the baseline model. We used seqeval with a strict matching paradigm which is comparable to previous work. [5]" }, { "code": null, "e": 10015, "s": 9845, "text": "╔═══╦══════╦═══════╗║ ║ BERT ║ QUMLS ║╠═══╬══════╬═══════╣║ P ║ .53 ║ .27 ║║ R ║ .58 ║ .36 ║║ F ║ .56 ║ .31 ║╚═══╩══════╩═══════╝Table 1: baseline performance" }, { "code": null, "e": 10198, "s": 10015, "text": "Not too impressive, right? Unfortunately, the baseline suffers from a bad case of not being optimized for specific task. As such, let’s optimize the baseline using simple heuristics." }, { "code": null, "e": 10632, "s": 10198, "text": "There are a couple of ways to improve QuickUMLS beyond its initial performance. First, we note that the standard parser used by QuickUMLS is the default spacy model, i.e., en_core_web_sm. Given that we are dealing with biomedical text, we are better served by using a biomedical language model. In our case, we swapped out the model to a scispacy [7] model, en_core_sci_sm. This already improves performance a little bit, at no cost." }, { "code": null, "e": 10867, "s": 10632, "text": "╔═══╦══════╦═══════╦═════════╗║ ║ BERT ║ QUMLS ║ + Spacy ║╠═══╬══════╬═══════╬═════════╣║ P ║ .53 ║ .27 ║ .29 ║║ R ║ .58 ║ .36 ║ .37 ║║ F ║ .56 ║ .31 ║ .32 ║╚═══╩══════╩═══════╩═════════╝Table 2: adding scispacy" }, { "code": null, "e": 11308, "s": 10867, "text": "Other improvements can be gained by using some information from the training corpus. While this does turn QuickUMLS from a purely unsupervised method into a supervised one, there is still no dependence on a large body of specific annotations. In other words, there is no explicit “fit” step on a specific corpus: the improvements we are going to make can also be estimated using a small set of annotations or prior knowledge by a physician." }, { "code": null, "e": 11857, "s": 11308, "text": "The default settings for QuickUMLS, include a threshold of 0.7, and a set of metrics. The metric determines how the string similarity is counted, and can be set to “Jaccard”, “cosine”, “overlap” and “dice”. We perform a grid search over the metric and different thresholds. The best results ended up being a threshold of .99, meaning we only perform exact matches using SimString, and the “Jaccard” metric, which outperforms all other options in terms of speed and score. As you can see, we are getting closer and closer to the performance of BERT." }, { "code": null, "e": 12168, "s": 11857, "text": "╔═══╦══════╦═══════╦═════════╦════════╗║ ║ BERT ║ QUMLS ║ + Spacy ║ + Grid ║╠═══╬══════╬═══════╬═════════╬════════╣║ P ║ .53 ║ .27 ║ .29 ║ .37 ║║ R ║ .58 ║ .36 ║ .37 ║ .37 ║║ F ║ .56 ║ .31 ║ .32 ║ .37 ║╚═══╩══════╩═══════╩═════════╩════════╝Table 3: Grid searching over settings" }, { "code": null, "e": 12881, "s": 12168, "text": "Recall that above, we simply selected the best matching candidate based on whether it was a preferred string and their similarity. However, in many cases different concepts will have the same string representation, such as in the aforementioned “alcohol” example. This makes it difficult to choose an optimal candidate without having a disambiguation model, which requires context, and again turns the learning problem into a supervised one, or at least one that requires examples of contexts in which terms occur. One easy way out of this conundrum is to consider that, all else being equal, some semantic types are simply more likely, and therefore more likely in the given corpus. This is also called a prior." }, { "code": null, "e": 13296, "s": 12881, "text": "In our case, we estimate the class prior through the training set, as you would do in the well-known naive bayes classifier. Then, for each semantic type we extract for each set of candidates, we take the maximum similarity, and then multiply it with the prior. In neural network terms, you can think of this of max pooling on the class level. This also means we ignore the preferred term status of any candidates." }, { "code": null, "e": 13669, "s": 13296, "text": "╔═══╦══════╦═══════╦═════════╦════════╦══════════╗║ ║ BERT ║ QUMLS ║ + Spacy ║ + Grid ║ + Priors ║╠═══╬══════╬═══════╬═════════╬════════╬══════════╣║ P ║ .53 ║ .27 ║ .29 ║ .37 ║ .39 ║║ R ║ .58 ║ .36 ║ .37 ║ .37 ║ .39 ║║ F ║ .56 ║ .31 ║ .32 ║ .37 ║ .39 ║╚═══╩══════╩═══════╩═════════╩════════╩══════════╝Table 4: adding priors" }, { "code": null, "e": 14052, "s": 13669, "text": "Unfortunately, this is as far as we could get using the simple system in QuickUMLS. Given that we ended up using a threshold of .99 means that we do not use the approximate matching functionality of QuickUMLS at all. Removing the approximate matching would also speed up the entire system immensely, since most of the time of the algorithm is now spent on the matching in QuickUMLS." }, { "code": null, "e": 14877, "s": 14052, "text": "As we are doing a Named Entity Recognition task, there are a couple of classes of errors we can make. First off, we can extract the right span, but the wrong class. This happens when we find a correct term, but give it the wrong label, e.g., we think “alcohol” refers to the drink when it refers to the disinfectant. Second, we can also extract the span partially, but still match the right label. In this case, we can think of the match as a “partial match”. In our scoring, we only counted exact matches as correct. An example of this is extracting “mild anesthetic” when the gold standard is “anesthetic”. We can also miss spans completely, e.g., because UMLS does not contain the term, or extract spans that do not correspond to gold standard mentions. The figure below shows what kinds of these errors our system makes:" }, { "code": null, "e": 15222, "s": 14877, "text": "This shows that the errors QuickUMLS makes do not belong to one specific category. It extracts too many items, but, when it extracts items, it also often assigns the wrong label to those items. This shows that QuickUMLS could be employed as a pre-extraction system, after which a disambiguation system could be used to assign the correct label." }, { "code": null, "e": 15941, "s": 15222, "text": "As you can see from the results, an off-the-shelf terminology extraction system can be used as an efficient and effective NER system without training. Getting training data for specific use cases can often be a time-consuming process, hampering R&D speed. The QuickUMLS classifier we built shows that we can go a long way with very few training examples. And by being smart about the way we apply our resources, we have saved lot of time in the R&D process for biomedical NER. Our modified QuickUMLS classifier can be tried out here on github. The benefit of this approach can mean a solution robust enough for the outcome, simple to develop and test, and small enough for easy implementation into product development." }, { "code": null, "e": 16078, "s": 15941, "text": "[1] L. Soldaini, and N. Goharian. Quickumls: a fast, unsupervised approach for medical concept extraction, (2016), MedIR workshop, SIGIR" }, { "code": null, "e": 16212, "s": 16078, "text": "[2] S. Mohan, and D. Li, Medmentions: a large biomedical corpus annotated with UMLS concepts, (2019), arXiv preprint arXiv:1902.09476" }, { "code": null, "e": 16363, "s": 16212, "text": "[3] Y. Peng, Q. Chen, and Z. Lu, An empirical study of multi-task learning on BERT for biomedical text mining, (2020), arXiv preprint arXiv:2005.02799" }, { "code": null, "e": 16552, "s": 16363, "text": "[4] J. Lee, W. Yoon, S. Kim, D. Kim, S. Kim, C.H. So, and J. Kang, BioBERT: a pre-trained biomedical language representation model for biomedical text mining, (2020), Bioinformatics, 36(4)" }, { "code": null, "e": 16777, "s": 16552, "text": "[5] K.C. Fraser, I. Nejadgholi, B. De Bruijn, M. Li, A. LaPlante and K.Z.E. Abidine, Extracting UMLS concepts from medical text using general and domain-specific deep learning models, (2019), arXiv preprint arXiv:1910.01274." }, { "code": null, "e": 16989, "s": 16777, "text": "[6] N. Okazaki, and J.I. Tsujii, Simple and efficient algorithm for approximate dictionary matching, (2010, August), In Proceedings of the 23rd International Conference on Computational Linguistics (Coling 2010)" } ]
Scatter plot and Color mapping in Python
We can create a scatter plot using the scatter() method and we can set the color for every data point. Create random values (for x and y) in a given shape, using np.random.rand() method. Create random values (for x and y) in a given shape, using np.random.rand() method. Create a scatter plot of *y* vs. *x* with varying marker size and/or color, using the scatter method where color range would be in the range of (0, 1000). Create a scatter plot of *y* vs. *x* with varying marker size and/or color, using the scatter method where color range would be in the range of (0, 1000). Show the figure using plt.show(). Show the figure using plt.show(). import matplotlib.pyplot as plt import numpy as np x = np.random.rand(1000) y = np.random.rand(1000) plt.scatter(x, y, c=[i for i in range(1000)]) plt.show()
[ { "code": null, "e": 1165, "s": 1062, "text": "We can create a scatter plot using the scatter() method and we can set the color for every data point." }, { "code": null, "e": 1249, "s": 1165, "text": "Create random values (for x and y) in a given shape, using np.random.rand() method." }, { "code": null, "e": 1333, "s": 1249, "text": "Create random values (for x and y) in a given shape, using np.random.rand() method." }, { "code": null, "e": 1488, "s": 1333, "text": "Create a scatter plot of *y* vs. *x* with varying marker size and/or color, using the scatter method where color range would be in the range of (0, 1000)." }, { "code": null, "e": 1643, "s": 1488, "text": "Create a scatter plot of *y* vs. *x* with varying marker size and/or color, using the scatter method where color range would be in the range of (0, 1000)." }, { "code": null, "e": 1677, "s": 1643, "text": "Show the figure using plt.show()." }, { "code": null, "e": 1711, "s": 1677, "text": "Show the figure using plt.show()." }, { "code": null, "e": 1871, "s": 1711, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.random.rand(1000)\ny = np.random.rand(1000)\n\nplt.scatter(x, y, c=[i for i in range(1000)])\nplt.show()" } ]
Difference between Template and TemplateURL in AngularJS - GeeksforGeeks
08 Oct, 2021 As we know that, the @Component decorator is a function that accepts one object and that object has many properties. The major two important properties are template & template URL. The are various Method to create Templates in Angular The template is a part of a component that is used for the user interface by which the end-user can interact easily. We can create a template in two ways are follow: – Inline template External Template Inline Templates: When we define the template for the component in a .ts file it is known as an inline template the inline templates are defined in the component decorator using the template property. It refers to write the required HTML inside the typescript file. Let us consider an example. Open the app.component.ts file and modify the component decorator which as shown below. Here, you need to define the HTML content with the help of tilt characters. HTML <!--The content below is only a placeholder and can be replaced.-->import { Component } from '@angular/core'; @Component({ selector:'app-root', template:`<h3>Hello World</h3>` })export class AppComponent {title = 'MyAngularApp' Also, open the app.module.ts file and set the AppComponent to the start-up component in the bootstrap array as shown in below. HTML <!--The content below is only a placeholder and can be replaced.-->@NgModule({ declaration:[ AppComponent, MyComponentComponent, ]; imports: [ BrowseModule, AppRoutingModule ], providers: [],, bootstrap : [AppComponent] })export class AppModule { } Then modify the index.html page as shown below. HTML <!--The content below is only a placeholder and can be replaced.--><!Doctype html> <html lang ="en"> <head> <meta charset ="utf-8"> <title>MyAngularApp</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> Now, compile the application and you will get the following output. Can’t we include the HTML code inside single or double quotes? Yes, we can include the above HTML code inside a pair of either single quotes or double quotes or till when the HTML code is in a single line as shown below. Here we are using single quotes. HTML <!--The content below is only aplaceholder and can be replaced.-->@Component({ selector: 'app-root', template: '<h3>Hello World</h3>' }) When we are using Single quotes output will be: Using double quotes: You can also replace the above HTML Code inside a pair of double quotes as shown below HTML <!--The content below is only a placeholder and can be replaced.-->@Component({ selector: 'app-root', template: "<h3>Welcome to GeeksforGeeks</h3>"}) When we are using Double quotes output will be: When we will use tilt instead of either single quotes or double quotes? When we have multiple lines of HTML code then we need to use the tilt otherwise you will get a compile-time error. In order to get rid of this error, we need to use backticks (tilt) as shown in the below HTML <!--The content below is only a placeholder and can be replaced.-->@Component({ selector: 'app-root', template:`<h3>Let’s learn About the Angularjs. It is easy to understand.</h3>` }) When we are using backticks output will be: External Template: In real-time most cases, we need to use the templateURL. When we define the template in an external file and then after we link with our component is said to be an external template. In other words, The External templates define the HTML code in a separate file and we can refer to that file using templateURL property of Component decorator. The TypeScript file contains the path of the HTML code file using the “templateURL” property. When we need use the templateURL in angular? When we are working with a complex view, then it is recommended by angular to create that complex view in an external HTML File instead of an inline template. The angular component decorator provides the property of templateUrl and using this property we can set the external HTML code file path. By default, Angular creates an HTML code file with the name of app.component.html inside the app folder when we create any new angular project. Let us consider an example to understand How to provide that HTML code Path in component decorator using the templateUrl property. Also, do modify the app.component.ts file as shown below to use templateUrl property to set an external HTML file. HTML <!--The content below is only a placeholder and can be replaced.--> import { Component } from '@angular/core'; @Component({ selector:'app-root', templateUrl:'app/app.Component.html' }) export class AppComponent { title = 'MyAngularApp';} When we refer the code of app.component.html file to the app.component.ts file using TemplateURL then output will be: Template vs TemplateUrl in Angular: In AngularJS, we can define the view inside the HTML tags and there is various method to define the templates in angular components. Templates are one of the most essential parts of angular component because it allows us to define the UI for the component, we can have 2 ways to define the template. Inline template External Template There are no such real differences between the template and templateUrl property in a term of performance of an application. But from the developer’s point of view, there are some differences which we will discuss here. In Angular, when we have a complex view then we should go with templateUrl (using an external file) otherwise we can use the template (inline HTML) property of the component decorator. When we use an inline template, then we do no longer have the intelligence support, code-completion, and formatting features of Visual Studio. But with an outside template, we will have the intelligence support, code-completion, and formatting functions of Visual Studio as well. The TypeScript code isn’t always to study and recognize if we combined it with the inline HTML template. There is a convenience thing to having the typescript code and the associated HTML in the same record because it turns into much less complicated to peer how they are associated with each other. anikakapoor AngularJS-Misc AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? How to set focus on input field automatically on page load in AngularJS ? How to bundle an Angular app for production? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25119, "s": 25091, "text": "\n08 Oct, 2021" }, { "code": null, "e": 25300, "s": 25119, "text": "As we know that, the @Component decorator is a function that accepts one object and that object has many properties. The major two important properties are template & template URL." }, { "code": null, "e": 25354, "s": 25300, "text": "The are various Method to create Templates in Angular" }, { "code": null, "e": 25522, "s": 25354, "text": "The template is a part of a component that is used for the user interface by which the end-user can interact easily. We can create a template in two ways are follow: –" }, { "code": null, "e": 25538, "s": 25522, "text": "Inline template" }, { "code": null, "e": 25556, "s": 25538, "text": "External Template" }, { "code": null, "e": 25574, "s": 25556, "text": "Inline Templates:" }, { "code": null, "e": 25850, "s": 25574, "text": "When we define the template for the component in a .ts file it is known as an inline template the inline templates are defined in the component decorator using the template property. It refers to write the required HTML inside the typescript file. Let us consider an example." }, { "code": null, "e": 26014, "s": 25850, "text": "Open the app.component.ts file and modify the component decorator which as shown below. Here, you need to define the HTML content with the help of tilt characters." }, { "code": null, "e": 26019, "s": 26014, "text": "HTML" }, { "code": "<!--The content below is only a placeholder and can be replaced.-->import { Component } from '@angular/core'; @Component({ selector:'app-root', template:`<h3>Hello World</h3>` })export class AppComponent {title = 'MyAngularApp'", "e": 26264, "s": 26019, "text": null }, { "code": null, "e": 26392, "s": 26264, "text": "Also, open the app.module.ts file and set the AppComponent to the start-up component in the bootstrap array as shown in below." }, { "code": null, "e": 26397, "s": 26392, "text": "HTML" }, { "code": "<!--The content below is only a placeholder and can be replaced.-->@NgModule({ declaration:[ AppComponent, MyComponentComponent, ]; imports: [ BrowseModule, AppRoutingModule ], providers: [],, bootstrap : [AppComponent] })export class AppModule { }", "e": 26691, "s": 26397, "text": null }, { "code": null, "e": 26739, "s": 26691, "text": "Then modify the index.html page as shown below." }, { "code": null, "e": 26744, "s": 26739, "text": "HTML" }, { "code": "<!--The content below is only a placeholder and can be replaced.--><!Doctype html> <html lang =\"en\"> <head> <meta charset =\"utf-8\"> <title>MyAngularApp</title> <base href=\"/\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\"> </head> <body> <app-root></app-root> </body> </html>", "e": 27193, "s": 26744, "text": null }, { "code": null, "e": 27261, "s": 27193, "text": "Now, compile the application and you will get the following output." }, { "code": null, "e": 27324, "s": 27261, "text": "Can’t we include the HTML code inside single or double quotes?" }, { "code": null, "e": 27485, "s": 27324, "text": "Yes, we can include the above HTML code inside a pair of either single quotes or double quotes or till when the HTML code is in a single line as shown below. " }, { "code": null, "e": 27518, "s": 27485, "text": "Here we are using single quotes." }, { "code": null, "e": 27523, "s": 27518, "text": "HTML" }, { "code": "<!--The content below is only aplaceholder and can be replaced.-->@Component({ selector: 'app-root', template: '<h3>Hello World</h3>' })", "e": 27675, "s": 27523, "text": null }, { "code": null, "e": 27724, "s": 27675, "text": "When we are using Single quotes output will be: " }, { "code": null, "e": 27745, "s": 27724, "text": "Using double quotes:" }, { "code": null, "e": 27832, "s": 27745, "text": "You can also replace the above HTML Code inside a pair of double quotes as shown below" }, { "code": null, "e": 27837, "s": 27832, "text": "HTML" }, { "code": "<!--The content below is only a placeholder and can be replaced.-->@Component({ selector: 'app-root', template: \"<h3>Welcome to GeeksforGeeks</h3>\"})", "e": 28001, "s": 27837, "text": null }, { "code": null, "e": 28050, "s": 28001, "text": "When we are using Double quotes output will be: " }, { "code": null, "e": 28122, "s": 28050, "text": "When we will use tilt instead of either single quotes or double quotes?" }, { "code": null, "e": 28327, "s": 28122, "text": "When we have multiple lines of HTML code then we need to use the tilt otherwise you will get a compile-time error. In order to get rid of this error, we need to use backticks (tilt) as shown in the below" }, { "code": null, "e": 28332, "s": 28327, "text": "HTML" }, { "code": "<!--The content below is only a placeholder and can be replaced.-->@Component({ selector: 'app-root', template:`<h3>Let’s learn About the Angularjs. It is easy to understand.</h3>` })", "e": 28552, "s": 28332, "text": null }, { "code": null, "e": 28597, "s": 28552, "text": "When we are using backticks output will be: " }, { "code": null, "e": 28616, "s": 28597, "text": "External Template:" }, { "code": null, "e": 28799, "s": 28616, "text": "In real-time most cases, we need to use the templateURL. When we define the template in an external file and then after we link with our component is said to be an external template." }, { "code": null, "e": 29053, "s": 28799, "text": "In other words, The External templates define the HTML code in a separate file and we can refer to that file using templateURL property of Component decorator. The TypeScript file contains the path of the HTML code file using the “templateURL” property." }, { "code": null, "e": 29098, "s": 29053, "text": "When we need use the templateURL in angular?" }, { "code": null, "e": 29395, "s": 29098, "text": "When we are working with a complex view, then it is recommended by angular to create that complex view in an external HTML File instead of an inline template. The angular component decorator provides the property of templateUrl and using this property we can set the external HTML code file path." }, { "code": null, "e": 29785, "s": 29395, "text": "By default, Angular creates an HTML code file with the name of app.component.html inside the app folder when we create any new angular project. Let us consider an example to understand How to provide that HTML code Path in component decorator using the templateUrl property. Also, do modify the app.component.ts file as shown below to use templateUrl property to set an external HTML file." }, { "code": null, "e": 29790, "s": 29785, "text": "HTML" }, { "code": "<!--The content below is only a placeholder and can be replaced.--> import { Component } from '@angular/core'; @Component({ selector:'app-root', templateUrl:'app/app.Component.html' }) export class AppComponent { title = 'MyAngularApp';}", "e": 30060, "s": 29790, "text": null }, { "code": null, "e": 30178, "s": 30060, "text": "When we refer the code of app.component.html file to the app.component.ts file using TemplateURL then output will be:" }, { "code": null, "e": 30214, "s": 30178, "text": "Template vs TemplateUrl in Angular:" }, { "code": null, "e": 30347, "s": 30214, "text": "In AngularJS, we can define the view inside the HTML tags and there is various method to define the templates in angular components." }, { "code": null, "e": 30514, "s": 30347, "text": "Templates are one of the most essential parts of angular component because it allows us to define the UI for the component, we can have 2 ways to define the template." }, { "code": null, "e": 30530, "s": 30514, "text": "Inline template" }, { "code": null, "e": 30548, "s": 30530, "text": "External Template" }, { "code": null, "e": 30768, "s": 30548, "text": "There are no such real differences between the template and templateUrl property in a term of performance of an application. But from the developer’s point of view, there are some differences which we will discuss here." }, { "code": null, "e": 30953, "s": 30768, "text": "In Angular, when we have a complex view then we should go with templateUrl (using an external file) otherwise we can use the template (inline HTML) property of the component decorator." }, { "code": null, "e": 31535, "s": 30953, "text": "When we use an inline template, then we do no longer have the intelligence support, code-completion, and formatting features of Visual Studio. But with an outside template, we will have the intelligence support, code-completion, and formatting functions of Visual Studio as well. The TypeScript code isn’t always to study and recognize if we combined it with the inline HTML template. There is a convenience thing to having the typescript code and the associated HTML in the same record because it turns into much less complicated to peer how they are associated with each other." }, { "code": null, "e": 31549, "s": 31537, "text": "anikakapoor" }, { "code": null, "e": 31564, "s": 31549, "text": "AngularJS-Misc" }, { "code": null, "e": 31574, "s": 31564, "text": "AngularJS" }, { "code": null, "e": 31591, "s": 31574, "text": "Web Technologies" }, { "code": null, "e": 31689, "s": 31591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31733, "s": 31689, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 31764, "s": 31733, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 31806, "s": 31764, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 31880, "s": 31806, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 31925, "s": 31880, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 31967, "s": 31925, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32000, "s": 31967, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32043, "s": 32000, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32105, "s": 32043, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to add Video Player in NextJS ?
14 Dec, 2021 In this article, we are going to learn how we can add Video Player in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. Approach: To add our Video Player we are going to use the react-player package. The react-player package helps us to add a video player anywhere in our app. So first, we will install the react-player package and then we will add a video player on our homepage. Create NextJS Application: You can create a new NextJs project using the below command: npx create-next-app gfg Install the required package: Now we will install the react-player package using the below command: npm i react-player Project Structure: It will look like this. Adding the Video Player: After installing the package we can easily add Video Player to our app. For this example, we are going to add a video player to our homepage. index.js import React from 'react'import ReactPlayer from 'react-player' export default function VideoPlayer(){ return ( <div> <h2>NextJs VideoPlayer - GeeksforGeeks</h2> <ReactPlayer url='https://www.youtube.com/watch?v=wWgIAphfn2U' /> </div> )} Explanation: In the above example first, we are importing our ReactPlayer component from the installed package. After that, we are using the ReactPlayer component inside a new function. We can enter the link of the video that we want to play. Steps to run the application: Run the below command in the terminal to run the app. npm run dev Next.js JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to fetch data from an API in ReactJS ? Axios in React: A Guide for Beginners How to redirect to another page in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Dec, 2021" }, { "code": null, "e": 276, "s": 53, "text": "In this article, we are going to learn how we can add Video Player in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. " }, { "code": null, "e": 537, "s": 276, "text": "Approach: To add our Video Player we are going to use the react-player package. The react-player package helps us to add a video player anywhere in our app. So first, we will install the react-player package and then we will add a video player on our homepage." }, { "code": null, "e": 625, "s": 537, "text": "Create NextJS Application: You can create a new NextJs project using the below command:" }, { "code": null, "e": 649, "s": 625, "text": "npx create-next-app gfg" }, { "code": null, "e": 751, "s": 651, "text": "Install the required package: Now we will install the react-player package using the below command:" }, { "code": null, "e": 770, "s": 751, "text": "npm i react-player" }, { "code": null, "e": 813, "s": 770, "text": "Project Structure: It will look like this." }, { "code": null, "e": 980, "s": 813, "text": "Adding the Video Player: After installing the package we can easily add Video Player to our app. For this example, we are going to add a video player to our homepage." }, { "code": null, "e": 989, "s": 980, "text": "index.js" }, { "code": "import React from 'react'import ReactPlayer from 'react-player' export default function VideoPlayer(){ return ( <div> <h2>NextJs VideoPlayer - GeeksforGeeks</h2> <ReactPlayer url='https://www.youtube.com/watch?v=wWgIAphfn2U' /> </div> )}", "e": 1246, "s": 989, "text": null }, { "code": null, "e": 1489, "s": 1246, "text": "Explanation: In the above example first, we are importing our ReactPlayer component from the installed package. After that, we are using the ReactPlayer component inside a new function. We can enter the link of the video that we want to play." }, { "code": null, "e": 1573, "s": 1489, "text": "Steps to run the application: Run the below command in the terminal to run the app." }, { "code": null, "e": 1585, "s": 1573, "text": "npm run dev" }, { "code": null, "e": 1593, "s": 1585, "text": "Next.js" }, { "code": null, "e": 1604, "s": 1593, "text": "JavaScript" }, { "code": null, "e": 1612, "s": 1604, "text": "ReactJS" }, { "code": null, "e": 1629, "s": 1612, "text": "Web Technologies" }, { "code": null, "e": 1727, "s": 1629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1788, "s": 1727, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1828, "s": 1788, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1870, "s": 1828, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1911, "s": 1870, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1933, "s": 1911, "text": "JavaScript | Promises" }, { "code": null, "e": 1976, "s": 1933, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2014, "s": 1976, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2059, "s": 2014, "text": "How to redirect to another page in ReactJS ?" } ]
What are the differences between Widening Casting (Implicit) and Narrowing Casting (Explicit) in Java?
A Type casting in Java is used to convert objects or variables of one type into another. When we are converting or assigning one data type to another they might not compatible. If it is suitable then it will do smoothly otherwise chances of data loss. Java Type Casting is classified into two types. Widening Casting (Implicit) – Automatic Type Conversion Narrowing Casting (Explicit) – Need Explicit Conversion Widening Type Conversion can happen if both types are compatible and the target type is larger than source type. Widening Casting takes place when two types are compatible and the target type is larger than the source type. Live Demo public class ImplicitCastingExample { public static void main(String args[]) { byte i = 40; // No casting needed for below conversion short j = i; int k = j; long l = k; float m = l; double n = m; System.out.println("byte value : "+i); System.out.println("short value : "+j); System.out.println("int value : "+k); System.out.println("long value : "+l); System.out.println("float value : "+m); System.out.println("double value : "+n); } } byte value : 40 short value : 40 int value : 40 long value : 40 float value : 40.0 double value : 40.0 In the below example, Child class is the smaller type we are assigning it to Parent class type which is a larger type hence no casting is required. Live Demo class Parent { public void display() { System.out.println("Parent class display() called"); } } public class Child extends Parent { public static void main(String args[]) { Parent p = new Child(); p.display(); } } Parent class display() method called When we are assigning a larger type to a smaller type, Explicit Casting is required. Live Demo public class ExplicitCastingExample { public static void main(String args[]) { double d = 30.0; // Explicit casting is needed for below conversion float f = (float) d; long l = (long) f; int i = (int) l; short s = (short) i; byte b = (byte) s; System.out.println("double value : "+d); System.out.println("float value : "+f); System.out.println("long value : "+l); System.out.println("int value : "+i); System.out.println("short value : "+s); System.out.println("byte value : "+b); } } double value : 30.0 float value : 30.0 long value : 30 int value : 30 short value : 30 byte value : 30 When we are assigning larger type to a smaller type, then we need to explicitly typecast it. Live Demo class Parent { public void display() { System.out.println("Parent class display() method called"); } } public class Child extends Parent { public void display() { System.out.println("Child class display() method called"); } public static void main(String args[]) { Parent p = new Child(); Child c = (Child) p; c.display(); } } Child class display() method called
[ { "code": null, "e": 1439, "s": 1187, "text": "A Type casting in Java is used to convert objects or variables of one type into another. When we are converting or assigning one data type to another they might not compatible. If it is suitable then it will do smoothly otherwise chances of data loss." }, { "code": null, "e": 1487, "s": 1439, "text": "Java Type Casting is classified into two types." }, { "code": null, "e": 1543, "s": 1487, "text": "Widening Casting (Implicit) – Automatic Type Conversion" }, { "code": null, "e": 1599, "s": 1543, "text": "Narrowing Casting (Explicit) – Need Explicit Conversion" }, { "code": null, "e": 1823, "s": 1599, "text": "Widening\nType Conversion can happen if both types are compatible and the target type is larger than source type. Widening Casting takes place when two types are compatible and the target type is larger than the source type." }, { "code": null, "e": 1833, "s": 1823, "text": "Live Demo" }, { "code": null, "e": 2355, "s": 1833, "text": "public class ImplicitCastingExample {\n public static void main(String args[]) {\n byte i = 40;\n // No casting needed for below conversion\n short j = i;\n int k = j;\n long l = k;\n float m = l;\n double n = m;\n System.out.println(\"byte value : \"+i);\n System.out.println(\"short value : \"+j);\n System.out.println(\"int value : \"+k);\n System.out.println(\"long value : \"+l);\n System.out.println(\"float value : \"+m);\n System.out.println(\"double value : \"+n);\n }\n}" }, { "code": null, "e": 2458, "s": 2355, "text": "byte value : 40\nshort value : 40\nint value : 40\nlong value : 40\nfloat value : 40.0\ndouble value : 40.0" }, { "code": null, "e": 2606, "s": 2458, "text": "In the below example, Child class is the smaller type we are assigning it to Parent class type which is a larger type hence no casting is required." }, { "code": null, "e": 2616, "s": 2606, "text": "Live Demo" }, { "code": null, "e": 2860, "s": 2616, "text": "class Parent {\n public void display() {\n System.out.println(\"Parent class display() called\");\n }\n}\npublic class Child extends Parent {\n public static void main(String args[]) {\n Parent p = new Child();\n p.display();\n }\n}" }, { "code": null, "e": 2897, "s": 2860, "text": "Parent class display() method called" }, { "code": null, "e": 2982, "s": 2897, "text": "When we are assigning a larger type to a smaller type, Explicit Casting is required." }, { "code": null, "e": 2992, "s": 2982, "text": "Live Demo" }, { "code": null, "e": 3561, "s": 2992, "text": "public class ExplicitCastingExample {\n public static void main(String args[]) {\n double d = 30.0;\n // Explicit casting is needed for below conversion\n float f = (float) d;\n long l = (long) f;\n int i = (int) l;\n short s = (short) i;\n byte b = (byte) s;\n System.out.println(\"double value : \"+d);\n System.out.println(\"float value : \"+f);\n System.out.println(\"long value : \"+l);\n System.out.println(\"int value : \"+i);\n System.out.println(\"short value : \"+s);\n System.out.println(\"byte value : \"+b);\n }\n}" }, { "code": null, "e": 3664, "s": 3561, "text": "double value : 30.0\nfloat value : 30.0\nlong value : 30\nint value : 30\nshort value : 30\nbyte value : 30" }, { "code": null, "e": 3757, "s": 3664, "text": "When we are assigning larger type to a smaller type, then we need to explicitly\ntypecast it." }, { "code": null, "e": 3767, "s": 3757, "text": "Live Demo" }, { "code": null, "e": 4142, "s": 3767, "text": "class Parent {\n public void display() {\n System.out.println(\"Parent class display() method called\");\n }\n}\npublic class Child extends Parent {\n public void display() {\n System.out.println(\"Child class display() method called\");\n }\n public static void main(String args[]) {\n Parent p = new Child();\n Child c = (Child) p;\n c.display();\n }\n}" }, { "code": null, "e": 4178, "s": 4142, "text": "Child class display() method called" } ]
Difference between Indirect and Implied Addressing Modes
04 Jul, 2022 1. Indirect Addressing Mode: This is the mode of addressing where the instruction contains the address of the location where the target address is stored. So in this way, it is Indirectly storing the address of the target location in another memory location. So it is called Indirect Addressing mode. Prerequisite - Addressing Modes There are 2 types(or versions) of Indirect Addressing Mode: Memory Indirect, and Register Indirect. 1. Memory Indirect: In this type, we directly mention the address of the memory location in the instruction either enclosed by parenthesis or preceded by the ‘@’ character. Example : LOAD R1, (1005) or LOAD R1, @1005 2. Register Indirect: In this type, the address of the target memory location will be stored in the register and the register will be mentioned in the instruction. Example: MOV R@, 1005 LOAD R1, (R2) 2. Implied Addressing Mode : This is the mode of addressing where the operand is specified implicitly in the definition of the instruction. This mode of addressing is normally used in zero address (e.g., Stack operations) and one address (e.g., MUL AL) instructions. Hence the operand is implied inside the instruction, it is called Implied Addressing Mode. Example : MOV CL, 05 L1: INC AL LOOP L1 Here AL will be incremented by 1 every time the loop executes. Hence 1 is implied inside the instruction INC AL. Difference between Indirect and Implied Addressing Modes : chhabradhanvi annieahujaweb2020 Picked Computer Organization & Architecture Difference Between GATE CS Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2022" }, { "code": null, "e": 330, "s": 28, "text": "1. Indirect Addressing Mode: This is the mode of addressing where the instruction contains the address of the location where the target address is stored. So in this way, it is Indirectly storing the address of the target location in another memory location. So it is called Indirect Addressing mode. " }, { "code": null, "e": 363, "s": 330, "text": "Prerequisite - Addressing Modes " }, { "code": null, "e": 464, "s": 363, "text": "There are 2 types(or versions) of Indirect Addressing Mode: Memory Indirect, and Register Indirect. " }, { "code": null, "e": 638, "s": 464, "text": "1. Memory Indirect: In this type, we directly mention the address of the memory location in the instruction either enclosed by parenthesis or preceded by the ‘@’ character. " }, { "code": null, "e": 648, "s": 638, "text": "Example :" }, { "code": null, "e": 685, "s": 648, "text": "LOAD R1, (1005) \nor \nLOAD R1, @1005 " }, { "code": null, "e": 850, "s": 685, "text": "2. Register Indirect: In this type, the address of the target memory location will be stored in the register and the register will be mentioned in the instruction. " }, { "code": null, "e": 860, "s": 850, "text": "Example: " }, { "code": null, "e": 888, "s": 860, "text": "MOV R@, 1005\nLOAD R1, (R2) " }, { "code": null, "e": 1247, "s": 888, "text": "2. Implied Addressing Mode : This is the mode of addressing where the operand is specified implicitly in the definition of the instruction. This mode of addressing is normally used in zero address (e.g., Stack operations) and one address (e.g., MUL AL) instructions. Hence the operand is implied inside the instruction, it is called Implied Addressing Mode. " }, { "code": null, "e": 1258, "s": 1247, "text": "Example : " }, { "code": null, "e": 1293, "s": 1258, "text": "MOV CL, 05\nL1: INC AL\n LOOP L1 " }, { "code": null, "e": 1407, "s": 1293, "text": "Here AL will be incremented by 1 every time the loop executes. Hence 1 is implied inside the instruction INC AL. " }, { "code": null, "e": 1467, "s": 1407, "text": "Difference between Indirect and Implied Addressing Modes : " }, { "code": null, "e": 1483, "s": 1469, "text": "chhabradhanvi" }, { "code": null, "e": 1501, "s": 1483, "text": "annieahujaweb2020" }, { "code": null, "e": 1508, "s": 1501, "text": "Picked" }, { "code": null, "e": 1545, "s": 1508, "text": "Computer Organization & Architecture" }, { "code": null, "e": 1564, "s": 1545, "text": "Difference Between" }, { "code": null, "e": 1572, "s": 1564, "text": "GATE CS" }, { "code": null, "e": 1588, "s": 1572, "text": "Write From Home" } ]
fork() in C
09 Dec, 2019 Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call. A child process uses the same pc(program counter), same CPU registers, same open files which use in the parent process. It takes no parameters and returns an integer value. Below are different values returned by fork(). Negative Value: creation of a child process was unsuccessful.Zero: Returned to the newly created child process.Positive value: Returned to parent or caller. The value contains process ID of newly created child process. Please note that the above programs don’t compile in Windows environment. Predict the Output of the following program:.#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){ // make two process which run same // program after this instruction fork(); printf("Hello world!\n"); return 0;}Output:Hello world! Hello world! Calculate number of times hello is printed:#include <stdio.h>#include <sys/types.h>int main(){ fork(); fork(); fork(); printf("hello\n"); return 0;}Output:hello hello hello hello hello hello hello hello The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8Let us put some label names for the three lines:fork (); // Line 1 fork (); // Line 2 fork (); // Line 3 L1 // There will be 1 child process / \ // created by line 1. L2 L2 // There will be 2 child processes / \ / \ // created by line 2 L3 L3 L3 L3 // There will be 4 child processes // created by line 3 So there are total eight processes (new child processes and one original process).If we want to represent the relationship between the processes as a tree hierarchy it would be the following:The main process: P0Processes created by the 1st fork: P1Processes created by the 2nd fork: P2, P3Processes created by the 3rd fork: P4, P5, P6, P7 P0 / | \ P1 P4 P2 / \ \ P3 P6 P5 / P7 Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h>void forkexample(){ // child process because return value zero if (fork() == 0) printf("Hello from Child!\n"); // parent process because return value non-zero. else printf("Hello from Parent!\n");}int main(){ forkexample(); return 0;}Output:1. Hello from Child! Hello from Parent! (or) 2. Hello from Parent! Hello from Child! In the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process.Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process.Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example:Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h> void forkexample(){ int x = 1; if (fork() == 0) printf("Child has x = %d\n", ++x); else printf("Parent has x = %d\n", --x);}int main(){ forkexample(); return 0;}Output:Parent has x = 0 Child has x = 2 (or) Child has x = 2 Parent has x = 0 Here, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible. Predict the Output of the following program:.#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){ // make two process which run same // program after this instruction fork(); printf("Hello world!\n"); return 0;}Output:Hello world! Hello world! #include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){ // make two process which run same // program after this instruction fork(); printf("Hello world!\n"); return 0;} Output: Hello world! Hello world! Calculate number of times hello is printed:#include <stdio.h>#include <sys/types.h>int main(){ fork(); fork(); fork(); printf("hello\n"); return 0;}Output:hello hello hello hello hello hello hello hello The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8Let us put some label names for the three lines:fork (); // Line 1 fork (); // Line 2 fork (); // Line 3 L1 // There will be 1 child process / \ // created by line 1. L2 L2 // There will be 2 child processes / \ / \ // created by line 2 L3 L3 L3 L3 // There will be 4 child processes // created by line 3 So there are total eight processes (new child processes and one original process).If we want to represent the relationship between the processes as a tree hierarchy it would be the following:The main process: P0Processes created by the 1st fork: P1Processes created by the 2nd fork: P2, P3Processes created by the 3rd fork: P4, P5, P6, P7 P0 / | \ P1 P4 P2 / \ \ P3 P6 P5 / P7 #include <stdio.h>#include <sys/types.h>int main(){ fork(); fork(); fork(); printf("hello\n"); return 0;} Output: hello hello hello hello hello hello hello hello The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8 Let us put some label names for the three lines: fork (); // Line 1 fork (); // Line 2 fork (); // Line 3 L1 // There will be 1 child process / \ // created by line 1. L2 L2 // There will be 2 child processes / \ / \ // created by line 2 L3 L3 L3 L3 // There will be 4 child processes // created by line 3 So there are total eight processes (new child processes and one original process). If we want to represent the relationship between the processes as a tree hierarchy it would be the following: The main process: P0Processes created by the 1st fork: P1Processes created by the 2nd fork: P2, P3Processes created by the 3rd fork: P4, P5, P6, P7 P0 / | \ P1 P4 P2 / \ \ P3 P6 P5 / P7 Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h>void forkexample(){ // child process because return value zero if (fork() == 0) printf("Hello from Child!\n"); // parent process because return value non-zero. else printf("Hello from Parent!\n");}int main(){ forkexample(); return 0;}Output:1. Hello from Child! Hello from Parent! (or) 2. Hello from Parent! Hello from Child! In the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process.Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process.Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example: #include <stdio.h>#include <sys/types.h>#include <unistd.h>void forkexample(){ // child process because return value zero if (fork() == 0) printf("Hello from Child!\n"); // parent process because return value non-zero. else printf("Hello from Parent!\n");}int main(){ forkexample(); return 0;} Output: 1. Hello from Child! Hello from Parent! (or) 2. Hello from Parent! Hello from Child! In the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process.Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process. Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example: Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h> void forkexample(){ int x = 1; if (fork() == 0) printf("Child has x = %d\n", ++x); else printf("Parent has x = %d\n", --x);}int main(){ forkexample(); return 0;}Output:Parent has x = 0 Child has x = 2 (or) Child has x = 2 Parent has x = 0 Here, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible. #include <stdio.h>#include <sys/types.h>#include <unistd.h> void forkexample(){ int x = 1; if (fork() == 0) printf("Child has x = %d\n", ++x); else printf("Parent has x = %d\n", --x);}int main(){ forkexample(); return 0;} Output: Parent has x = 0 Child has x = 2 (or) Child has x = 2 Parent has x = 0 Here, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible. fork() vs exec() The fork system call creates a new process. The new process created by fork() is a copy of the current process except for the returned value. The exec() system call replaces the current process with a new program. Exercise: A process executes the following code:for (i = 0; i < n; i++) fork();The total number of child processes created is: (GATE-CS-2008)(A) n(B) 2^n – 1(C) 2^n(D) 2^(n+1) – 1;See this for solution.Consider the following code fragment:if (fork() == 0) { a = a + 5; printf("%d, %d\n", a, &a);}else { a = a –5; printf("%d, %d\n", a, &a);}Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != ySee this for solution.Predict output of below program.#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf("forked\n"); return 0;}See this for solution A process executes the following code:for (i = 0; i < n; i++) fork();The total number of child processes created is: (GATE-CS-2008)(A) n(B) 2^n – 1(C) 2^n(D) 2^(n+1) – 1;See this for solution. for (i = 0; i < n; i++) fork(); The total number of child processes created is: (GATE-CS-2008)(A) n(B) 2^n – 1(C) 2^n(D) 2^(n+1) – 1; See this for solution. Consider the following code fragment:if (fork() == 0) { a = a + 5; printf("%d, %d\n", a, &a);}else { a = a –5; printf("%d, %d\n", a, &a);}Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != ySee this for solution. if (fork() == 0) { a = a + 5; printf("%d, %d\n", a, &a);}else { a = a –5; printf("%d, %d\n", a, &a);} Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != ySee this for solution. Predict output of below program.#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf("forked\n"); return 0;}See this for solution Predict output of below program. #include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf("forked\n"); return 0;} See this for solution Related Articles :C program to demonstrate fork() and pipe()Zombie and Orphan Processes in Cfork() and memory shared b/w processes created using it. References:http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html This article is contributed by Team GeeksforGeeks and Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. FunniestClown AndreiSas reddydheerajreddy 4slan jimbotherisenclown C-Library system-programming C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Dec, 2019" }, { "code": null, "e": 465, "s": 54, "text": "Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call. A child process uses the same pc(program counter), same CPU registers, same open files which use in the parent process." }, { "code": null, "e": 565, "s": 465, "text": "It takes no parameters and returns an integer value. Below are different values returned by fork()." }, { "code": null, "e": 784, "s": 565, "text": "Negative Value: creation of a child process was unsuccessful.Zero: Returned to the newly created child process.Positive value: Returned to parent or caller. The value contains process ID of newly created child process." }, { "code": null, "e": 858, "s": 784, "text": "Please note that the above programs don’t compile in Windows environment." }, { "code": null, "e": 3993, "s": 858, "text": "Predict the Output of the following program:.#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){ // make two process which run same // program after this instruction fork(); printf(\"Hello world!\\n\"); return 0;}Output:Hello world!\nHello world!\nCalculate number of times hello is printed:#include <stdio.h>#include <sys/types.h>int main(){ fork(); fork(); fork(); printf(\"hello\\n\"); return 0;}Output:hello\nhello\nhello\nhello\nhello\nhello\nhello\nhello\nThe number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8Let us put some label names for the three lines:fork (); // Line 1\nfork (); // Line 2\nfork (); // Line 3\n\n L1 // There will be 1 child process \n / \\ // created by line 1.\n L2 L2 // There will be 2 child processes\n / \\ / \\ // created by line 2\nL3 L3 L3 L3 // There will be 4 child processes \n // created by line 3\n\nSo there are total eight processes (new child processes and one original process).If we want to represent the relationship between the processes as a tree hierarchy it would be the following:The main process: P0Processes created by the 1st fork: P1Processes created by the 2nd fork: P2, P3Processes created by the 3rd fork: P4, P5, P6, P7 P0\n / | \\\n P1 P4 P2\n / \\ \\\n P3 P6 P5\n /\n P7\nPredict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h>void forkexample(){ // child process because return value zero if (fork() == 0) printf(\"Hello from Child!\\n\"); // parent process because return value non-zero. else printf(\"Hello from Parent!\\n\");}int main(){ forkexample(); return 0;}Output:1.\nHello from Child!\nHello from Parent!\n (or)\n2.\nHello from Parent!\nHello from Child!\nIn the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process.Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process.Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example:Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h> void forkexample(){ int x = 1; if (fork() == 0) printf(\"Child has x = %d\\n\", ++x); else printf(\"Parent has x = %d\\n\", --x);}int main(){ forkexample(); return 0;}Output:Parent has x = 0\nChild has x = 2\n (or)\nChild has x = 2\nParent has x = 0\nHere, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible." }, { "code": null, "e": 4275, "s": 3993, "text": "Predict the Output of the following program:.#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){ // make two process which run same // program after this instruction fork(); printf(\"Hello world!\\n\"); return 0;}Output:Hello world!\nHello world!\n" }, { "code": "#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){ // make two process which run same // program after this instruction fork(); printf(\"Hello world!\\n\"); return 0;}", "e": 4479, "s": 4275, "text": null }, { "code": null, "e": 4487, "s": 4479, "text": "Output:" }, { "code": null, "e": 4514, "s": 4487, "text": "Hello world!\nHello world!\n" }, { "code": null, "e": 5732, "s": 4514, "text": "Calculate number of times hello is printed:#include <stdio.h>#include <sys/types.h>int main(){ fork(); fork(); fork(); printf(\"hello\\n\"); return 0;}Output:hello\nhello\nhello\nhello\nhello\nhello\nhello\nhello\nThe number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8Let us put some label names for the three lines:fork (); // Line 1\nfork (); // Line 2\nfork (); // Line 3\n\n L1 // There will be 1 child process \n / \\ // created by line 1.\n L2 L2 // There will be 2 child processes\n / \\ / \\ // created by line 2\nL3 L3 L3 L3 // There will be 4 child processes \n // created by line 3\n\nSo there are total eight processes (new child processes and one original process).If we want to represent the relationship between the processes as a tree hierarchy it would be the following:The main process: P0Processes created by the 1st fork: P1Processes created by the 2nd fork: P2, P3Processes created by the 3rd fork: P4, P5, P6, P7 P0\n / | \\\n P1 P4 P2\n / \\ \\\n P3 P6 P5\n /\n P7\n" }, { "code": "#include <stdio.h>#include <sys/types.h>int main(){ fork(); fork(); fork(); printf(\"hello\\n\"); return 0;}", "e": 5853, "s": 5732, "text": null }, { "code": null, "e": 5861, "s": 5853, "text": "Output:" }, { "code": null, "e": 5910, "s": 5861, "text": "hello\nhello\nhello\nhello\nhello\nhello\nhello\nhello\n" }, { "code": null, "e": 6082, "s": 5910, "text": "The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8" }, { "code": null, "e": 6131, "s": 6082, "text": "Let us put some label names for the three lines:" }, { "code": null, "e": 6463, "s": 6131, "text": "fork (); // Line 1\nfork (); // Line 2\nfork (); // Line 3\n\n L1 // There will be 1 child process \n / \\ // created by line 1.\n L2 L2 // There will be 2 child processes\n / \\ / \\ // created by line 2\nL3 L3 L3 L3 // There will be 4 child processes \n // created by line 3\n\n" }, { "code": null, "e": 6546, "s": 6463, "text": "So there are total eight processes (new child processes and one original process)." }, { "code": null, "e": 6656, "s": 6546, "text": "If we want to represent the relationship between the processes as a tree hierarchy it would be the following:" }, { "code": null, "e": 6804, "s": 6656, "text": "The main process: P0Processes created by the 1st fork: P1Processes created by the 2nd fork: P2, P3Processes created by the 3rd fork: P4, P5, P6, P7" }, { "code": null, "e": 6916, "s": 6804, "text": " P0\n / | \\\n P1 P4 P2\n / \\ \\\n P3 P6 P5\n /\n P7\n" }, { "code": null, "e": 7967, "s": 6916, "text": "Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h>void forkexample(){ // child process because return value zero if (fork() == 0) printf(\"Hello from Child!\\n\"); // parent process because return value non-zero. else printf(\"Hello from Parent!\\n\");}int main(){ forkexample(); return 0;}Output:1.\nHello from Child!\nHello from Parent!\n (or)\n2.\nHello from Parent!\nHello from Child!\nIn the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process.Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process.Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example:" }, { "code": "#include <stdio.h>#include <sys/types.h>#include <unistd.h>void forkexample(){ // child process because return value zero if (fork() == 0) printf(\"Hello from Child!\\n\"); // parent process because return value non-zero. else printf(\"Hello from Parent!\\n\");}int main(){ forkexample(); return 0;}", "e": 8295, "s": 7967, "text": null }, { "code": null, "e": 8303, "s": 8295, "text": "Output:" }, { "code": null, "e": 8394, "s": 8303, "text": "1.\nHello from Child!\nHello from Parent!\n (or)\n2.\nHello from Parent!\nHello from Child!\n" }, { "code": null, "e": 8724, "s": 8394, "text": "In the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process.Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process." }, { "code": null, "e": 8978, "s": 8724, "text": "Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example:" }, { "code": null, "e": 9565, "s": 8978, "text": "Predict the Output of the following program:#include <stdio.h>#include <sys/types.h>#include <unistd.h> void forkexample(){ int x = 1; if (fork() == 0) printf(\"Child has x = %d\\n\", ++x); else printf(\"Parent has x = %d\\n\", --x);}int main(){ forkexample(); return 0;}Output:Parent has x = 0\nChild has x = 2\n (or)\nChild has x = 2\nParent has x = 0\nHere, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible." }, { "code": "#include <stdio.h>#include <sys/types.h>#include <unistd.h> void forkexample(){ int x = 1; if (fork() == 0) printf(\"Child has x = %d\\n\", ++x); else printf(\"Parent has x = %d\\n\", --x);}int main(){ forkexample(); return 0;}", "e": 9819, "s": 9565, "text": null }, { "code": null, "e": 9827, "s": 9819, "text": "Output:" }, { "code": null, "e": 9904, "s": 9827, "text": "Parent has x = 0\nChild has x = 2\n (or)\nChild has x = 2\nParent has x = 0\n" }, { "code": null, "e": 10111, "s": 9904, "text": "Here, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible." }, { "code": null, "e": 10128, "s": 10111, "text": "fork() vs exec()" }, { "code": null, "e": 10342, "s": 10128, "text": "The fork system call creates a new process. The new process created by fork() is a copy of the current process except for the returned value. The exec() system call replaces the current process with a new program." }, { "code": null, "e": 10352, "s": 10342, "text": "Exercise:" }, { "code": null, "e": 11168, "s": 10352, "text": "A process executes the following code:for (i = 0; i < n; i++) fork();The total number of child processes created is: (GATE-CS-2008)(A) n(B) 2^n – 1(C) 2^n(D) 2^(n+1) – 1;See this for solution.Consider the following code fragment:if (fork() == 0) { a = a + 5; printf(\"%d, %d\\n\", a, &a);}else { a = a –5; printf(\"%d, %d\\n\", a, &a);}Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != ySee this for solution.Predict output of below program.#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf(\"forked\\n\"); return 0;}See this for solution" }, { "code": null, "e": 11364, "s": 11168, "text": "A process executes the following code:for (i = 0; i < n; i++) fork();The total number of child processes created is: (GATE-CS-2008)(A) n(B) 2^n – 1(C) 2^n(D) 2^(n+1) – 1;See this for solution." }, { "code": "for (i = 0; i < n; i++) fork();", "e": 11399, "s": 11364, "text": null }, { "code": null, "e": 11501, "s": 11399, "text": "The total number of child processes created is: (GATE-CS-2008)(A) n(B) 2^n – 1(C) 2^n(D) 2^(n+1) – 1;" }, { "code": null, "e": 11524, "s": 11501, "text": "See this for solution." }, { "code": null, "e": 11952, "s": 11524, "text": "Consider the following code fragment:if (fork() == 0) { a = a + 5; printf(\"%d, %d\\n\", a, &a);}else { a = a –5; printf(\"%d, %d\\n\", a, &a);}Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != ySee this for solution." }, { "code": "if (fork() == 0) { a = a + 5; printf(\"%d, %d\\n\", a, &a);}else { a = a –5; printf(\"%d, %d\\n\", a, &a);}", "e": 12066, "s": 11952, "text": null }, { "code": null, "e": 12344, "s": 12066, "text": "Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)(A) u = x + 10 and v = y(B) u = x + 10 and v != y(C) u + 10 = x and v = y(D) u + 10 = x and v != ySee this for solution." }, { "code": null, "e": 12538, "s": 12344, "text": "Predict output of below program.#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf(\"forked\\n\"); return 0;}See this for solution" }, { "code": null, "e": 12571, "s": 12538, "text": "Predict output of below program." }, { "code": "#include <stdio.h>#include <unistd.h>int main(){ fork(); fork() && fork() || fork(); fork(); printf(\"forked\\n\"); return 0;}", "e": 12712, "s": 12571, "text": null }, { "code": null, "e": 12734, "s": 12712, "text": "See this for solution" }, { "code": null, "e": 12883, "s": 12734, "text": "Related Articles :C program to demonstrate fork() and pipe()Zombie and Orphan Processes in Cfork() and memory shared b/w processes created using it." }, { "code": null, "e": 12962, "s": 12883, "text": "References:http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html" }, { "code": null, "e": 13284, "s": 12962, "text": "This article is contributed by Team GeeksforGeeks and Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 13409, "s": 13284, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 13423, "s": 13409, "text": "FunniestClown" }, { "code": null, "e": 13433, "s": 13423, "text": "AndreiSas" }, { "code": null, "e": 13451, "s": 13433, "text": "reddydheerajreddy" }, { "code": null, "e": 13457, "s": 13451, "text": "4slan" }, { "code": null, "e": 13476, "s": 13457, "text": "jimbotherisenclown" }, { "code": null, "e": 13486, "s": 13476, "text": "C-Library" }, { "code": null, "e": 13505, "s": 13486, "text": "system-programming" }, { "code": null, "e": 13516, "s": 13505, "text": "C Language" } ]
Array Type Manipulation in C++
The array is a data structure in c++ that stored multiple data elements of the same data type in continuous memory locations. In c++ programming language, there are inbuilt functions to manipulate array types. Some functions can also be applied to multidimensional arrays. The array header file contains functions to manipulate arrays in c++ programming language. Some common methods to manipulate arrays in c++ are − This function is used to check if the variable passed to the function is of the type array or not. This method is strict in recognizing arrays that even std:: array is rejected in the check. The return type is an integer i.e. it returns true(1) if an array is passed otherwise False (0). Live Demo #include<type_traits> #include<iostream> #include<array> #include<string> using namespace std; int main(){ cout<<"Checking if int is an array ? : "; is_array<int>::value?cout<<"True":cout<<"False"; cout<<"\nChecking if int[] is an array? : "; is_array<int[6]>::value?cout<<"True":cout<<"False"; cout<<"\nChecking if 2D Array is an array? : "; is_array<int[2][3]>::value?cout<<"True":cout<<"False"; cout<<"\nChecking if String is an array? : "; is_array<string>::value?cout<<"True":cout<<"False"; cout<<"\nChecking if Character Array is an array? : "; is_array<char[4]>::value?cout<<"True":cout<<"False"; cout << endl; return 0; } Checking if int is an array ? : False Checking if int[] is an array? : True Checking if 2D Array is an array? : True Checking if String is an array? : False Checking if Character Array is an array? : True This function is used to check if the two types passed have exact same blueprints i.e. the types of both should be the same. Let’s see this example which will clear the concept − Live Demo #include<type_traits> #include<iostream> #include<array> #include<string> using namespace std; int main(){ cout << "Checking if 1D array is same as 1D array (Different sizes) ? : " ; is_same<int[3],int[4]>::value?cout<<"True":cout<<"False"; cout << "\nChecking if 1D array is same as 1D array? (Same sizes): " ; is_same<int[5],int[5]>::value?cout<<"True":cout<<"False"; cout << "\nChecking If 2D array is same as 1D array? : "; is_same<int[3],int[3][4]>::value?cout<<"True":cout<<"False"; cout << "\nChecking if Character array is same as Integer array? : " ; is_same<int[5],char[5]>::value?cout<<"True":cout<<"False"; return 0; } Checking if 1D array is same as 1D array (Different sizes) ? : False Checking if 1D array is same as 1D array? (Same sizes): True Checking If 2D array is same as 1D array? : False Checking if Character array is same as Integer array? : False The rank function is used to return the rank of the array passed. Rank means the dimension of the array. It returns an integer value of the rank of the array. Live Demo #include<type_traits> #include<iostream> using namespace std; int main(){ cout<<"Print rank for the following types of arrays : \n"; cout<<"integer : "<<rank<int>::value<<endl; cout<<"1D integer array (int[]) : "<< rank<int[5]>::value<<endl; cout<<"2D integer array (int[][]) : "<<rank<int[2][2]>::value<<endl; cout<<"3D integer array (int[][][]) : "<<rank<int[2][3][4]>::value<<endl; cout<<"1D character array : "<<rank<char[10]>::value<<endl; } Print rank for the following types of arrays : integer : 0 1D integer array (int[]) : 1 2D integer array (int[][]) : 2 3D integer array (int[][][]) : 3 1D character array : 1 The extent() method in c++ returns the size of a dimension of an array. There are two input parameters for this method, array, and the dimension. Live Demo #include<type_traits> #include<iostream> using namespace std; int main(){ cout<<"Printing the length of all dimensions of the array arr[2][45][5] :\n"; cout<<"1st dimension : "<<extent<int[2][45][5],0>::value<<endl; cout<<"2nd dimension : "<<extent<int[2][45][5],1>::value<<endl; cout<<"3rd dimension : "<<extent<int[2][45][5],2>::value<<endl; cout<<"4th dimension : "<<extent<int[2][45][5],3>::value<<endl; } Printing the length of all dimensions of the array arr[2][45][5] : 1st dimension : 2 2nd dimension : 45 3rd dimension : 5 4th dimension : 0 The remove_extent function is used to remove the dimension of a multidimensional array. It deletes the first dimension of the array. Live Demo #include<type_traits> #include<iostream> using namespace std; int main(){ cout<<"Removing extent of the array arr[2][5][4] : \n"; cout<<"Initial rank : "<<rank<int[2][5][4]>::value<<endl; cout<<"The rank after removing 1 extent is : " ; cout << rank<remove_extent<int[20][10][30]>::type>::value << endl; cout << "length of 1st dimension after removal is :"; cout<<extent<remove_extent<int[20][10][30]>::type>::value << endl; } Removing extent of the array arr[2][5][4] : Initial rank : 3 The rank after removing 1 extent is : 2 length of 1st dimension after removal is :10 This function is used to remove all the dimensions of the array in one go. The array is changed to a variable of the same as of array. Live Demo #include<type_traits> #include<iostream> using namespace std; int main(){ cout<<"Removing all extents of the array arr[2][5][4] : \n"; cout<<"Initial rank : "<<rank<int[2][5][4]>::value<<endl; cout<<"The rank after removing all extents is : " ; cout << rank<remove_all_extents<int[20][10][30]>::type>::value << endl; cout << "length of 1st dimension after removal is :"; cout<<extent<remove_all_extents<int[20][10][30]>::type>::value << endl; } Removing all extents of the array arr[2][5][4] : Initial rank : 3 The rank after removing all extents is : 0 length of 1st dimension after removal is :0
[ { "code": null, "e": 1313, "s": 1187, "text": "The array is a data structure in c++ that stored multiple data elements of the same data type in continuous memory locations." }, { "code": null, "e": 1551, "s": 1313, "text": "In c++ programming language, there are inbuilt functions to manipulate array types. Some functions can also be applied to multidimensional arrays. The array header file contains functions to manipulate arrays in c++ programming language." }, { "code": null, "e": 1605, "s": 1551, "text": "Some common methods to manipulate arrays in c++ are −" }, { "code": null, "e": 1893, "s": 1605, "text": "This function is used to check if the variable passed to the function is of the type array or not. This method is strict in recognizing arrays that even std:: array is rejected in the check. The return type is an integer i.e. it returns true(1) if an array is passed otherwise False (0)." }, { "code": null, "e": 1904, "s": 1893, "text": " Live Demo" }, { "code": null, "e": 2570, "s": 1904, "text": "#include<type_traits>\n#include<iostream>\n#include<array>\n#include<string>\nusing namespace std;\nint main(){\n cout<<\"Checking if int is an array ? : \";\n is_array<int>::value?cout<<\"True\":cout<<\"False\";\n cout<<\"\\nChecking if int[] is an array? : \";\n is_array<int[6]>::value?cout<<\"True\":cout<<\"False\";\n cout<<\"\\nChecking if 2D Array is an array? : \";\n is_array<int[2][3]>::value?cout<<\"True\":cout<<\"False\";\n cout<<\"\\nChecking if String is an array? : \";\n is_array<string>::value?cout<<\"True\":cout<<\"False\";\n cout<<\"\\nChecking if Character Array is an array? : \";\n is_array<char[4]>::value?cout<<\"True\":cout<<\"False\";\n cout << endl;\n return 0;\n}" }, { "code": null, "e": 2775, "s": 2570, "text": "Checking if int is an array ? : False\nChecking if int[] is an array? : True\nChecking if 2D Array is an array? : True\nChecking if String is an array? : False\nChecking if Character Array is an array? : True" }, { "code": null, "e": 2954, "s": 2775, "text": "This function is used to check if the two types passed have exact same blueprints i.e. the types of both should be the same. Let’s see this example which will clear the concept −" }, { "code": null, "e": 2965, "s": 2954, "text": " Live Demo" }, { "code": null, "e": 3623, "s": 2965, "text": "#include<type_traits>\n#include<iostream>\n#include<array>\n#include<string>\nusing namespace std;\nint main(){\n cout << \"Checking if 1D array is same as 1D array (Different sizes) ? : \" ;\n is_same<int[3],int[4]>::value?cout<<\"True\":cout<<\"False\";\n cout << \"\\nChecking if 1D array is same as 1D array? (Same sizes): \" ;\n is_same<int[5],int[5]>::value?cout<<\"True\":cout<<\"False\";\n cout << \"\\nChecking If 2D array is same as 1D array? : \";\n is_same<int[3],int[3][4]>::value?cout<<\"True\":cout<<\"False\";\n cout << \"\\nChecking if Character array is same as Integer array? : \" ;\n is_same<int[5],char[5]>::value?cout<<\"True\":cout<<\"False\";\n return 0;\n}" }, { "code": null, "e": 3865, "s": 3623, "text": "Checking if 1D array is same as 1D array (Different sizes) ? : False\nChecking if 1D array is same as 1D array? (Same sizes): True\nChecking If 2D array is same as 1D array? : False\nChecking if Character array is same as Integer array? : False" }, { "code": null, "e": 4024, "s": 3865, "text": "The rank function is used to return the rank of the array passed. Rank means the dimension of the array. It returns an integer value of the rank of the array." }, { "code": null, "e": 4035, "s": 4024, "text": " Live Demo" }, { "code": null, "e": 4500, "s": 4035, "text": "#include<type_traits>\n#include<iostream>\nusing namespace std;\nint main(){\n cout<<\"Print rank for the following types of arrays : \\n\";\n cout<<\"integer : \"<<rank<int>::value<<endl;\n cout<<\"1D integer array (int[]) : \"<< rank<int[5]>::value<<endl;\n cout<<\"2D integer array (int[][]) : \"<<rank<int[2][2]>::value<<endl;\n cout<<\"3D integer array (int[][][]) : \"<<rank<int[2][3][4]>::value<<endl;\n cout<<\"1D character array : \"<<rank<char[10]>::value<<endl;\n}" }, { "code": null, "e": 4675, "s": 4500, "text": "Print rank for the following types of arrays :\ninteger : 0\n1D integer array (int[]) : 1\n2D integer array (int[][]) : 2\n3D integer array (int[][][]) : 3\n1D character array : 1" }, { "code": null, "e": 4821, "s": 4675, "text": "The extent() method in c++ returns the size of a dimension of an array. There are two input parameters for this method, array, and the dimension." }, { "code": null, "e": 4832, "s": 4821, "text": " Live Demo" }, { "code": null, "e": 5257, "s": 4832, "text": "#include<type_traits>\n#include<iostream>\nusing namespace std;\nint main(){\n cout<<\"Printing the length of all dimensions of the array arr[2][45][5] :\\n\";\n cout<<\"1st dimension : \"<<extent<int[2][45][5],0>::value<<endl;\n cout<<\"2nd dimension : \"<<extent<int[2][45][5],1>::value<<endl;\n cout<<\"3rd dimension : \"<<extent<int[2][45][5],2>::value<<endl;\n cout<<\"4th dimension : \"<<extent<int[2][45][5],3>::value<<endl;\n}" }, { "code": null, "e": 5397, "s": 5257, "text": "Printing the length of all dimensions of the array arr[2][45][5] :\n1st dimension : 2\n2nd dimension : 45\n3rd dimension : 5\n4th dimension : 0" }, { "code": null, "e": 5530, "s": 5397, "text": "The remove_extent function is used to remove the dimension of a multidimensional array. It deletes the first dimension of the array." }, { "code": null, "e": 5541, "s": 5530, "text": " Live Demo" }, { "code": null, "e": 5986, "s": 5541, "text": "#include<type_traits>\n#include<iostream>\nusing namespace std;\nint main(){\n cout<<\"Removing extent of the array arr[2][5][4] : \\n\";\n cout<<\"Initial rank : \"<<rank<int[2][5][4]>::value<<endl;\n cout<<\"The rank after removing 1 extent is : \" ;\n cout << rank<remove_extent<int[20][10][30]>::type>::value << endl;\n cout << \"length of 1st dimension after removal is :\";\n cout<<extent<remove_extent<int[20][10][30]>::type>::value << endl;\n}" }, { "code": null, "e": 6132, "s": 5986, "text": "Removing extent of the array arr[2][5][4] :\nInitial rank : 3\nThe rank after removing 1 extent is : 2\nlength of 1st dimension after removal is :10" }, { "code": null, "e": 6267, "s": 6132, "text": "This function is used to remove all the dimensions of the array in one go. The array is changed to a variable of the same as of array." }, { "code": null, "e": 6278, "s": 6267, "text": " Live Demo" }, { "code": null, "e": 6741, "s": 6278, "text": "#include<type_traits>\n#include<iostream>\nusing namespace std;\nint main(){\n cout<<\"Removing all extents of the array arr[2][5][4] : \\n\";\n cout<<\"Initial rank : \"<<rank<int[2][5][4]>::value<<endl;\n cout<<\"The rank after removing all extents is : \" ;\n cout << rank<remove_all_extents<int[20][10][30]>::type>::value << endl;\n cout << \"length of 1st dimension after removal is :\";\n cout<<extent<remove_all_extents<int[20][10][30]>::type>::value << endl;\n}" }, { "code": null, "e": 6894, "s": 6741, "text": "Removing all extents of the array arr[2][5][4] :\nInitial rank : 3\nThe rank after removing all extents is : 0\nlength of 1st dimension after removal is :0" } ]
Number of digits to be removed to make a number divisible by 3
08 Jun, 2022 Given a very large number num (1 <= num <= 10^1000), print the number of digits that needs to be removed to make the number exactly divisible by 3. If it is not possible then print -1. Examples : Input: num = "1234" Output: 1 Explanation: we need to remove one digit that is 1 or 4, to make the number divisible by 3.on Input: num = "11" Output: -1 Explanation: It is not possible to remove any digits and make it divisible by 3. The idea is based on the fact that a number is multiple of 3 if and only if sum of its digits is multiple of 3 (See this for details).One important observation used here is that the answer is at most 2 if an answer exists. So here are the only options for the function: Sum of digits is already equal to 0 modulo 3. Thus, we don’t have to erase any digits.There exists such a digit that equals sum modulo 3. Then we just have to erase a single digitAll the digits are neither divisible by 3 nor equal to sum modulo 3. So two of such digits will sum up to number, which equals sum modulo 3, (2+2) mod 3=1, (1+1) mod 3=2 Sum of digits is already equal to 0 modulo 3. Thus, we don’t have to erase any digits. There exists such a digit that equals sum modulo 3. Then we just have to erase a single digit All the digits are neither divisible by 3 nor equal to sum modulo 3. So two of such digits will sum up to number, which equals sum modulo 3, (2+2) mod 3=1, (1+1) mod 3=2 C++ Java Python3 C# PHP Javascript // CPP program to find the minimum number of// digits to be removed to make a large number// divisible by 3.#include <bits/stdc++.h>using namespace std; // function to count the no of removal of digits// to make a very large number divisible by 3int divisible(string num){ int n = num.length(); // add up all the digits of num int sum = accumulate(begin(num), end(num), 0) - '0' * 1; // if num is already is divisible by 3 // then no digits are to be removed if (sum % 3 == 0) return 0; // if there is single digit, then it is // not possible to remove one digit. if (n == 1) return -1; // traverse through the number and find out // if any number on removal makes the sum // divisible by 3 for (int i = 0; i < n; i++) if (sum % 3 == (num[i] - '0') % 3) return 1; // if there are two numbers then it is // not possible to remove two digits. if (n == 2) return -1; // Otherwise we can always make a number // multiple of 2 by removing 2 digits. return 2;} // Driver Codeint main(){ string num = "1234"; cout << divisible(num); return 0;} // Java program to find the// minimum number of digits// to be removed to make a// large number divisible by 3.import java.io.*; // function to count the no// of removal of digits// to make a very large// number divisible by 3class GFG { static int divisible(String num) { int n = num.length(); // add up all the // digits of num int sum = 0; for (int i = 0; i < n; i++) sum += (int)(num.charAt(i)); // if num is already is // divisible by 3 then // no digits are to be // removed if (sum % 3 == 0) return 0; // if there is single digit, // then it is not possible // to remove one digit. if (n == 1) return -1; // traverse through the number // and find out if any number // on removal makes the sum // divisible by 3 for (int i = 0; i < n; i++) if (sum % 3 == (num.charAt(i) - '0') % 3) return 1; // if there are two numbers // then it is not possible // to remove two digits. if (n == 2) return -1; // Otherwise we can always // make a number multiple // of 2 by removing 2 digits. return 2; } // Driver Code public static void main(String[] args) { String num = "1234"; System.out.println(divisible(num)); }} // This code is contributed by Raj # Python3 program to find the# minimum number of digits to# be removed to make a large# number divisible by 3. # function to count the# no of removal of digits# to make a very large# number divisible by 3 def divisible(num): n = len(num) # add up all the digits of num sum_ = 0 for i in range(n): sum_ += int(num[i]) # if num is already is # divisible by 3 then no # digits are to be removed if (sum_ % 3 == 0): return 0 # if there is single digit, # then it is not possible # to remove one digit. if (n == 1): return -1 # traverse through the number # and find out if any number # on removal makes the sum # divisible by 3 for i in range(n): if (sum_ % 3 == int(num[i]) % 3): return 1 # if there are two numbers # then it is not possible # to remove two digits. if (n == 2): return -1 # Otherwise we can always # make a number multiple of # 2 by removing 2 digits. return 2 # Driver Codeif __name__ == '__main__': num = "1234" print(divisible(num)) # This code is contributed by mits // C# program to find the// minimum number of digits// to be removed to make a// large number divisible by 3.using System; // function to count the no// of removal of digits// to make a very large// number divisible by 3class GFG { static int divisible(String num) { int n = num.Length; // add up all the // digits of num int sum = 0; for (int i = 0; i < n; i++) sum += (int)(num[i]); // if num is already is // divisible by 3 then // no digits are to be // removed if (sum % 3 == 0) return 0; // if there is single digit, // then it is not possible // to remove one digit. if (n == 1) return -1; // traverse through the number // and find out if any number // on removal makes the sum // divisible by 3 for (int i = 0; i < n; i++) if (sum % 3 == (num[i] - '0') % 3) return 1; // if there are two numbers // then it is not possible // to remove two digits. if (n == 2) return -1; // Otherwise we can always // make a number multiple // of 2 by removing 2 digits. return 2; } // Driver Code public static void Main() { string num = "1234"; Console.WriteLine(divisible(num)); }} // This code is contributed by mits <?php// PHP program to find the// minimum number of digits to// be removed to make a large// number divisible by 3. // function to count the// no of removal of digits// to make a very large// number divisible by 3 function divisible($num){ $n = strlen($num); // add up all the digits of num $sum = ($num); ($num); 0 - '0'; // if num is already is // divisible by 3 then no // digits are to be removed if ($sum % 3 == 0) return 0; // if there is single digit, // then it is not possible // to remove one digit. if ($n == 1) return -1; // traverse through the number // and find out if any number // on removal makes the sum // divisible by 3 for ($i = 0; $i < $n; $i++) if ($sum % 3 == ($num[$i] - '0') % 3) return 1; // if there are two numbers // then it is not possible // to remove two digits. if ($n == 2) return -1; // Otherwise we can always // make a number multiple of // 2 by removing 2 digits. return 2;} // Driver Code$num = "1234";echo divisible($num); // This code is contributed by ajit?> <script> // JavaScript program to find the minimum number of// digits to be removed to make a large number// divisible by 3. // function to count the no of removal of digits// to make a very large number divisible by 3function divisible(num){ let n = num.length; // add up all the digits of num let sum = 0; for (let i = 0; i < n; i++) sum += (num.charAt(i)); // if num is already is divisible by 3 // then no digits are to be removed if (sum % 3 == 0) return 0; // if there is single digit, then it is // not possible to remove one digit. if (n == 1) return -1; // traverse through the number and find out // if any number on removal makes the sum // divisible by 3 for (let i = 0; i < n; i++) if (sum % 3 == (num.charAt(i) - '0') % 3) return 1; // if there are two numbers then it is // not possible to remove two digits. if (n == 2) return -1; // Otherwise we can always make a number // multiple of 2 by removing 2 digits. return 2;} // Driver Code let num = "1234"; document.write(divisible(num)); // This code is contributed by Surbhi Tyagi. </script> Output : 1 Time Complexity: O(N), as we are using a loop to traverse N times. Auxiliary Space: O(1), as we are not using any extra space. This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar R_Raj expensiveassh0l3 surbhityagi15 rohan07 divisibility large-numbers Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Minimum number of jumps to reach end Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 239, "s": 54, "text": "Given a very large number num (1 <= num <= 10^1000), print the number of digits that needs to be removed to make the number exactly divisible by 3. If it is not possible then print -1." }, { "code": null, "e": 251, "s": 239, "text": "Examples : " }, { "code": null, "e": 490, "s": 251, "text": "Input: num = \"1234\"\nOutput: 1\nExplanation: we need to remove one \ndigit that is 1 or 4, to make the\nnumber divisible by 3.on \n\nInput: num = \"11\"\nOutput: -1\nExplanation: It is not possible to \nremove any digits and make it divisible\nby 3. " }, { "code": null, "e": 761, "s": 490, "text": "The idea is based on the fact that a number is multiple of 3 if and only if sum of its digits is multiple of 3 (See this for details).One important observation used here is that the answer is at most 2 if an answer exists. So here are the only options for the function: " }, { "code": null, "e": 1110, "s": 761, "text": "Sum of digits is already equal to 0 modulo 3. Thus, we don’t have to erase any digits.There exists such a digit that equals sum modulo 3. Then we just have to erase a single digitAll the digits are neither divisible by 3 nor equal to sum modulo 3. So two of such digits will sum up to number, which equals sum modulo 3, (2+2) mod 3=1, (1+1) mod 3=2" }, { "code": null, "e": 1197, "s": 1110, "text": "Sum of digits is already equal to 0 modulo 3. Thus, we don’t have to erase any digits." }, { "code": null, "e": 1291, "s": 1197, "text": "There exists such a digit that equals sum modulo 3. Then we just have to erase a single digit" }, { "code": null, "e": 1461, "s": 1291, "text": "All the digits are neither divisible by 3 nor equal to sum modulo 3. So two of such digits will sum up to number, which equals sum modulo 3, (2+2) mod 3=1, (1+1) mod 3=2" }, { "code": null, "e": 1465, "s": 1461, "text": "C++" }, { "code": null, "e": 1470, "s": 1465, "text": "Java" }, { "code": null, "e": 1478, "s": 1470, "text": "Python3" }, { "code": null, "e": 1481, "s": 1478, "text": "C#" }, { "code": null, "e": 1485, "s": 1481, "text": "PHP" }, { "code": null, "e": 1496, "s": 1485, "text": "Javascript" }, { "code": "// CPP program to find the minimum number of// digits to be removed to make a large number// divisible by 3.#include <bits/stdc++.h>using namespace std; // function to count the no of removal of digits// to make a very large number divisible by 3int divisible(string num){ int n = num.length(); // add up all the digits of num int sum = accumulate(begin(num), end(num), 0) - '0' * 1; // if num is already is divisible by 3 // then no digits are to be removed if (sum % 3 == 0) return 0; // if there is single digit, then it is // not possible to remove one digit. if (n == 1) return -1; // traverse through the number and find out // if any number on removal makes the sum // divisible by 3 for (int i = 0; i < n; i++) if (sum % 3 == (num[i] - '0') % 3) return 1; // if there are two numbers then it is // not possible to remove two digits. if (n == 2) return -1; // Otherwise we can always make a number // multiple of 2 by removing 2 digits. return 2;} // Driver Codeint main(){ string num = \"1234\"; cout << divisible(num); return 0;}", "e": 2668, "s": 1496, "text": null }, { "code": "// Java program to find the// minimum number of digits// to be removed to make a// large number divisible by 3.import java.io.*; // function to count the no// of removal of digits// to make a very large// number divisible by 3class GFG { static int divisible(String num) { int n = num.length(); // add up all the // digits of num int sum = 0; for (int i = 0; i < n; i++) sum += (int)(num.charAt(i)); // if num is already is // divisible by 3 then // no digits are to be // removed if (sum % 3 == 0) return 0; // if there is single digit, // then it is not possible // to remove one digit. if (n == 1) return -1; // traverse through the number // and find out if any number // on removal makes the sum // divisible by 3 for (int i = 0; i < n; i++) if (sum % 3 == (num.charAt(i) - '0') % 3) return 1; // if there are two numbers // then it is not possible // to remove two digits. if (n == 2) return -1; // Otherwise we can always // make a number multiple // of 2 by removing 2 digits. return 2; } // Driver Code public static void main(String[] args) { String num = \"1234\"; System.out.println(divisible(num)); }} // This code is contributed by Raj", "e": 4118, "s": 2668, "text": null }, { "code": "# Python3 program to find the# minimum number of digits to# be removed to make a large# number divisible by 3. # function to count the# no of removal of digits# to make a very large# number divisible by 3 def divisible(num): n = len(num) # add up all the digits of num sum_ = 0 for i in range(n): sum_ += int(num[i]) # if num is already is # divisible by 3 then no # digits are to be removed if (sum_ % 3 == 0): return 0 # if there is single digit, # then it is not possible # to remove one digit. if (n == 1): return -1 # traverse through the number # and find out if any number # on removal makes the sum # divisible by 3 for i in range(n): if (sum_ % 3 == int(num[i]) % 3): return 1 # if there are two numbers # then it is not possible # to remove two digits. if (n == 2): return -1 # Otherwise we can always # make a number multiple of # 2 by removing 2 digits. return 2 # Driver Codeif __name__ == '__main__': num = \"1234\" print(divisible(num)) # This code is contributed by mits", "e": 5238, "s": 4118, "text": null }, { "code": "// C# program to find the// minimum number of digits// to be removed to make a// large number divisible by 3.using System; // function to count the no// of removal of digits// to make a very large// number divisible by 3class GFG { static int divisible(String num) { int n = num.Length; // add up all the // digits of num int sum = 0; for (int i = 0; i < n; i++) sum += (int)(num[i]); // if num is already is // divisible by 3 then // no digits are to be // removed if (sum % 3 == 0) return 0; // if there is single digit, // then it is not possible // to remove one digit. if (n == 1) return -1; // traverse through the number // and find out if any number // on removal makes the sum // divisible by 3 for (int i = 0; i < n; i++) if (sum % 3 == (num[i] - '0') % 3) return 1; // if there are two numbers // then it is not possible // to remove two digits. if (n == 2) return -1; // Otherwise we can always // make a number multiple // of 2 by removing 2 digits. return 2; } // Driver Code public static void Main() { string num = \"1234\"; Console.WriteLine(divisible(num)); }} // This code is contributed by mits", "e": 6652, "s": 5238, "text": null }, { "code": "<?php// PHP program to find the// minimum number of digits to// be removed to make a large// number divisible by 3. // function to count the// no of removal of digits// to make a very large// number divisible by 3 function divisible($num){ $n = strlen($num); // add up all the digits of num $sum = ($num); ($num); 0 - '0'; // if num is already is // divisible by 3 then no // digits are to be removed if ($sum % 3 == 0) return 0; // if there is single digit, // then it is not possible // to remove one digit. if ($n == 1) return -1; // traverse through the number // and find out if any number // on removal makes the sum // divisible by 3 for ($i = 0; $i < $n; $i++) if ($sum % 3 == ($num[$i] - '0') % 3) return 1; // if there are two numbers // then it is not possible // to remove two digits. if ($n == 2) return -1; // Otherwise we can always // make a number multiple of // 2 by removing 2 digits. return 2;} // Driver Code$num = \"1234\";echo divisible($num); // This code is contributed by ajit?>", "e": 7780, "s": 6652, "text": null }, { "code": "<script> // JavaScript program to find the minimum number of// digits to be removed to make a large number// divisible by 3. // function to count the no of removal of digits// to make a very large number divisible by 3function divisible(num){ let n = num.length; // add up all the digits of num let sum = 0; for (let i = 0; i < n; i++) sum += (num.charAt(i)); // if num is already is divisible by 3 // then no digits are to be removed if (sum % 3 == 0) return 0; // if there is single digit, then it is // not possible to remove one digit. if (n == 1) return -1; // traverse through the number and find out // if any number on removal makes the sum // divisible by 3 for (let i = 0; i < n; i++) if (sum % 3 == (num.charAt(i) - '0') % 3) return 1; // if there are two numbers then it is // not possible to remove two digits. if (n == 2) return -1; // Otherwise we can always make a number // multiple of 2 by removing 2 digits. return 2;} // Driver Code let num = \"1234\"; document.write(divisible(num)); // This code is contributed by Surbhi Tyagi. </script>", "e": 8962, "s": 7780, "text": null }, { "code": null, "e": 8972, "s": 8962, "text": "Output : " }, { "code": null, "e": 8974, "s": 8972, "text": "1" }, { "code": null, "e": 9041, "s": 8974, "text": "Time Complexity: O(N), as we are using a loop to traverse N times." }, { "code": null, "e": 9101, "s": 9041, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 9517, "s": 9101, "text": "This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9523, "s": 9517, "text": "jit_t" }, { "code": null, "e": 9536, "s": 9523, "text": "Mithun Kumar" }, { "code": null, "e": 9542, "s": 9536, "text": "R_Raj" }, { "code": null, "e": 9559, "s": 9542, "text": "expensiveassh0l3" }, { "code": null, "e": 9573, "s": 9559, "text": "surbhityagi15" }, { "code": null, "e": 9581, "s": 9573, "text": "rohan07" }, { "code": null, "e": 9594, "s": 9581, "text": "divisibility" }, { "code": null, "e": 9608, "s": 9594, "text": "large-numbers" }, { "code": null, "e": 9621, "s": 9608, "text": "Mathematical" }, { "code": null, "e": 9634, "s": 9621, "text": "Mathematical" }, { "code": null, "e": 9732, "s": 9634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9756, "s": 9732, "text": "Merge two sorted arrays" }, { "code": null, "e": 9777, "s": 9756, "text": "Operators in C / C++" }, { "code": null, "e": 9791, "s": 9777, "text": "Prime Numbers" }, { "code": null, "e": 9813, "s": 9791, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 9855, "s": 9813, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 9908, "s": 9855, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 9940, "s": 9908, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 9977, "s": 9940, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 10004, "s": 9977, "text": "Modulo 10^9+7 (1000000007)" } ]
Convert String or String Array to HashMap In Java
08 Dec, 2020 Considering a string object that contains the student name and roll number separated by a comma, and each student contains the name and roll number separated by a colon. Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object. In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output. Input as an array of strings is converted to HashMap. Input string elements as follows: Input : "Aashish:1, Bina:2, Chintu:3" Approach : Phase 1: The input string is converted to an array of strings as output. Phase 2: Input as an array of strings is converted to HashMap. Phase 1: First, we split the String by a comma and store it in an array parts. After the split we have the following content: "Aashish:1","Bina:2", "Chintu:3" And then iterate on parts and split the student data to get the student name and roll number. And set roll no as key and the name as the value of the HashMap. Phase 2: We can also convert an array of String to a HashMap. Suppose we have a string array of the student name and an array of roll numbers, and we want to convert it to HashMap so the roll number becomes the key of the HashMap and the name becomes the value of the HashMap. Note: Both the arrays should be the same size. Input array of string elements as follows which will be output in phase 1 String stuName[] = {"Aashish","Bina","Chintu"} Integer stuRollNo[] = {1,2,3} Approach : Iterate over the array and set the roll number as key and the name as values in the HashMap. Phase 1 – String to Array of string Java // Convert String or String array to HashMap In Java // Phase 1: Input- String converted to ArrayofStrings // Importing java generic librariesimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // String object that contains the student name and // roll number separated by a comma String student = "Aashish:1, Bina:2, Chintu:3"; // New HashMap obj Map<String, String> hashMap = new HashMap<String, String>(); // split the String by a comma String parts[] = student.split(","); // iterate the parts and add them to a HashMap for (String part : parts) { // split the student data by colon to get the // name and roll number String stuData[] = part.split(":"); String stuRollNo = stuData[0].trim(); String stuName = stuData[1].trim(); // Add to map hashMap.put(stuRollNo, stuName); } // Print hashMap System.out.println("String to HashMap: " + hashMap); }} String to HashMap: {Chintu=3, Bina=2, Aashish=1} Phase 2 – String to Array to HashMap Java // Convert String or String array to HashMap In Java // Phase 2: Input- Array of strings converted to HashMap. // Importing java generic librariesimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // String array that contains the student name String stuName[] = { "Aashish", "Bina", "Chintu" }; // Integer array that contains roll number of the // students Integer stuRollNo[] = { 1, 2, 3 }; // New HashMap obj Map<Integer, String> hashMap = new HashMap<Integer, String>(); // Iterating over array of strings for (int i = 0; i < stuName.length; i++) { // And set roll no as key and the name as value hashMap.put(stuRollNo[i], stuName[i]); } // Printing HashMap System.out.println("String to hashmap: " + hashMap); }} String to hashmap: {1=Aashish, 2=Bina, 3=Chintu} Java-Collections Java-HashMap Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2020" }, { "code": null, "e": 368, "s": 28, "text": "Considering a string object that contains the student name and roll number separated by a comma, and each student contains the name and roll number separated by a colon. Now need is to convert the String to a Map object so that each student roll number becomes the key of the HashMap, and the name becomes the value of the HashMap object. " }, { "code": null, "e": 447, "s": 368, "text": "In order to convert strings to HashMap, the process is divided into two parts:" }, { "code": null, "e": 511, "s": 447, "text": "The input string is converted to an array of strings as output." }, { "code": null, "e": 565, "s": 511, "text": "Input as an array of strings is converted to HashMap." }, { "code": null, "e": 600, "s": 565, "text": " Input string elements as follows:" }, { "code": null, "e": 638, "s": 600, "text": "Input : \"Aashish:1, Bina:2, Chintu:3\"" }, { "code": null, "e": 650, "s": 638, "text": "Approach : " }, { "code": null, "e": 723, "s": 650, "text": "Phase 1: The input string is converted to an array of strings as output." }, { "code": null, "e": 786, "s": 723, "text": "Phase 2: Input as an array of strings is converted to HashMap." }, { "code": null, "e": 795, "s": 786, "text": "Phase 1:" }, { "code": null, "e": 912, "s": 795, "text": "First, we split the String by a comma and store it in an array parts. After the split we have the following content:" }, { "code": null, "e": 945, "s": 912, "text": "\"Aashish:1\",\"Bina:2\", \"Chintu:3\"" }, { "code": null, "e": 1104, "s": 945, "text": "And then iterate on parts and split the student data to get the student name and roll number. And set roll no as key and the name as the value of the HashMap." }, { "code": null, "e": 1113, "s": 1104, "text": "Phase 2:" }, { "code": null, "e": 1381, "s": 1113, "text": "We can also convert an array of String to a HashMap. Suppose we have a string array of the student name and an array of roll numbers, and we want to convert it to HashMap so the roll number becomes the key of the HashMap and the name becomes the value of the HashMap." }, { "code": null, "e": 1428, "s": 1381, "text": "Note: Both the arrays should be the same size." }, { "code": null, "e": 1502, "s": 1428, "text": "Input array of string elements as follows which will be output in phase 1" }, { "code": null, "e": 1579, "s": 1502, "text": "String stuName[] = {\"Aashish\",\"Bina\",\"Chintu\"}\nInteger stuRollNo[] = {1,2,3}" }, { "code": null, "e": 1591, "s": 1579, "text": "Approach : " }, { "code": null, "e": 1684, "s": 1591, "text": "Iterate over the array and set the roll number as key and the name as values in the HashMap." }, { "code": null, "e": 1720, "s": 1684, "text": "Phase 1 – String to Array of string" }, { "code": null, "e": 1725, "s": 1720, "text": "Java" }, { "code": "// Convert String or String array to HashMap In Java // Phase 1: Input- String converted to ArrayofStrings // Importing java generic librariesimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // String object that contains the student name and // roll number separated by a comma String student = \"Aashish:1, Bina:2, Chintu:3\"; // New HashMap obj Map<String, String> hashMap = new HashMap<String, String>(); // split the String by a comma String parts[] = student.split(\",\"); // iterate the parts and add them to a HashMap for (String part : parts) { // split the student data by colon to get the // name and roll number String stuData[] = part.split(\":\"); String stuRollNo = stuData[0].trim(); String stuName = stuData[1].trim(); // Add to map hashMap.put(stuRollNo, stuName); } // Print hashMap System.out.println(\"String to HashMap: \" + hashMap); }}", "e": 2826, "s": 1725, "text": null }, { "code": null, "e": 2875, "s": 2826, "text": "String to HashMap: {Chintu=3, Bina=2, Aashish=1}" }, { "code": null, "e": 2912, "s": 2875, "text": "Phase 2 – String to Array to HashMap" }, { "code": null, "e": 2917, "s": 2912, "text": "Java" }, { "code": "// Convert String or String array to HashMap In Java // Phase 2: Input- Array of strings converted to HashMap. // Importing java generic librariesimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // String array that contains the student name String stuName[] = { \"Aashish\", \"Bina\", \"Chintu\" }; // Integer array that contains roll number of the // students Integer stuRollNo[] = { 1, 2, 3 }; // New HashMap obj Map<Integer, String> hashMap = new HashMap<Integer, String>(); // Iterating over array of strings for (int i = 0; i < stuName.length; i++) { // And set roll no as key and the name as value hashMap.put(stuRollNo[i], stuName[i]); } // Printing HashMap System.out.println(\"String to hashmap: \" + hashMap); }}", "e": 3823, "s": 2917, "text": null }, { "code": null, "e": 3872, "s": 3823, "text": "String to hashmap: {1=Aashish, 2=Bina, 3=Chintu}" }, { "code": null, "e": 3889, "s": 3872, "text": "Java-Collections" }, { "code": null, "e": 3902, "s": 3889, "text": "Java-HashMap" }, { "code": null, "e": 3909, "s": 3902, "text": "Picked" }, { "code": null, "e": 3914, "s": 3909, "text": "Java" }, { "code": null, "e": 3928, "s": 3914, "text": "Java Programs" }, { "code": null, "e": 3933, "s": 3928, "text": "Java" }, { "code": null, "e": 3950, "s": 3933, "text": "Java-Collections" } ]
Matplotlib.pyplot.axvline() in Python
21 Apr, 2020 Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more information, refer to Python Matplotlib – An Overview Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source. Note: For more information, refer to Pyplot in Matplotlib This function add the vertical lines across the axes of the plot Syntax:matplotlib.pyplot.axvline(x=0, ymin=0, ymax=1, **kwargs) Parameters:x : x position in data coordinates to place the vertical lineymin :vertical line starting position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axisymax :vertical line ending position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis**kwargs :Other optional parameters to change the properties of the line, likechanging color, linewidth etc Example-1: # Importing matplotlib.pyplot as pltimport matplotlib.pyplot as plt # Initialising values of x and yx =[0, 5, 10, 15, 20]y =[1, 3, 5, 6, 9] # Plotting the graphplt.plot(x, y) # Drawing red vertical line at# x = 2.5 starting at half the #length of y axis(ymin = 0.5) and #continuing till the end(ymax = 1)# And setting the color of line to redplt.axvline(x = 2.5, ymin = 0.5, ymax = 1, color ='red') plt.show() Output : Example-2 : import matplotlib.pyplot as plt x =[0, 5, 10, 15, 20]y =[1, 3, 5, 6, 9] plt.plot(x, y)# Drawing vertical line from 25 % # of the y-axis length to 80 % # And also increasing the linewidthplt.axvline(x = 2.5, ymin = 0.25, ymax = 0.80, linewidth = 8, color ='green') plt.show() Output: Example-3 : import matplotlib.pyplot as plt x =[0, 5, 10, 15, 20]y =[1, 3, 5, 6, 9] plt.plot(x, y) # Drawing vertical line from 25 %# of the y-axis length to 75 % # And also changing the linestyleplt.axvline(x = 2.5, ymin = 0.25, ymax = 0.75, linewidth = 4, linestyle ="--", color ='red') plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 307, "s": 28, "text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc." }, { "code": null, "e": 376, "s": 307, "text": "Note: For more information, refer to Python Matplotlib – An Overview" }, { "code": null, "e": 576, "s": 376, "text": "Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source." }, { "code": null, "e": 634, "s": 576, "text": "Note: For more information, refer to Pyplot in Matplotlib" }, { "code": null, "e": 699, "s": 634, "text": "This function add the vertical lines across the axes of the plot" }, { "code": null, "e": 763, "s": 699, "text": "Syntax:matplotlib.pyplot.axvline(x=0, ymin=0, ymax=1, **kwargs)" }, { "code": null, "e": 1215, "s": 763, "text": "Parameters:x : x position in data coordinates to place the vertical lineymin :vertical line starting position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axisymax :vertical line ending position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis**kwargs :Other optional parameters to change the properties of the line, likechanging color, linewidth etc" }, { "code": null, "e": 1226, "s": 1215, "text": "Example-1:" }, { "code": "# Importing matplotlib.pyplot as pltimport matplotlib.pyplot as plt # Initialising values of x and yx =[0, 5, 10, 15, 20]y =[1, 3, 5, 6, 9] # Plotting the graphplt.plot(x, y) # Drawing red vertical line at# x = 2.5 starting at half the #length of y axis(ymin = 0.5) and #continuing till the end(ymax = 1)# And setting the color of line to redplt.axvline(x = 2.5, ymin = 0.5, ymax = 1, color ='red') plt.show()", "e": 1653, "s": 1226, "text": null }, { "code": null, "e": 1662, "s": 1653, "text": "Output :" }, { "code": null, "e": 1674, "s": 1662, "text": "Example-2 :" }, { "code": "import matplotlib.pyplot as plt x =[0, 5, 10, 15, 20]y =[1, 3, 5, 6, 9] plt.plot(x, y)# Drawing vertical line from 25 % # of the y-axis length to 80 % # And also increasing the linewidthplt.axvline(x = 2.5, ymin = 0.25, ymax = 0.80, linewidth = 8, color ='green') plt.show()", "e": 1963, "s": 1674, "text": null }, { "code": null, "e": 1971, "s": 1963, "text": "Output:" }, { "code": null, "e": 1983, "s": 1971, "text": "Example-3 :" }, { "code": "import matplotlib.pyplot as plt x =[0, 5, 10, 15, 20]y =[1, 3, 5, 6, 9] plt.plot(x, y) # Drawing vertical line from 25 %# of the y-axis length to 75 % # And also changing the linestyleplt.axvline(x = 2.5, ymin = 0.25, ymax = 0.75, linewidth = 4, linestyle =\"--\", color ='red') plt.show()", "e": 2297, "s": 1983, "text": null }, { "code": null, "e": 2305, "s": 2297, "text": "Output:" }, { "code": null, "e": 2323, "s": 2305, "text": "Python-matplotlib" }, { "code": null, "e": 2330, "s": 2323, "text": "Python" }, { "code": null, "e": 2428, "s": 2330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2446, "s": 2428, "text": "Python Dictionary" }, { "code": null, "e": 2488, "s": 2446, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2510, "s": 2488, "text": "Enumerate() in Python" }, { "code": null, "e": 2545, "s": 2510, "text": "Read a file line by line in Python" }, { "code": null, "e": 2571, "s": 2545, "text": "Python String | replace()" }, { "code": null, "e": 2603, "s": 2571, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2632, "s": 2603, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2659, "s": 2632, "text": "Python Classes and Objects" }, { "code": null, "e": 2689, "s": 2659, "text": "Iterate over a list in Python" } ]
How to print string with double quotes in Golang?
04 May, 2020 Whenever the user wants to double-quote a string, he can’t simply write the string within double quotes inside the fmt.Printf() command. This prints only the text written inside those quotes. To print the string along with quotes, he can use various methods including certain escape characters. There are different ways in Golang to print a string with double-quotes. 1) Quoting a string using %q: Syntax: fmt.Printf("%q", output) package main import "fmt" func main() { var result = "Welcome to GeeksforGeeks." fmt.Printf("%q", result)} Output: "Welcome to GeeksforGeeks." Explanation: In the above example, we used “%q” to display our string with double-quotes. 2) Quoting a string using an escape character “\”: Syntax: fmt.Println("\"string\"") package main import "fmt" func main() { fmt.Println("\"GeeksforGeeks is a computer science portal\"")} Output: "GeeksforGeeks is a computer science portal" Explanation: In the above example, we used an escape character “\” to print a string with double-quotes. We can simply do so by adding a backslash(\) before the double-quotes. 3) Double quoting a string using a raw string lateral (`): Syntax: fmt.Println(`"string\"`) package main import "fmt" func main() { fmt.Println(`"GeeksforGeeks"`)} Output: "GeeksforGeeks" Explanation: In the above example, we used a raw string lateral (`) to print a string with double-quotes. Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to convert a string in lower case in Golang? How to Parse JSON in Golang? How to Trim a String in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n04 May, 2020" }, { "code": null, "e": 396, "s": 28, "text": "Whenever the user wants to double-quote a string, he can’t simply write the string within double quotes inside the fmt.Printf() command. This prints only the text written inside those quotes. To print the string along with quotes, he can use various methods including certain escape characters. There are different ways in Golang to print a string with double-quotes." }, { "code": null, "e": 426, "s": 396, "text": "1) Quoting a string using %q:" }, { "code": null, "e": 434, "s": 426, "text": "Syntax:" }, { "code": null, "e": 459, "s": 434, "text": "fmt.Printf(\"%q\", output)" }, { "code": "package main import \"fmt\" func main() { var result = \"Welcome to GeeksforGeeks.\" fmt.Printf(\"%q\", result)}", "e": 574, "s": 459, "text": null }, { "code": null, "e": 582, "s": 574, "text": "Output:" }, { "code": null, "e": 610, "s": 582, "text": "\"Welcome to GeeksforGeeks.\"" }, { "code": null, "e": 700, "s": 610, "text": "Explanation: In the above example, we used “%q” to display our string with double-quotes." }, { "code": null, "e": 751, "s": 700, "text": "2) Quoting a string using an escape character “\\”:" }, { "code": null, "e": 759, "s": 751, "text": "Syntax:" }, { "code": null, "e": 785, "s": 759, "text": "fmt.Println(\"\\\"string\\\"\")" }, { "code": "package main import \"fmt\" func main() { fmt.Println(\"\\\"GeeksforGeeks is a computer science portal\\\"\")}", "e": 893, "s": 785, "text": null }, { "code": null, "e": 901, "s": 893, "text": "Output:" }, { "code": null, "e": 946, "s": 901, "text": "\"GeeksforGeeks is a computer science portal\"" }, { "code": null, "e": 1122, "s": 946, "text": "Explanation: In the above example, we used an escape character “\\” to print a string with double-quotes. We can simply do so by adding a backslash(\\) before the double-quotes." }, { "code": null, "e": 1181, "s": 1122, "text": "3) Double quoting a string using a raw string lateral (`):" }, { "code": null, "e": 1189, "s": 1181, "text": "Syntax:" }, { "code": null, "e": 1214, "s": 1189, "text": "fmt.Println(`\"string\\\"`)" }, { "code": "package main import \"fmt\" func main() { fmt.Println(`\"GeeksforGeeks\"`)}", "e": 1291, "s": 1214, "text": null }, { "code": null, "e": 1299, "s": 1291, "text": "Output:" }, { "code": null, "e": 1315, "s": 1299, "text": "\"GeeksforGeeks\"" }, { "code": null, "e": 1421, "s": 1315, "text": "Explanation: In the above example, we used a raw string lateral (`) to print a string with double-quotes." }, { "code": null, "e": 1428, "s": 1421, "text": "Picked" }, { "code": null, "e": 1440, "s": 1428, "text": "Go Language" }, { "code": null, "e": 1538, "s": 1440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1585, "s": 1538, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 1598, "s": 1585, "text": "Arrays in Go" }, { "code": null, "e": 1610, "s": 1598, "text": "Golang Maps" }, { "code": null, "e": 1643, "s": 1610, "text": "How to Split a String in Golang?" }, { "code": null, "e": 1664, "s": 1643, "text": "Interfaces in Golang" }, { "code": null, "e": 1681, "s": 1664, "text": "Slices in Golang" }, { "code": null, "e": 1735, "s": 1681, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 1784, "s": 1735, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 1813, "s": 1784, "text": "How to Parse JSON in Golang?" } ]
Job Sequencing Problem – Loss Minimization
08 Jun, 2022 We are given N jobs numbered 1 to N. For each activity, let Ti denotes the number of days required to complete the job. For each day of delay before starting to work for job i, a loss of Li is incurred. We are required to find a sequence to complete the jobs so that overall loss is minimized. We can only work on one job at a time. If multiple such solutions are possible, then we are required to give the lexicographically least permutation (i.e earliest in dictionary order). Examples: Input : L = {3, 1, 2, 4} and T = {4, 1000, 2, 5} Output : 3, 4, 1, 2 Explanation: We should first complete job 3, then jobs 4, 1, 2 respectively. Input : L = {1, 2, 3, 5, 6} T = {2, 4, 1, 3, 2} Output : 3, 5, 4, 1, 2 Explanation: We should complete jobs 3, 5, 4, 1 and then 2 in this order. Let us consider two extreme cases and we shall deduce the general case solution from them. All jobs take same time to finish, i.e Ti = k for all i. Since all jobs take same time to finish we should first select jobs which have large Loss (Li). We should select jobs which have the highest losses and finish them as early as possible. Thus this is a greedy algorithm. Sort the jobs in descending order based on Li only.All jobs have the same penalty. Since all jobs have the same penalty we will do those jobs first which will take less amount of time to finish. This will minimize the total delay, and hence also the total loss incurred. This is also a greedy algorithm. Sort the jobs in ascending order based on Ti. Or we can also sort in descending order of 1/Ti. All jobs take same time to finish, i.e Ti = k for all i. Since all jobs take same time to finish we should first select jobs which have large Loss (Li). We should select jobs which have the highest losses and finish them as early as possible. Thus this is a greedy algorithm. Sort the jobs in descending order based on Li only. All jobs have the same penalty. Since all jobs have the same penalty we will do those jobs first which will take less amount of time to finish. This will minimize the total delay, and hence also the total loss incurred. This is also a greedy algorithm. Sort the jobs in ascending order based on Ti. Or we can also sort in descending order of 1/Ti. From the above cases, we can easily see that we should sort the jobs not on the basis of Li or Ti alone. Instead, we should sort the jobs according to the ratio Li/Ti, in descending order. We can get the lexicographically smallest permutation of jobs if we perform a stable sort on the jobs. An example of a stable sort is merge sort. To get most accurate result avoid dividing Li by Ti. Instead, compare the two ratios like fractions. To compare a/b and c/d, compare ad and bc. C++ Java // CPP program to minimize loss using stable sort.#include <iostream>#include <algorithm>#include <vector>using namespace std; #define all(c) c.begin(), c.end() // Each job is represented as a pair of int and pair.// This is done to provide implementation simplicity// so that we can use functions provided by algorithm// headertypedef pair<int, pair<int, int> > job; // compare function is given so that we can specify// how to compare a pair of jobsbool cmp_pair(job a, job b){ int a_Li, a_Ti, b_Li, b_Ti; a_Li = a.second.first; a_Ti = a.second.second; b_Li = b.second.first; b_Ti = b.second.second; // To compare a/b and c/d, compare ad and bc return (a_Li * b_Ti) > (b_Li * a_Ti);} void printOptimal(int L[], int T[], int N){ vector<job> list; // (Job Index, Si, Ti) for (int i = 0; i < N; i++) { int t = T[i]; int l = L[i]; // Each element is: (Job Index, (Li, Ti) ) list.push_back(make_pair(i + 1, make_pair(l, t))); } stable_sort(all(list), cmp_pair); // traverse the list and print job numbers cout << "Job numbers in optimal sequence are\n"; for (int i = 0; i < N; i++) cout << list[i].first << " "; } // Driver codeint main(){ int L[] = { 1, 2, 3, 5, 6 }; int T[] = { 2, 4, 1, 3, 2 }; int N = sizeof(L) / sizeof(L[0]); printOptimal(L, T, N); return 0;} //Java program to minimize loss using stable sort. import java.io.*;import java.util.*; class GFG { // compare function is given so that we can specify // how to compare a pair of jobs public static class cmp_pair implements Comparator<job> { @Override public int compare(job a, job b){ int a_Li, a_Ti, b_Li, b_Ti; a_Li = a.li; a_Ti = a.ti; b_Li = b.li; b_Ti = b.ti; // To compare a/b and c/d, compare ad and bc return (a_Li * b_Ti) > (b_Li * a_Ti)?-1:1; } } public static void printOptimal(int L[], int T[], int N) { List<job> list = new ArrayList<>(); // (Job Index, Si, Ti) for (int i = 0; i < N; i++) { int t = T[i]; int l = L[i]; // Each element is: (Job Index, (Li, Ti) ) list.add(new job(i + 1, l, t)); } Collections.sort(list,new cmp_pair()); // traverse the list and print job numbers System.out.println("Job numbers in optimal sequence are"); for (int i = 0; i < N; i++) System.out.print(list.get(i).index+" "); } public static void main (String[] args) { int L[] = { 1, 2, 3, 5, 6 }; int T[] = { 2, 4, 1, 3, 2 }; int N = L.length; printOptimal(L, T, N); }} // Each job is represented as a pair of int and pair.// This is done to provide implementation simplicity// so that we can use functions provided by algorithm// headerclass job{ int index,ti,li; job(int i,int l, int t){ this.index=i; this.ti=t; this.li=l; }} //This code is contributed by shruti456rawal Job numbers in optimal sequence are 3 5 4 1 2 Time Complexity: O(N log N)Space Complexity: O(N) This article is contributed by Sayan Mahapatra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shruti456rawal Greedy Sorting Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Policemen catch thieves K Centers Problem | Set 1 (Greedy Approximate Algorithm) Maximize difference between the Sum of the two halves of the Array after removal of N elements Minimize Cash Flow among a given set of friends who have borrowed money from each other Minimum time taken by each job to be completed given by a Directed Acyclic Graph Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 543, "s": 54, "text": "We are given N jobs numbered 1 to N. For each activity, let Ti denotes the number of days required to complete the job. For each day of delay before starting to work for job i, a loss of Li is incurred. We are required to find a sequence to complete the jobs so that overall loss is minimized. We can only work on one job at a time. If multiple such solutions are possible, then we are required to give the lexicographically least permutation (i.e earliest in dictionary order). Examples:" }, { "code": null, "e": 856, "s": 543, "text": "Input : L = {3, 1, 2, 4} and \n T = {4, 1000, 2, 5}\nOutput : 3, 4, 1, 2\nExplanation: We should first complete \njob 3, then jobs 4, 1, 2 respectively.\n\nInput : L = {1, 2, 3, 5, 6} \n T = {2, 4, 1, 3, 2}\nOutput : 3, 5, 4, 1, 2 \nExplanation: We should complete jobs \n3, 5, 4, 1 and then 2 in this order." }, { "code": null, "e": 947, "s": 856, "text": "Let us consider two extreme cases and we shall deduce the general case solution from them." }, { "code": null, "e": 1622, "s": 947, "text": "All jobs take same time to finish, i.e Ti = k for all i. Since all jobs take same time to finish we should first select jobs which have large Loss (Li). We should select jobs which have the highest losses and finish them as early as possible. Thus this is a greedy algorithm. Sort the jobs in descending order based on Li only.All jobs have the same penalty. Since all jobs have the same penalty we will do those jobs first which will take less amount of time to finish. This will minimize the total delay, and hence also the total loss incurred. This is also a greedy algorithm. Sort the jobs in ascending order based on Ti. Or we can also sort in descending order of 1/Ti." }, { "code": null, "e": 1950, "s": 1622, "text": "All jobs take same time to finish, i.e Ti = k for all i. Since all jobs take same time to finish we should first select jobs which have large Loss (Li). We should select jobs which have the highest losses and finish them as early as possible. Thus this is a greedy algorithm. Sort the jobs in descending order based on Li only." }, { "code": null, "e": 2298, "s": 1950, "text": "All jobs have the same penalty. Since all jobs have the same penalty we will do those jobs first which will take less amount of time to finish. This will minimize the total delay, and hence also the total loss incurred. This is also a greedy algorithm. Sort the jobs in ascending order based on Ti. Or we can also sort in descending order of 1/Ti." }, { "code": null, "e": 2487, "s": 2298, "text": "From the above cases, we can easily see that we should sort the jobs not on the basis of Li or Ti alone. Instead, we should sort the jobs according to the ratio Li/Ti, in descending order." }, { "code": null, "e": 2633, "s": 2487, "text": "We can get the lexicographically smallest permutation of jobs if we perform a stable sort on the jobs. An example of a stable sort is merge sort." }, { "code": null, "e": 2777, "s": 2633, "text": "To get most accurate result avoid dividing Li by Ti. Instead, compare the two ratios like fractions. To compare a/b and c/d, compare ad and bc." }, { "code": null, "e": 2781, "s": 2777, "text": "C++" }, { "code": null, "e": 2786, "s": 2781, "text": "Java" }, { "code": "// CPP program to minimize loss using stable sort.#include <iostream>#include <algorithm>#include <vector>using namespace std; #define all(c) c.begin(), c.end() // Each job is represented as a pair of int and pair.// This is done to provide implementation simplicity// so that we can use functions provided by algorithm// headertypedef pair<int, pair<int, int> > job; // compare function is given so that we can specify// how to compare a pair of jobsbool cmp_pair(job a, job b){ int a_Li, a_Ti, b_Li, b_Ti; a_Li = a.second.first; a_Ti = a.second.second; b_Li = b.second.first; b_Ti = b.second.second; // To compare a/b and c/d, compare ad and bc return (a_Li * b_Ti) > (b_Li * a_Ti);} void printOptimal(int L[], int T[], int N){ vector<job> list; // (Job Index, Si, Ti) for (int i = 0; i < N; i++) { int t = T[i]; int l = L[i]; // Each element is: (Job Index, (Li, Ti) ) list.push_back(make_pair(i + 1, make_pair(l, t))); } stable_sort(all(list), cmp_pair); // traverse the list and print job numbers cout << \"Job numbers in optimal sequence are\\n\"; for (int i = 0; i < N; i++) cout << list[i].first << \" \"; } // Driver codeint main(){ int L[] = { 1, 2, 3, 5, 6 }; int T[] = { 2, 4, 1, 3, 2 }; int N = sizeof(L) / sizeof(L[0]); printOptimal(L, T, N); return 0;}", "e": 4146, "s": 2786, "text": null }, { "code": "//Java program to minimize loss using stable sort. import java.io.*;import java.util.*; class GFG { // compare function is given so that we can specify // how to compare a pair of jobs public static class cmp_pair implements Comparator<job> { @Override public int compare(job a, job b){ int a_Li, a_Ti, b_Li, b_Ti; a_Li = a.li; a_Ti = a.ti; b_Li = b.li; b_Ti = b.ti; // To compare a/b and c/d, compare ad and bc return (a_Li * b_Ti) > (b_Li * a_Ti)?-1:1; } } public static void printOptimal(int L[], int T[], int N) { List<job> list = new ArrayList<>(); // (Job Index, Si, Ti) for (int i = 0; i < N; i++) { int t = T[i]; int l = L[i]; // Each element is: (Job Index, (Li, Ti) ) list.add(new job(i + 1, l, t)); } Collections.sort(list,new cmp_pair()); // traverse the list and print job numbers System.out.println(\"Job numbers in optimal sequence are\"); for (int i = 0; i < N; i++) System.out.print(list.get(i).index+\" \"); } public static void main (String[] args) { int L[] = { 1, 2, 3, 5, 6 }; int T[] = { 2, 4, 1, 3, 2 }; int N = L.length; printOptimal(L, T, N); }} // Each job is represented as a pair of int and pair.// This is done to provide implementation simplicity// so that we can use functions provided by algorithm// headerclass job{ int index,ti,li; job(int i,int l, int t){ this.index=i; this.ti=t; this.li=l; }} //This code is contributed by shruti456rawal", "e": 5871, "s": 4146, "text": null }, { "code": null, "e": 5918, "s": 5871, "text": "Job numbers in optimal sequence are\n3 5 4 1 2 " }, { "code": null, "e": 5968, "s": 5918, "text": "Time Complexity: O(N log N)Space Complexity: O(N)" }, { "code": null, "e": 6271, "s": 5968, "text": "This article is contributed by Sayan Mahapatra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 6396, "s": 6271, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6411, "s": 6396, "text": "shruti456rawal" }, { "code": null, "e": 6418, "s": 6411, "text": "Greedy" }, { "code": null, "e": 6426, "s": 6418, "text": "Sorting" }, { "code": null, "e": 6433, "s": 6426, "text": "Greedy" }, { "code": null, "e": 6441, "s": 6433, "text": "Sorting" }, { "code": null, "e": 6539, "s": 6441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6563, "s": 6539, "text": "Policemen catch thieves" }, { "code": null, "e": 6620, "s": 6563, "text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)" }, { "code": null, "e": 6715, "s": 6620, "text": "Maximize difference between the Sum of the two halves of the Array after removal of N elements" }, { "code": null, "e": 6803, "s": 6715, "text": "Minimize Cash Flow among a given set of friends who have borrowed money from each other" }, { "code": null, "e": 6884, "s": 6803, "text": "Minimum time taken by each job to be completed given by a Directed Acyclic Graph" }, { "code": null, "e": 6895, "s": 6884, "text": "Merge Sort" }, { "code": null, "e": 6917, "s": 6895, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 6927, "s": 6917, "text": "QuickSort" }, { "code": null, "e": 6942, "s": 6927, "text": "Insertion Sort" } ]
HTML | download Attribute
29 Apr, 2022 The HTML download Attribute is used to download the element when the user clicks on the hyperlink. It is used only when the href attribute is set. The downloaded file name will be the value of the attribute. The value of the attribute will be the name of the downloaded file. If the value is removed then original filename used.Uses: It is used in <a> and<area> Element. Syntax: <Element download="filename"> Attribute Values: It contains single value filename which is optional. It specifies the new filename for the downloaded file. The below example illustrates the use of download attribute in anchor Element. Example: html <!DOCTYPE html><html> <head> <title>HTML a download Attribute</title> </head> <body> <p>Click on image to download</p> <p> <a href="https://media.geeksforgeeks.org/wp-content/uploads/20190221234751/geeksforgeeks-logo1.png" download > <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190221234751/geeksforgeeks-logo1.png" alt="gfg" width="500" height="200" /> </a> </p> </body></html> Output: Supported Browsers: The browsers supported by download Attribute are listed below: Google Chrome Internet Explorer Firefox Opera hritikbhatnagar2182 chhabradhanvi hellodnzk HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2022" }, { "code": null, "e": 434, "s": 54, "text": "The HTML download Attribute is used to download the element when the user clicks on the hyperlink. It is used only when the href attribute is set. The downloaded file name will be the value of the attribute. The value of the attribute will be the name of the downloaded file. If the value is removed then original filename used.Uses: It is used in <a> and<area> Element. Syntax: " }, { "code": null, "e": 464, "s": 434, "text": "<Element download=\"filename\">" }, { "code": null, "e": 590, "s": 464, "text": "Attribute Values: It contains single value filename which is optional. It specifies the new filename for the downloaded file." }, { "code": null, "e": 678, "s": 590, "text": "The below example illustrates the use of download attribute in anchor Element. Example:" }, { "code": null, "e": 683, "s": 678, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML a download Attribute</title> </head> <body> <p>Click on image to download</p> <p> <a href=\"https://media.geeksforgeeks.org/wp-content/uploads/20190221234751/geeksforgeeks-logo1.png\" download > <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190221234751/geeksforgeeks-logo1.png\" alt=\"gfg\" width=\"500\" height=\"200\" /> </a> </p> </body></html>", "e": 1175, "s": 683, "text": null }, { "code": null, "e": 1184, "s": 1175, "text": "Output: " }, { "code": null, "e": 1268, "s": 1184, "text": "Supported Browsers: The browsers supported by download Attribute are listed below: " }, { "code": null, "e": 1282, "s": 1268, "text": "Google Chrome" }, { "code": null, "e": 1300, "s": 1282, "text": "Internet Explorer" }, { "code": null, "e": 1308, "s": 1300, "text": "Firefox" }, { "code": null, "e": 1314, "s": 1308, "text": "Opera" }, { "code": null, "e": 1336, "s": 1316, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1350, "s": 1336, "text": "chhabradhanvi" }, { "code": null, "e": 1360, "s": 1350, "text": "hellodnzk" }, { "code": null, "e": 1376, "s": 1360, "text": "HTML-Attributes" }, { "code": null, "e": 1381, "s": 1376, "text": "HTML" }, { "code": null, "e": 1398, "s": 1381, "text": "Web Technologies" }, { "code": null, "e": 1403, "s": 1398, "text": "HTML" } ]
Android - Camera
These are the following two ways, in which you can use camera in your application Using existing android camera application in our application Using existing android camera application in our application Directly using Camera API provided by android in our application Directly using Camera API provided by android in our application You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); Apart from the above, there are other available Intents provided by MediaStore. They are listed as follows ACTION_IMAGE_CAPTURE_SECURE It returns the image captured from the camera , when the device is secured ACTION_VIDEO_CAPTURE It calls the existing video application in android to capture video EXTRA_SCREEN_ORIENTATION It is used to set the orientation of the screen to vertical or landscape EXTRA_FULL_SCREEN It is used to control the user interface of the ViewImage INTENT_ACTION_VIDEO_CAMERA This intent is used to launch the camera in the video mode EXTRA_SIZE_LIMIT It is used to specify the size limit of video or image capture size Now you will use the function startActivityForResult() to launch this activity and wait for its result. Its syntax is given below startActivityForResult(intent,0) This method has been defined in the activity class. We are calling it from main activity. There are methods defined in the activity class that does the same job , but used when you are not calling from the activity but from somewhere else. They are listed below startActivityForResult(Intent intent, int requestCode, Bundle options) It starts an activity , but can take extra bundle of options with it startActivityFromChild(Activity child, Intent intent, int requestCode) It launch the activity when your activity is child of any other activity startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options) It work same as above , but it can take extra values in the shape of bundle with it startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) It launches activity from the fragment you are currently inside startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options) It not only launches the activity from the fragment , but can take extra values with it No matter which function you used to launch the activity , they all return the result. The result can be obtained by overriding the function onActivityResult. Here is an example that shows how to launch the existing camera application to capture an image and display the result in the form of bitmap. 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 main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; public class MainActivity extends AppCompatActivity { public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100; public static final String ALLOW_KEY = "ALLOWED"; public static final String CAMERA_PREF = "camera_pref"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (getFromPref(this, ALLOW_KEY)) { showSettingsAlert(); } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { showAlert(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } } } else { openCamera(); } } public static void saveToPreferences(Context context, String key, Boolean allowed) { SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = myPrefs.edit(); prefsEditor.putBoolean(key, allowed); prefsEditor.commit(); } public static Boolean getFromPref(Context context, String key) { SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, Context.MODE_PRIVATE); return (myPrefs.getBoolean(key, false)); } private void showAlert() { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage("App needs to access the Camera."); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } }); alertDialog.show(); } private void showSettingsAlert() { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage("App needs to access the Camera."); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT ALLOW", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); //finish(); } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); startInstalledAppDetailsActivity(MainActivity.this); } }); alertDialog.show(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_CAMERA: { for (int i = 0, len = permissions.length; i < len; i++) { String permission = permissions[i]; if (grantResults[i] == PackageManager.PERMISSION_DENIED) { boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale( this, permission); if (showRationale) { showAlert(); } else if (!showRationale) { // user denied flagging NEVER ASK AGAIN // you can either enable some fall back, // disable features of your app // or open another dialog explaining // again the permission and directing to // the app setting saveToPreferences(MainActivity.this, ALLOW_KEY, true); } } } } // other 'case' lines to check for other // permissions this app might request } } @Override protected void onResume() { super.onResume(); } public static void startInstalledAppDetailsActivity(final Activity context) { if (context == null) { return; } final Intent i = new Intent(); i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); i.addCategory(Intent.CATEGORY_DEFAULT); i.setData(Uri.parse("package:" + context.getPackageName())); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(i); } private void openCamera() { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivity(intent); } } Following will be the content of res/layout/activity_main.xml file− <?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"> </RelativeLayout> Following will be the content of res/values/strings.xml to define one new constants <resources> <string name="app_name">My Application</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <uses-permission android:name="android.permission.CAMERA" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.sairamkrishna.myapplication.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> </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 open the camera and display following screen −
[ { "code": null, "e": 3823, "s": 3741, "text": "These are the following two ways, in which you can use camera in your application" }, { "code": null, "e": 3884, "s": 3823, "text": "Using existing android camera application in our application" }, { "code": null, "e": 3945, "s": 3884, "text": "Using existing android camera application in our application" }, { "code": null, "e": 4010, "s": 3945, "text": "Directly using Camera API provided by android in our application" }, { "code": null, "e": 4075, "s": 4010, "text": "Directly using Camera API provided by android in our application" }, { "code": null, "e": 4212, "s": 4075, "text": "You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below" }, { "code": null, "e": 4290, "s": 4212, "text": "Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);" }, { "code": null, "e": 4397, "s": 4290, "text": "Apart from the above, there are other available Intents provided by MediaStore. They are listed as follows" }, { "code": null, "e": 4425, "s": 4397, "text": "ACTION_IMAGE_CAPTURE_SECURE" }, { "code": null, "e": 4500, "s": 4425, "text": "It returns the image captured from the camera , when the device is secured" }, { "code": null, "e": 4521, "s": 4500, "text": "ACTION_VIDEO_CAPTURE" }, { "code": null, "e": 4589, "s": 4521, "text": "It calls the existing video application in android to capture video" }, { "code": null, "e": 4614, "s": 4589, "text": "EXTRA_SCREEN_ORIENTATION" }, { "code": null, "e": 4687, "s": 4614, "text": "It is used to set the orientation of the screen to vertical or landscape" }, { "code": null, "e": 4705, "s": 4687, "text": "EXTRA_FULL_SCREEN" }, { "code": null, "e": 4763, "s": 4705, "text": "It is used to control the user interface of the ViewImage" }, { "code": null, "e": 4790, "s": 4763, "text": "INTENT_ACTION_VIDEO_CAMERA" }, { "code": null, "e": 4849, "s": 4790, "text": "This intent is used to launch the camera in the video mode" }, { "code": null, "e": 4866, "s": 4849, "text": "EXTRA_SIZE_LIMIT" }, { "code": null, "e": 4934, "s": 4866, "text": "It is used to specify the size limit of video or image capture size" }, { "code": null, "e": 5064, "s": 4934, "text": "Now you will use the function startActivityForResult() to launch this activity and wait for its result. Its syntax is given below" }, { "code": null, "e": 5097, "s": 5064, "text": "startActivityForResult(intent,0)" }, { "code": null, "e": 5359, "s": 5097, "text": "This method has been defined in the activity class. We are calling it from main activity. There are methods defined in the activity class that does the same job , but used when you are not calling from the activity but from somewhere else. They are listed below" }, { "code": null, "e": 5430, "s": 5359, "text": "startActivityForResult(Intent intent, int requestCode, Bundle options)" }, { "code": null, "e": 5499, "s": 5430, "text": "It starts an activity , but can take extra bundle of options with it" }, { "code": null, "e": 5570, "s": 5499, "text": "startActivityFromChild(Activity child, Intent intent, int requestCode)" }, { "code": null, "e": 5643, "s": 5570, "text": "It launch the activity when your activity is child of any other activity" }, { "code": null, "e": 5730, "s": 5643, "text": "startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)" }, { "code": null, "e": 5814, "s": 5730, "text": "It work same as above , but it can take extra values in the shape of bundle with it" }, { "code": null, "e": 5891, "s": 5814, "text": "startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)" }, { "code": null, "e": 5955, "s": 5891, "text": "It launches activity from the fragment you are currently inside" }, { "code": null, "e": 6048, "s": 5955, "text": "startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options)" }, { "code": null, "e": 6136, "s": 6048, "text": "It not only launches the activity from the fragment , but can take extra values with it" }, { "code": null, "e": 6295, "s": 6136, "text": "No matter which function you used to launch the activity , they all return the result. The result can be obtained by overriding the function onActivityResult." }, { "code": null, "e": 6437, "s": 6295, "text": "Here is an example that shows how to launch the existing camera application to capture an image and display the result in the form of bitmap." }, { "code": null, "e": 6542, "s": 6437, "text": "To experiment with this example , you need to run this on an actual device on which camera is supported." }, { "code": null, "e": 6625, "s": 6542, "text": "Following is the content of the modified main activity file src/MainActivity.java." }, { "code": null, "e": 13054, "s": 6625, "text": "package com.example.sairamkrishna.myapplication;\n\nimport android.Manifest;\nimport android.app.Activity;\nimport android.app.AlertDialog;\n\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.content.SharedPreferences;\nimport android.content.pm.PackageManager;\n\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.provider.Settings;\n\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.Toolbar;\n\npublic class MainActivity extends AppCompatActivity {\n public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;\n public static final String ALLOW_KEY = \"ALLOWED\";\n public static final String CAMERA_PREF = \"camera_pref\";\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {\n if (getFromPref(this, ALLOW_KEY)) {\n showSettingsAlert();\n } else if (ContextCompat.checkSelfPermission(this,\n Manifest.permission.CAMERA)\n \n != PackageManager.PERMISSION_GRANTED) {\n \n // Should we show an explanation?\n if (ActivityCompat.shouldShowRequestPermissionRationale(this,\n Manifest.permission.CAMERA)) {\n showAlert();\n } else {\n // No explanation needed, we can request the permission.\n ActivityCompat.requestPermissions(this,\n new String[]{Manifest.permission.CAMERA},\n MY_PERMISSIONS_REQUEST_CAMERA);\n }\n }\n } else {\n openCamera();\n }\n \n }\n public static void saveToPreferences(Context context, String key, Boolean allowed) {\n SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, \n Context.MODE_PRIVATE);\n SharedPreferences.Editor prefsEditor = myPrefs.edit();\n prefsEditor.putBoolean(key, allowed);\n prefsEditor.commit();\n }\n\t\t\n public static Boolean getFromPref(Context context, String key) {\n SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, \n Context.MODE_PRIVATE);\n return (myPrefs.getBoolean(key, false));\n }\n\t\t\n private void showAlert() {\n AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();\n alertDialog.setTitle(\"Alert\");\n alertDialog.setMessage(\"App needs to access the Camera.\");\n \n alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, \"DONT ALLOW\",\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n finish();\n }\n });\n\t\t\t\n alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, \"ALLOW\",\n new DialogInterface.OnClickListener() {\n \n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n ActivityCompat.requestPermissions(MainActivity.this,\n new String[]{Manifest.permission.CAMERA},\n MY_PERMISSIONS_REQUEST_CAMERA);\n }\n });\n alertDialog.show();\n }\n\t\t\n private void showSettingsAlert() {\n AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();\n alertDialog.setTitle(\"Alert\");\n alertDialog.setMessage(\"App needs to access the Camera.\");\n \n alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, \"DONT ALLOW\",\n new DialogInterface.OnClickListener() {\n \n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n //finish();\n }\n });\n\t\t\t\n alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, \"SETTINGS\",\n new DialogInterface.OnClickListener() {\n \n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n startInstalledAppDetailsActivity(MainActivity.this);\n }\n });\n\t\t\t\n alertDialog.show();\n }\n\t\t\n @Override\n public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {\n switch (requestCode) {\n case MY_PERMISSIONS_REQUEST_CAMERA: {\n for (int i = 0, len = permissions.length; i < len; i++) {\n String permission = permissions[i];\n \n if (grantResults[i] == PackageManager.PERMISSION_DENIED) {\n boolean \n showRationale = \n ActivityCompat.shouldShowRequestPermissionRationale(\n this, permission);\n \n if (showRationale) {\n showAlert();\n } else if (!showRationale) {\n // user denied flagging NEVER ASK AGAIN\n // you can either enable some fall back,\n // disable features of your app\n // or open another dialog explaining\n // again the permission and directing to\n // the app setting\n saveToPreferences(MainActivity.this, ALLOW_KEY, true);\n }\n }\n }\n }\n \n // other 'case' lines to check for other\n // permissions this app might request\n }\n }\n\t\t\n @Override\n protected void onResume() {\n super.onResume();\n }\n\t\t\n public static void startInstalledAppDetailsActivity(final Activity context) {\n if (context == null) {\n return;\n }\n\t\t\t\n final Intent i = new Intent();\n i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n i.addCategory(Intent.CATEGORY_DEFAULT);\n i.setData(Uri.parse(\"package:\" + context.getPackageName()));\n i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);\n i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);\n context.startActivity(i);\n }\n\t\t\n private void openCamera() {\n Intent intent = new Intent(\"android.media.action.IMAGE_CAPTURE\");\n startActivity(intent);\n }\n}" }, { "code": null, "e": 13122, "s": 13054, "text": "Following will be the content of res/layout/activity_main.xml file−" }, { "code": null, "e": 13652, "s": 13122, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n 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</RelativeLayout>" }, { "code": null, "e": 13736, "s": 13652, "text": "Following will be the content of res/values/strings.xml to define one new constants" }, { "code": null, "e": 13812, "s": 13736, "text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>" }, { "code": null, "e": 13870, "s": 13812, "text": "Following is the default content of AndroidManifest.xml −" }, { "code": null, "e": 14673, "s": 13870, "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 <uses-permission android:name=\"android.permission.CAMERA\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication.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 </application>\n</manifest>" }, { "code": null, "e": 15054, "s": 14673, "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." } ]
Sorted merge in one array
21 Jun, 2021 Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order.Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two arrays by inserting the smaller elements to front of A, but the issue with this approach is that we have to shift every element to right after every insertion.So, instead from comparing which one is smaller element, we can compare which one is larger and then inserting that element to end of A.Below is the solution for above approach. C++ Java Python3 C# PHP Javascript // Merging b[] into a[]#include <bits/stdc++.h>using namespace std;#define NA -1 void sortedMerge(int a[], int b[], int n, int m) { int i = n - 1; int j = m - 1; int lastIndex = n + m - 1; /* Merge a and b, starting from last element in each */ while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { a[lastIndex] = a[i]; // Copy Element i--; } else { a[lastIndex] = b[j]; // Copy Element j--; } lastIndex--; // Move indices }} /* Helper function to print the array */void printArray(int *arr, int n) { cout << "Array A after merging B in sorted" " order : " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " ";} int main() { int a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA}; int n = 5; int size_a = 10; int b[] = {16, 17, 19, 20, 22}; int m = 5; sortedMerge(a, b, n, m); printArray(a, size_a); return 0;} // Java program to merge B// into A in sorted order.import java.io.*; class GFG{ static int NA =-1; static void sortedMerge(int a[], int b[], int n, int m) { int i = n - 1; int j = m - 1; int lastIndex = n + m - 1; // Merge a and b, starting // from last element in each while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { // Copy Element a[lastIndex] = a[i]; i--; } else { // Copy Element a[lastIndex] = b[j]; j--; } // Move indices lastIndex--; } } // Helper function to print the array static void printArray(int arr[], int n) { System.out.println ( "Array A after merging B in sorted order : " ) ; for (int i = 0; i < n; i++) System.out.print(arr[i] +" "); } // Driver code public static void main (String[] args) { int a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA}; int n = 5; int size_a = 10; int b[] = {16, 17, 19, 20, 22}; int m = 5; sortedMerge(a, b, n, m); printArray(a, size_a); }} // This code is contributed by vt_m. # Python3 program to merge B# into A in sorted order. NA = -1 # Merging b[] into a[]def sortedMerge(a, b, n, m): i = n - 1 j = m - 1 lastIndex = n + m - 1 # Merge a and b, starting from last # element in each while (j >= 0) : # End of a is greater than end # of b if (i >= 0 and a[i] > b[j]): # Copy Element a[lastIndex] = a[i] i -= 1 else: # Copy Element a[lastIndex] = b[j] j -= 1 # Move indices lastIndex-= 1 # Helper function to print# the arraydef printArray(arr, n): print("Array A after merging B in sorted order : ") for i in range(0, n): print(arr[i], end =" ") size_a = 10 a = [10, 12, 13, 14, 18, NA, NA, NA, NA, NA]n = 5 b = [16, 17, 19, 20, 22]m = 5 sortedMerge(a, b, n, m)printArray(a, size_a) # This code is contributed by# Smitha Dinesh Semwal // C# program to merge B into A in// sorted order.using System; class GFG { static int NA =-1; static void sortedMerge(int []a, int []b, int n, int m) { int i = n - 1; int j = m - 1; int lastIndex = n + m - 1; // Merge a and b, starting // from last element in each while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { // Copy Element a[lastIndex] = a[i]; i--; } else { // Copy Element a[lastIndex] = b[j]; j--; } // Move indices lastIndex--; } } // Helper function to print the array static void printArray(int []arr, int n) { Console.WriteLine ( "Array A after " + "merging B in sorted order : " ) ; for (int i = 0; i < n; i++) Console.Write(arr[i] +" "); } // Driver code public static void Main () { int []a = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA}; int n = 5; int size_a = 10; int []b = {16, 17, 19, 20, 22}; int m = 5; sortedMerge(a, b, n, m); printArray(a, size_a); }} // This code is contributed by vt_m. <?php// PHP program to merge B into A in// sorted order. // Merging b[] into a[]function sortedMerge($a, $b, $n, $m){ $i = $n - 1; $j = $m - 1; $lastIndex = $n + $m - 1; /* Merge a and b, starting from last element in each */ while ($j >= 0) { /* End of a is greater than end of b */ if ($i >= 0 && $a[$i] > $b[$j]) { $a[$lastIndex] = $a[$i]; // Copy Element $i--; } else { $a[$lastIndex] = $b[$j]; // Copy Element $j--; } $lastIndex--; // Move indices } return $a;} /* Helper function to print the array */function printArray($arr, $n){ echo "Array A after merging B in sorted"; echo " order : \n"; for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Driver Code$a = array(10, 12, 13, 14, 18, -1, -1, -1, -1, -1);$n = 5;$size_a = 10; $b = array(16, 17, 19, 20, 22);$m = 5;$c = sortedMerge($a, $b, $n, $m);printArray($c, $size_a); // This code is contributed by Rajput-Ji.?> <script>// Javascript program to merge B into A in// sorted order. // Merging b[] into a[]function sortedMerge(a, b, n, m) { let i = n - 1; let j = m - 1; let lastIndex = n + m - 1; /* Merge a and b, starting from last element in each */ while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { a[lastIndex] = a[i]; // Copy Element i--; } else { a[lastIndex] = b[j]; // Copy Element j--; } lastIndex--; // Move indices } return a;} /* Helper function to print the array */function printArray(arr, n) { document.write("Array A after merging B in sorted"); document.write(" order : <br>"); for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver Codelet a = [10, 12, 13, 14, 18, -1, -1, -1, -1, -1];let n = 5;let size_a = 10; let b = new Array(16, 17, 19, 20, 22);let m = 5;let c = sortedMerge(a, b, n, m);printArray(c, size_a); // This code is contributed by gfgking.</script> Array A after merging B in sorted order : 10 12 13 14 16 17 18 19 20 22 Time complexity is O(m+n). Rajput-Ji gfgking array-merge Merge Sort Arrays Arrays Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Next Greater Element Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Find subarray with given sum | Set 1 (Nonnegative Numbers) Move all negative numbers to beginning and positive to end with constant extra space Count pairs with given sum
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2021" }, { "code": null, "e": 187, "s": 54, "text": "Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order.Examples: " }, { "code": null, "e": 338, "s": 187, "text": "Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} \n b[] = {16, 17, 19, 20, 22};;\nOutput : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22}" }, { "code": null, "e": 706, "s": 340, "text": "One way is to merge the two arrays by inserting the smaller elements to front of A, but the issue with this approach is that we have to shift every element to right after every insertion.So, instead from comparing which one is smaller element, we can compare which one is larger and then inserting that element to end of A.Below is the solution for above approach. " }, { "code": null, "e": 710, "s": 706, "text": "C++" }, { "code": null, "e": 715, "s": 710, "text": "Java" }, { "code": null, "e": 723, "s": 715, "text": "Python3" }, { "code": null, "e": 726, "s": 723, "text": "C#" }, { "code": null, "e": 730, "s": 726, "text": "PHP" }, { "code": null, "e": 741, "s": 730, "text": "Javascript" }, { "code": "// Merging b[] into a[]#include <bits/stdc++.h>using namespace std;#define NA -1 void sortedMerge(int a[], int b[], int n, int m) { int i = n - 1; int j = m - 1; int lastIndex = n + m - 1; /* Merge a and b, starting from last element in each */ while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { a[lastIndex] = a[i]; // Copy Element i--; } else { a[lastIndex] = b[j]; // Copy Element j--; } lastIndex--; // Move indices }} /* Helper function to print the array */void printArray(int *arr, int n) { cout << \"Array A after merging B in sorted\" \" order : \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \";} int main() { int a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA}; int n = 5; int size_a = 10; int b[] = {16, 17, 19, 20, 22}; int m = 5; sortedMerge(a, b, n, m); printArray(a, size_a); return 0;}", "e": 1654, "s": 741, "text": null }, { "code": "// Java program to merge B// into A in sorted order.import java.io.*; class GFG{ static int NA =-1; static void sortedMerge(int a[], int b[], int n, int m) { int i = n - 1; int j = m - 1; int lastIndex = n + m - 1; // Merge a and b, starting // from last element in each while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { // Copy Element a[lastIndex] = a[i]; i--; } else { // Copy Element a[lastIndex] = b[j]; j--; } // Move indices lastIndex--; } } // Helper function to print the array static void printArray(int arr[], int n) { System.out.println ( \"Array A after merging B in sorted order : \" ) ; for (int i = 0; i < n; i++) System.out.print(arr[i] +\" \"); } // Driver code public static void main (String[] args) { int a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA}; int n = 5; int size_a = 10; int b[] = {16, 17, 19, 20, 22}; int m = 5; sortedMerge(a, b, n, m); printArray(a, size_a); }} // This code is contributed by vt_m.", "e": 3002, "s": 1654, "text": null }, { "code": "# Python3 program to merge B# into A in sorted order. NA = -1 # Merging b[] into a[]def sortedMerge(a, b, n, m): i = n - 1 j = m - 1 lastIndex = n + m - 1 # Merge a and b, starting from last # element in each while (j >= 0) : # End of a is greater than end # of b if (i >= 0 and a[i] > b[j]): # Copy Element a[lastIndex] = a[i] i -= 1 else: # Copy Element a[lastIndex] = b[j] j -= 1 # Move indices lastIndex-= 1 # Helper function to print# the arraydef printArray(arr, n): print(\"Array A after merging B in sorted order : \") for i in range(0, n): print(arr[i], end =\" \") size_a = 10 a = [10, 12, 13, 14, 18, NA, NA, NA, NA, NA]n = 5 b = [16, 17, 19, 20, 22]m = 5 sortedMerge(a, b, n, m)printArray(a, size_a) # This code is contributed by# Smitha Dinesh Semwal", "e": 3955, "s": 3002, "text": null }, { "code": "// C# program to merge B into A in// sorted order.using System; class GFG { static int NA =-1; static void sortedMerge(int []a, int []b, int n, int m) { int i = n - 1; int j = m - 1; int lastIndex = n + m - 1; // Merge a and b, starting // from last element in each while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { // Copy Element a[lastIndex] = a[i]; i--; } else { // Copy Element a[lastIndex] = b[j]; j--; } // Move indices lastIndex--; } } // Helper function to print the array static void printArray(int []arr, int n) { Console.WriteLine ( \"Array A after \" + \"merging B in sorted order : \" ) ; for (int i = 0; i < n; i++) Console.Write(arr[i] +\" \"); } // Driver code public static void Main () { int []a = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA}; int n = 5; int size_a = 10; int []b = {16, 17, 19, 20, 22}; int m = 5; sortedMerge(a, b, n, m); printArray(a, size_a); }} // This code is contributed by vt_m.", "e": 5472, "s": 3955, "text": null }, { "code": "<?php// PHP program to merge B into A in// sorted order. // Merging b[] into a[]function sortedMerge($a, $b, $n, $m){ $i = $n - 1; $j = $m - 1; $lastIndex = $n + $m - 1; /* Merge a and b, starting from last element in each */ while ($j >= 0) { /* End of a is greater than end of b */ if ($i >= 0 && $a[$i] > $b[$j]) { $a[$lastIndex] = $a[$i]; // Copy Element $i--; } else { $a[$lastIndex] = $b[$j]; // Copy Element $j--; } $lastIndex--; // Move indices } return $a;} /* Helper function to print the array */function printArray($arr, $n){ echo \"Array A after merging B in sorted\"; echo \" order : \\n\"; for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \";} // Driver Code$a = array(10, 12, 13, 14, 18, -1, -1, -1, -1, -1);$n = 5;$size_a = 10; $b = array(16, 17, 19, 20, 22);$m = 5;$c = sortedMerge($a, $b, $n, $m);printArray($c, $size_a); // This code is contributed by Rajput-Ji.?>", "e": 6522, "s": 5472, "text": null }, { "code": "<script>// Javascript program to merge B into A in// sorted order. // Merging b[] into a[]function sortedMerge(a, b, n, m) { let i = n - 1; let j = m - 1; let lastIndex = n + m - 1; /* Merge a and b, starting from last element in each */ while (j >= 0) { /* End of a is greater than end of b */ if (i >= 0 && a[i] > b[j]) { a[lastIndex] = a[i]; // Copy Element i--; } else { a[lastIndex] = b[j]; // Copy Element j--; } lastIndex--; // Move indices } return a;} /* Helper function to print the array */function printArray(arr, n) { document.write(\"Array A after merging B in sorted\"); document.write(\" order : <br>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver Codelet a = [10, 12, 13, 14, 18, -1, -1, -1, -1, -1];let n = 5;let size_a = 10; let b = new Array(16, 17, 19, 20, 22);let m = 5;let c = sortedMerge(a, b, n, m);printArray(c, size_a); // This code is contributed by gfgking.</script>", "e": 7572, "s": 6522, "text": null }, { "code": null, "e": 7645, "s": 7572, "text": "Array A after merging B in sorted order : \n10 12 13 14 16 17 18 19 20 22" }, { "code": null, "e": 7675, "s": 7647, "text": "Time complexity is O(m+n). " }, { "code": null, "e": 7685, "s": 7675, "text": "Rajput-Ji" }, { "code": null, "e": 7693, "s": 7685, "text": "gfgking" }, { "code": null, "e": 7705, "s": 7693, "text": "array-merge" }, { "code": null, "e": 7716, "s": 7705, "text": "Merge Sort" }, { "code": null, "e": 7723, "s": 7716, "text": "Arrays" }, { "code": null, "e": 7730, "s": 7723, "text": "Arrays" }, { "code": null, "e": 7741, "s": 7730, "text": "Merge Sort" }, { "code": null, "e": 7839, "s": 7741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7871, "s": 7839, "text": "Introduction to Data Structures" }, { "code": null, "e": 7896, "s": 7871, "text": "Window Sliding Technique" }, { "code": null, "e": 7943, "s": 7896, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8007, "s": 7943, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8028, "s": 8007, "text": "Next Greater Element" }, { "code": null, "e": 8059, "s": 8028, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8117, "s": 8059, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 8176, "s": 8117, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 8261, "s": 8176, "text": "Move all negative numbers to beginning and positive to end with constant extra space" } ]
Find the parent of a node in the given binary tree
13 Aug, 2021 Given a tree and a node, the task is to find the parent of the given node in the tree. Print -1 if the given node is the root node.Examples: Input: Node = 3 1 / \ 2 3 / \ 4 5 Output: 1 Input: Node = 1 1 / \ 2 3 / \ 4 5 / 6 Output: -1 Approach: Write a recursive function that takes the current node and its parent as the arguments (root node is passed with -1 as its parent). If the current node is equal to the required node then print its parent and return else call the function recursively for its children and the current node as the parent.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; /* A binary tree node has data, pointerto left child and a pointerto right child */struct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Recursive function to find the// parent of the given nodevoid findParent(struct Node* node, int val, int parent){ if (node == NULL) return; // If current node is the required node if (node->data == val) { // Print its parent cout << parent; } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node->left, val, node->data); findParent(node->right, val, node->data); }} // Driver codeint main(){ struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); int node = 3; findParent(root, node, -1); return 0;} // Java implementation of the approachclass GFG{ /* A binary tree node has data, pointerto left child and a pointerto right child */static class Node{ int data; Node left, right; Node(int data) { this.data = data; left = right = null; }}; // Recursive function to find the// parent of the given nodestatic void findParent(Node node, int val, int parent){ if (node == null) return; // If current node is the required node if (node.data == val) { // Print its parent System.out.print(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); }} // Driver codepublic static void main(String []args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); int node = 3; findParent(root, node, -1);}} // This code is contributed by 29AjayKumar # Python3 implementation of# the above approach ''' A binary tree node has data, pointerto left child and a pointerto right child '''class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function to find the# parent of the given nodedef findParent(node : Node, val : int, parent : int) -> None: if (node is None): return # If current node is # the required node if (node.data == val): # Print its parent print(parent) else: # Recursive calls # for the children # of the current node # Current node is now # the new parent findParent(node.left, val, node.data) findParent(node.right, val, node.data) # Driver codeif __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) node = 3 findParent(root, node, -1) # This code is contributed by sanjeev2552 // C# implementation of the approachusing System; class GFG{ /* A binary tree node has data, pointerto left child and a pointerto right child */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; // Recursive function to find the// parent of the given nodestatic void findParent(Node node, int val, int parent){ if (node == null) return; // If current node is the required node if (node.data == val) { // Print its parent Console.Write(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); }} // Driver codepublic static void Main(String []args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); int node = 3; findParent(root, node, -1);}} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach /* A binary tree node has data, pointerto left child and a pointerto right child */class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Recursive function to find the// parent of the given nodefunction findParent(node, val, parent){ if (node == null) return; // If current node is the required node if (node.data == val) { // Print its parent document.write(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); }} // Driver codevar root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);var node = 3; findParent(root, node, -1); </script> 1 Time Complexity: O(N).Auxiliary Space: O(N). 29AjayKumar Rajput-Ji sanjeev2552 importantly pankajsharmagfg Binary Tree Data Structures Recursion Tree Data Structures Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Introduction to Data Structures Introduction to Tree Data Structure What is Data Structure: Types, Classifications and Applications What is Hashing | A Complete Tutorial Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Aug, 2021" }, { "code": null, "e": 196, "s": 54, "text": "Given a tree and a node, the task is to find the parent of the given node in the tree. Print -1 if the given node is the root node.Examples: " }, { "code": null, "e": 357, "s": 196, "text": "Input: Node = 3\n 1\n / \\\n 2 3\n / \\\n4 5\nOutput: 1\n\nInput: Node = 1\n 1\n / \\\n 2 3\n / \\\n4 5\n /\n 6\nOutput: -1" }, { "code": null, "e": 722, "s": 357, "text": "Approach: Write a recursive function that takes the current node and its parent as the arguments (root node is passed with -1 as its parent). If the current node is equal to the required node then print its parent and return else call the function recursively for its children and the current node as the parent.Below is the implementation of the above approach: " }, { "code": null, "e": 726, "s": 722, "text": "C++" }, { "code": null, "e": 731, "s": 726, "text": "Java" }, { "code": null, "e": 739, "s": 731, "text": "Python3" }, { "code": null, "e": 742, "s": 739, "text": "C#" }, { "code": null, "e": 753, "s": 742, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; /* A binary tree node has data, pointerto left child and a pointerto right child */struct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Recursive function to find the// parent of the given nodevoid findParent(struct Node* node, int val, int parent){ if (node == NULL) return; // If current node is the required node if (node->data == val) { // Print its parent cout << parent; } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node->left, val, node->data); findParent(node->right, val, node->data); }} // Driver codeint main(){ struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); int node = 3; findParent(root, node, -1); return 0;}", "e": 1838, "s": 753, "text": null }, { "code": "// Java implementation of the approachclass GFG{ /* A binary tree node has data, pointerto left child and a pointerto right child */static class Node{ int data; Node left, right; Node(int data) { this.data = data; left = right = null; }}; // Recursive function to find the// parent of the given nodestatic void findParent(Node node, int val, int parent){ if (node == null) return; // If current node is the required node if (node.data == val) { // Print its parent System.out.print(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); }} // Driver codepublic static void main(String []args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); int node = 3; findParent(root, node, -1);}} // This code is contributed by 29AjayKumar", "e": 2951, "s": 1838, "text": null }, { "code": "# Python3 implementation of# the above approach ''' A binary tree node has data, pointerto left child and a pointerto right child '''class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Recursive function to find the# parent of the given nodedef findParent(node : Node, val : int, parent : int) -> None: if (node is None): return # If current node is # the required node if (node.data == val): # Print its parent print(parent) else: # Recursive calls # for the children # of the current node # Current node is now # the new parent findParent(node.left, val, node.data) findParent(node.right, val, node.data) # Driver codeif __name__ == \"__main__\": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) node = 3 findParent(root, node, -1) # This code is contributed by sanjeev2552", "e": 4043, "s": 2951, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ /* A binary tree node has data, pointerto left child and a pointerto right child */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; // Recursive function to find the// parent of the given nodestatic void findParent(Node node, int val, int parent){ if (node == null) return; // If current node is the required node if (node.data == val) { // Print its parent Console.Write(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); }} // Driver codepublic static void Main(String []args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); int node = 3; findParent(root, node, -1);}} // This code is contributed by Rajput-Ji", "e": 5190, "s": 4043, "text": null }, { "code": "<script> // JavaScript implementation of the approach /* A binary tree node has data, pointerto left child and a pointerto right child */class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }}; // Recursive function to find the// parent of the given nodefunction findParent(node, val, parent){ if (node == null) return; // If current node is the required node if (node.data == val) { // Print its parent document.write(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); }} // Driver codevar root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);var node = 3; findParent(root, node, -1); </script>", "e": 6155, "s": 5190, "text": null }, { "code": null, "e": 6157, "s": 6155, "text": "1" }, { "code": null, "e": 6205, "s": 6159, "text": "Time Complexity: O(N).Auxiliary Space: O(N). " }, { "code": null, "e": 6217, "s": 6205, "text": "29AjayKumar" }, { "code": null, "e": 6227, "s": 6217, "text": "Rajput-Ji" }, { "code": null, "e": 6239, "s": 6227, "text": "sanjeev2552" }, { "code": null, "e": 6251, "s": 6239, "text": "importantly" }, { "code": null, "e": 6267, "s": 6251, "text": "pankajsharmagfg" }, { "code": null, "e": 6279, "s": 6267, "text": "Binary Tree" }, { "code": null, "e": 6295, "s": 6279, "text": "Data Structures" }, { "code": null, "e": 6305, "s": 6295, "text": "Recursion" }, { "code": null, "e": 6310, "s": 6305, "text": "Tree" }, { "code": null, "e": 6326, "s": 6310, "text": "Data Structures" }, { "code": null, "e": 6336, "s": 6326, "text": "Recursion" }, { "code": null, "e": 6341, "s": 6336, "text": "Tree" }, { "code": null, "e": 6439, "s": 6341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6464, "s": 6439, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6496, "s": 6464, "text": "Introduction to Data Structures" }, { "code": null, "e": 6532, "s": 6496, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 6596, "s": 6532, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6634, "s": 6596, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6694, "s": 6634, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6779, "s": 6694, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 6789, "s": 6779, "text": "Recursion" }, { "code": null, "e": 6816, "s": 6789, "text": "Program for Tower of Hanoi" } ]
Tic Tac Toe GUI In Python using PyGame
10 May, 2020 This article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Let’s break the task in five parts: Importing the required libraries and setting up the required global variables.Designing the game display function, that will set a platform for other components to be displayed on the screen.Main algorithm of win and drawGetting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse.Running an infinite loop, and including the defined methods in it. Importing the required libraries and setting up the required global variables. Designing the game display function, that will set a platform for other components to be displayed on the screen. Main algorithm of win and draw Getting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse. Running an infinite loop, and including the defined methods in it. Note: The required PNG files can be downloaded below – modified_cover.png X_modified.png o_modified.png We are going to use the pygame, time, and the sys library of Python. time library is used to keep track of time and sleep() method that we are going to use inside our code. Have a look at the code below. # importing the required librariesimport pygame as pgimport sysimport timefrom pygame.locals import * # declaring the global variables # for storing the 'x' or 'o' # value as characterXO = 'x' # storing the winner's value at# any instant of codewinner = None # to check if the game is a drawdraw = None # to set width of the game windowwidth = 400 # to set height of the game windowheight = 400 # to set background color of the # game windowwhite = (255, 255, 255) # color of the straightlines on that # white game board, dividing board # into 9 partsline_color = (0, 0, 0) # setting up a 3 * 3 board in canvasboard = [[None]*3, [None]*3, [None]*3] This is the trickier part, that makes the utmost importance in game development. We can use the display.set_mode() method to set up our display window. This takes three arguments, first one being a tuple having (width, height) of the display that we want it to be, the other two arguments are depth and fps respectively.display.set_caption(), sets a caption on the name tag of our display. pg.image.load() is an useful method to load the background images to customize the display. This method takes the file name as an argument along with the extension. There is a small problem with image.load(), it loads the image as a Python object in its native size, which may not be optimized along with the display. So we use another method in pygame known as pg.transform.scale(). This method takes two arguments, one being the name of the image object and the other is a tuple having (width, height), that we want our image to scale to. Finally we head to the first function, game_initiating_window(). On the very first line there is a screen.blit() function. The screen is the Python function and blit is the method that enables pygame to display something over another thing. Here out image object has been displayed over the screen, which was set white initially. pg.display.update() is another important function in game development. It updates the display of our window when called. Pygame also enables us to draw geometric objects like line, circle, etc. In this project we have used pg.draw.line() method that takes five arguments, namely – (display, line color, starting point, ending point, width). This involves a little bit of coordinate geometry to draw the lines properly. This is not sufficient. At each update of the display we need to know the game status, Weather it is win or lose.draw_status() helps us in displaying another 100pc window at the bottom of the main window, that updates the status at each click of the user. # initializing the pygame windowpg.init() # setting fps manuallyfps = 30 # this is used to track timeCLOCK = pg.time.Clock() # this method is used to build the# infrastructure of the displayscreen = pg.display.set_mode((width, height + 100), 0, 32) # setting up a nametag for the # game windowpg.display.set_caption("My Tic Tac Toe") # loading the images as python objectinitiating_window = pg.image.load("modified_cover.png")x_img = pg.image.load("X_modified.png")y_img = pg.image.load("o_modified.png") # resizing imagesinitiating_window = pg.transform.scale(initiating_window, (width, height + 100))x_img = pg.transform.scale(x_img, (80, 80))o_img = pg.transform.scale(y_img, (80, 80)) def game_initiating_window(): # displaying over the screen screen.blit(initiating_window, (0, 0)) # updating the display pg.display.update() time.sleep(3) screen.fill(white) # drawing vertical lines pg.draw.line(screen, line_color, (width / 3, 0), (width / 3, height), 7) pg.draw.line(screen, line_color, (width / 3 * 2, 0), (width / 3 * 2, height), 7) # drawing horizontal lines pg.draw.line(screen, line_color, (0, height / 3), (width, height / 3), 7) pg.draw.line(screen, line_color, (0, height / 3 * 2), (width, height / 3 * 2), 7) draw_status() def draw_status(): # getting the global variable draw # into action global draw if winner is None: message = XO.upper() + "'s Turn" else: message = winner.upper() + " won !" if draw: message = "Game Draw !" # setting a font object font = pg.font.Font(None, 30) # setting the font properties like # color and width of the text text = font.render(message, 1, (255, 255, 255)) # copy the rendered message onto the board # creating a small block at the bottom of the main display screen.fill ((0, 0, 0), (0, 400, 500, 100)) text_rect = text.get_rect(center =(width / 2, 500-50)) screen.blit(text, text_rect) pg.display.update() The main algorithm has a straight forward approach. A user can win row-wise, column-wise, and diagonally. So by using a multidimensional array, we can set up the conditions easily. def check_win(): global board, winner, draw # checking for winning rows for row in range(0, 3): if((board[row][0] == board[row][1] == board[row][2]) and (board [row][0] is not None)): winner = board[row][0] pg.draw.line(screen, (250, 0, 0), (0, (row + 1)*height / 3 -height / 6), (width, (row + 1)*height / 3 - height / 6 ), 4) break # checking for winning columns for col in range(0, 3): if((board[0][col] == board[1][col] == board[2][col]) and (board[0][col] is not None)): winner = board[0][col] pg.draw.line (screen, (250, 0, 0), ((col + 1)* width / 3 - width / 6, 0), \ ((col + 1)* width / 3 - width / 6, height), 4) break # check for diagonal winners if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None): # game won diagonally left to right winner = board[0][0] pg.draw.line (screen, (250, 70, 70), (50, 50), (350, 350), 4) if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None): # game won diagonally right to left winner = board[0][2] pg.draw.line (screen, (250, 70, 70), (350, 50), (50, 350), 4) if(all([all(row) for row in board]) and winner is None ): draw = True draw_status() This part deals with a visualization of the board and a little bit of coordinate geometry. drawXO() takes two arguments row and col. First of all, we have to set up the correct geometrical position to put the image of X and image of O that we have stored as two python objects “x_img” and “y_img” respectively. Have a look at the code for a proper understanding. user_click() is a function we have designed to get the input from a user mouse click. Imagine, you have clicked on one of the nine parts (boxes divided by the lines we have drawn horizontally and vertically), this function will define the coordinate of the position where you have clicked.pg.mouse.get_pos() gets the x-coordinate and y-coordinate of the mouse click of the user and return a tuple. Depending upon the (x, y) we can define the exact row and the exact column where the user has clicked. Finally, when we have the row and col, we pass these two as arguments to the function drawXO(row, col) to draw the image of ‘X’ or the image of ‘O’ at the desired position of the user on the game screen. def drawXO(row, col): global board, XO # for the first row, the image # should be pasted at a x coordinate # of 30 from the left margin if row == 1: posx = 30 # for the second row, the image # should be pasted at a x coordinate # of 30 from the game line if row == 2: # margin or width / 3 + 30 from # the left margin of the window posx = width / 3 + 30 if row == 3: posx = width / 3 * 2 + 30 if col == 1: posy = 30 if col == 2: posy = height / 3 + 30 if col == 3: posy = height / 3 * 2 + 30 # setting up the required board # value to display board[row-1][col-1] = XO if(XO == 'x'): # pasting x_img over the screen # at a coordinate position of # (pos_y, posx) defined in the # above code screen.blit(x_img, (posy, posx)) XO = 'o' else: screen.blit(o_img, (posy, posx)) XO = 'x' pg.display.update() def user_click(): # get coordinates of mouse click x, y = pg.mouse.get_pos() # get column of mouse click (1-3) if(x<width / 3): col = 1 elif (x<width / 3 * 2): col = 2 elif(x<width): col = 3 else: col = None # get row of mouse click (1-3) if(y<height / 3): row = 1 elif (y<height / 3 * 2): row = 2 elif(y<height): row = 3 else: row = None # after getting the row and col, # we need to draw the images at # the desired positions if(row and col and board[row-1][col-1] is None): global XO drawXO(row, col) check_win() This is the final important step to run our game infinitely until the user clicks exit. Before running an infinite loop, we need to set up a function that can reset all the global values and parameters to initial values for a fresh start of the game.reset_game() is used for this purpose. It resets the board value to 3 * 3 None value again and initializes global parameters. In the game development, every action by the player is an event. Whether he clicks on the window or clicks on the exit/close icon. To get these events as an object, pygame has a built-in method used as pg.event.get(). If the event type is “QUIT”, we use the sys library of Python to exit the game. But if the mouse is pressed, the event.get() will return “MOUSEBUTTONDOWN” and our call to user_click() happens to know the exact coordinate of the board where the user has clicked. In the entire code we have used the .sleep() method to pause our game for sometimes and make that user friendly and smooth. def reset_game(): global board, winner, XO, draw time.sleep(3) XO = 'x' draw = False game_initiating_window() winner = None board = [[None]*3, [None]*3, [None]*3] game_initiating_window() while(True): for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type is MOUSEBUTTONDOWN: user_click() if(winner or draw): reset_game() pg.display.update() CLOCK.tick(fps) The complete code: # importing the required librariesimport pygame as pgimport sysimport timefrom pygame.locals import * # declaring the global variables # for storing the 'x' or 'o' # value as characterXO = 'x' # storing the winner's value at# any instant of codewinner = None # to check if the game is a drawdraw = None # to set width of the game windowwidth = 400 # to set height of the game windowheight = 400 # to set background color of the # game windowwhite = (255, 255, 255) # color of the straightlines on that # white game board, dividing board # into 9 partsline_color = (0, 0, 0) # setting up a 3 * 3 board in canvasboard = [[None]*3, [None]*3, [None]*3] # initializing the pygame windowpg.init() # setting fps manuallyfps = 30 # this is used to track timeCLOCK = pg.time.Clock() # this method is used to build the# infrastructure of the displayscreen = pg.display.set_mode((width, height + 100), 0, 32) # setting up a nametag for the # game windowpg.display.set_caption("My Tic Tac Toe") # loading the images as python objectinitiating_window = pg.image.load("modified_cover.png")x_img = pg.image.load("X_modified.png")y_img = pg.image.load("o_modified.png") # resizing imagesinitiating_window = pg.transform.scale(initiating_window, (width, height + 100))x_img = pg.transform.scale(x_img, (80, 80))o_img = pg.transform.scale(y_img, (80, 80)) def game_initiating_window(): # displaying over the screen screen.blit(initiating_window, (0, 0)) # updating the display pg.display.update() time.sleep(3) screen.fill(white) # drawing vertical lines pg.draw.line(screen, line_color, (width / 3, 0), (width / 3, height), 7) pg.draw.line(screen, line_color, (width / 3 * 2, 0), (width / 3 * 2, height), 7) # drawing horizontal lines pg.draw.line(screen, line_color, (0, height / 3), (width, height / 3), 7) pg.draw.line(screen, line_color, (0, height / 3 * 2), (width, height / 3 * 2), 7) draw_status() def draw_status(): # getting the global variable draw # into action global draw if winner is None: message = XO.upper() + "'s Turn" else: message = winner.upper() + " won !" if draw: message = "Game Draw !" # setting a font object font = pg.font.Font(None, 30) # setting the font properties like # color and width of the text text = font.render(message, 1, (255, 255, 255)) # copy the rendered message onto the board # creating a small block at the bottom of the main display screen.fill ((0, 0, 0), (0, 400, 500, 100)) text_rect = text.get_rect(center =(width / 2, 500-50)) screen.blit(text, text_rect) pg.display.update() def check_win(): global board, winner, draw # checking for winning rows for row in range(0, 3): if((board[row][0] == board[row][1] == board[row][2]) and (board [row][0] is not None)): winner = board[row][0] pg.draw.line(screen, (250, 0, 0), (0, (row + 1)*height / 3 -height / 6), (width, (row + 1)*height / 3 - height / 6 ), 4) break # checking for winning columns for col in range(0, 3): if((board[0][col] == board[1][col] == board[2][col]) and (board[0][col] is not None)): winner = board[0][col] pg.draw.line (screen, (250, 0, 0), ((col + 1)* width / 3 - width / 6, 0), \ ((col + 1)* width / 3 - width / 6, height), 4) break # check for diagonal winners if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None): # game won diagonally left to right winner = board[0][0] pg.draw.line (screen, (250, 70, 70), (50, 50), (350, 350), 4) if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None): # game won diagonally right to left winner = board[0][2] pg.draw.line (screen, (250, 70, 70), (350, 50), (50, 350), 4) if(all([all(row) for row in board]) and winner is None ): draw = True draw_status() def drawXO(row, col): global board, XO # for the first row, the image # should be pasted at a x coordinate # of 30 from the left margin if row == 1: posx = 30 # for the second row, the image # should be pasted at a x coordinate # of 30 from the game line if row == 2: # margin or width / 3 + 30 from # the left margin of the window posx = width / 3 + 30 if row == 3: posx = width / 3 * 2 + 30 if col == 1: posy = 30 if col == 2: posy = height / 3 + 30 if col == 3: posy = height / 3 * 2 + 30 # setting up the required board # value to display board[row-1][col-1] = XO if(XO == 'x'): # pasting x_img over the screen # at a coordinate position of # (pos_y, posx) defined in the # above code screen.blit(x_img, (posy, posx)) XO = 'o' else: screen.blit(o_img, (posy, posx)) XO = 'x' pg.display.update() def user_click(): # get coordinates of mouse click x, y = pg.mouse.get_pos() # get column of mouse click (1-3) if(x<width / 3): col = 1 elif (x<width / 3 * 2): col = 2 elif(x<width): col = 3 else: col = None # get row of mouse click (1-3) if(y<height / 3): row = 1 elif (y<height / 3 * 2): row = 2 elif(y<height): row = 3 else: row = None # after getting the row and col, # we need to draw the images at # the desired positions if(row and col and board[row-1][col-1] is None): global XO drawXO(row, col) check_win() def reset_game(): global board, winner, XO, draw time.sleep(3) XO = 'x' draw = False game_initiating_window() winner = None board = [[None]*3, [None]*3, [None]*3] game_initiating_window() while(True): for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type is MOUSEBUTTONDOWN: user_click() if(winner or draw): reset_game() pg.display.update() CLOCK.tick(fps) Output: Python-gui Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2020" }, { "code": null, "e": 361, "s": 52, "text": "This article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language." }, { "code": null, "e": 397, "s": 361, "text": "Let’s break the task in five parts:" }, { "code": null, "e": 798, "s": 397, "text": "Importing the required libraries and setting up the required global variables.Designing the game display function, that will set a platform for other components to be displayed on the screen.Main algorithm of win and drawGetting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse.Running an infinite loop, and including the defined methods in it." }, { "code": null, "e": 877, "s": 798, "text": "Importing the required libraries and setting up the required global variables." }, { "code": null, "e": 991, "s": 877, "text": "Designing the game display function, that will set a platform for other components to be displayed on the screen." }, { "code": null, "e": 1022, "s": 991, "text": "Main algorithm of win and draw" }, { "code": null, "e": 1136, "s": 1022, "text": "Getting the user input and displaying the “X” or “O” at the proper position where the user has clicked his mouse." }, { "code": null, "e": 1203, "s": 1136, "text": "Running an infinite loop, and including the defined methods in it." }, { "code": null, "e": 1258, "s": 1203, "text": "Note: The required PNG files can be downloaded below –" }, { "code": null, "e": 1277, "s": 1258, "text": "modified_cover.png" }, { "code": null, "e": 1292, "s": 1277, "text": "X_modified.png" }, { "code": null, "e": 1307, "s": 1292, "text": "o_modified.png" }, { "code": null, "e": 1511, "s": 1307, "text": "We are going to use the pygame, time, and the sys library of Python. time library is used to keep track of time and sleep() method that we are going to use inside our code. Have a look at the code below." }, { "code": "# importing the required librariesimport pygame as pgimport sysimport timefrom pygame.locals import * # declaring the global variables # for storing the 'x' or 'o' # value as characterXO = 'x' # storing the winner's value at# any instant of codewinner = None # to check if the game is a drawdraw = None # to set width of the game windowwidth = 400 # to set height of the game windowheight = 400 # to set background color of the # game windowwhite = (255, 255, 255) # color of the straightlines on that # white game board, dividing board # into 9 partsline_color = (0, 0, 0) # setting up a 3 * 3 board in canvasboard = [[None]*3, [None]*3, [None]*3]", "e": 2171, "s": 1511, "text": null }, { "code": null, "e": 3102, "s": 2171, "text": "This is the trickier part, that makes the utmost importance in game development. We can use the display.set_mode() method to set up our display window. This takes three arguments, first one being a tuple having (width, height) of the display that we want it to be, the other two arguments are depth and fps respectively.display.set_caption(), sets a caption on the name tag of our display. pg.image.load() is an useful method to load the background images to customize the display. This method takes the file name as an argument along with the extension. There is a small problem with image.load(), it loads the image as a Python object in its native size, which may not be optimized along with the display. So we use another method in pygame known as pg.transform.scale(). This method takes two arguments, one being the name of the image object and the other is a tuple having (width, height), that we want our image to scale to." }, { "code": null, "e": 3851, "s": 3102, "text": "Finally we head to the first function, game_initiating_window(). On the very first line there is a screen.blit() function. The screen is the Python function and blit is the method that enables pygame to display something over another thing. Here out image object has been displayed over the screen, which was set white initially. pg.display.update() is another important function in game development. It updates the display of our window when called. Pygame also enables us to draw geometric objects like line, circle, etc. In this project we have used pg.draw.line() method that takes five arguments, namely – (display, line color, starting point, ending point, width). This involves a little bit of coordinate geometry to draw the lines properly." }, { "code": null, "e": 4107, "s": 3851, "text": "This is not sufficient. At each update of the display we need to know the game status, Weather it is win or lose.draw_status() helps us in displaying another 100pc window at the bottom of the main window, that updates the status at each click of the user." }, { "code": "# initializing the pygame windowpg.init() # setting fps manuallyfps = 30 # this is used to track timeCLOCK = pg.time.Clock() # this method is used to build the# infrastructure of the displayscreen = pg.display.set_mode((width, height + 100), 0, 32) # setting up a nametag for the # game windowpg.display.set_caption(\"My Tic Tac Toe\") # loading the images as python objectinitiating_window = pg.image.load(\"modified_cover.png\")x_img = pg.image.load(\"X_modified.png\")y_img = pg.image.load(\"o_modified.png\") # resizing imagesinitiating_window = pg.transform.scale(initiating_window, (width, height + 100))x_img = pg.transform.scale(x_img, (80, 80))o_img = pg.transform.scale(y_img, (80, 80)) def game_initiating_window(): # displaying over the screen screen.blit(initiating_window, (0, 0)) # updating the display pg.display.update() time.sleep(3) screen.fill(white) # drawing vertical lines pg.draw.line(screen, line_color, (width / 3, 0), (width / 3, height), 7) pg.draw.line(screen, line_color, (width / 3 * 2, 0), (width / 3 * 2, height), 7) # drawing horizontal lines pg.draw.line(screen, line_color, (0, height / 3), (width, height / 3), 7) pg.draw.line(screen, line_color, (0, height / 3 * 2), (width, height / 3 * 2), 7) draw_status() def draw_status(): # getting the global variable draw # into action global draw if winner is None: message = XO.upper() + \"'s Turn\" else: message = winner.upper() + \" won !\" if draw: message = \"Game Draw !\" # setting a font object font = pg.font.Font(None, 30) # setting the font properties like # color and width of the text text = font.render(message, 1, (255, 255, 255)) # copy the rendered message onto the board # creating a small block at the bottom of the main display screen.fill ((0, 0, 0), (0, 400, 500, 100)) text_rect = text.get_rect(center =(width / 2, 500-50)) screen.blit(text, text_rect) pg.display.update()", "e": 6156, "s": 4107, "text": null }, { "code": null, "e": 6337, "s": 6156, "text": "The main algorithm has a straight forward approach. A user can win row-wise, column-wise, and diagonally. So by using a multidimensional array, we can set up the conditions easily." }, { "code": "def check_win(): global board, winner, draw # checking for winning rows for row in range(0, 3): if((board[row][0] == board[row][1] == board[row][2]) and (board [row][0] is not None)): winner = board[row][0] pg.draw.line(screen, (250, 0, 0), (0, (row + 1)*height / 3 -height / 6), (width, (row + 1)*height / 3 - height / 6 ), 4) break # checking for winning columns for col in range(0, 3): if((board[0][col] == board[1][col] == board[2][col]) and (board[0][col] is not None)): winner = board[0][col] pg.draw.line (screen, (250, 0, 0), ((col + 1)* width / 3 - width / 6, 0), \\ ((col + 1)* width / 3 - width / 6, height), 4) break # check for diagonal winners if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None): # game won diagonally left to right winner = board[0][0] pg.draw.line (screen, (250, 70, 70), (50, 50), (350, 350), 4) if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None): # game won diagonally right to left winner = board[0][2] pg.draw.line (screen, (250, 70, 70), (350, 50), (50, 350), 4) if(all([all(row) for row in board]) and winner is None ): draw = True draw_status()", "e": 7772, "s": 6337, "text": null }, { "code": null, "e": 8135, "s": 7772, "text": "This part deals with a visualization of the board and a little bit of coordinate geometry. drawXO() takes two arguments row and col. First of all, we have to set up the correct geometrical position to put the image of X and image of O that we have stored as two python objects “x_img” and “y_img” respectively. Have a look at the code for a proper understanding." }, { "code": null, "e": 8840, "s": 8135, "text": "user_click() is a function we have designed to get the input from a user mouse click. Imagine, you have clicked on one of the nine parts (boxes divided by the lines we have drawn horizontally and vertically), this function will define the coordinate of the position where you have clicked.pg.mouse.get_pos() gets the x-coordinate and y-coordinate of the mouse click of the user and return a tuple. Depending upon the (x, y) we can define the exact row and the exact column where the user has clicked. Finally, when we have the row and col, we pass these two as arguments to the function drawXO(row, col) to draw the image of ‘X’ or the image of ‘O’ at the desired position of the user on the game screen." }, { "code": "def drawXO(row, col): global board, XO # for the first row, the image # should be pasted at a x coordinate # of 30 from the left margin if row == 1: posx = 30 # for the second row, the image # should be pasted at a x coordinate # of 30 from the game line if row == 2: # margin or width / 3 + 30 from # the left margin of the window posx = width / 3 + 30 if row == 3: posx = width / 3 * 2 + 30 if col == 1: posy = 30 if col == 2: posy = height / 3 + 30 if col == 3: posy = height / 3 * 2 + 30 # setting up the required board # value to display board[row-1][col-1] = XO if(XO == 'x'): # pasting x_img over the screen # at a coordinate position of # (pos_y, posx) defined in the # above code screen.blit(x_img, (posy, posx)) XO = 'o' else: screen.blit(o_img, (posy, posx)) XO = 'x' pg.display.update() def user_click(): # get coordinates of mouse click x, y = pg.mouse.get_pos() # get column of mouse click (1-3) if(x<width / 3): col = 1 elif (x<width / 3 * 2): col = 2 elif(x<width): col = 3 else: col = None # get row of mouse click (1-3) if(y<height / 3): row = 1 elif (y<height / 3 * 2): row = 2 elif(y<height): row = 3 else: row = None # after getting the row and col, # we need to draw the images at # the desired positions if(row and col and board[row-1][col-1] is None): global XO drawXO(row, col) check_win()", "e": 10593, "s": 8840, "text": null }, { "code": null, "e": 10969, "s": 10593, "text": "This is the final important step to run our game infinitely until the user clicks exit. Before running an infinite loop, we need to set up a function that can reset all the global values and parameters to initial values for a fresh start of the game.reset_game() is used for this purpose. It resets the board value to 3 * 3 None value again and initializes global parameters." }, { "code": null, "e": 11449, "s": 10969, "text": "In the game development, every action by the player is an event. Whether he clicks on the window or clicks on the exit/close icon. To get these events as an object, pygame has a built-in method used as pg.event.get(). If the event type is “QUIT”, we use the sys library of Python to exit the game. But if the mouse is pressed, the event.get() will return “MOUSEBUTTONDOWN” and our call to user_click() happens to know the exact coordinate of the board where the user has clicked." }, { "code": null, "e": 11573, "s": 11449, "text": "In the entire code we have used the .sleep() method to pause our game for sometimes and make that user friendly and smooth." }, { "code": "def reset_game(): global board, winner, XO, draw time.sleep(3) XO = 'x' draw = False game_initiating_window() winner = None board = [[None]*3, [None]*3, [None]*3] game_initiating_window() while(True): for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type is MOUSEBUTTONDOWN: user_click() if(winner or draw): reset_game() pg.display.update() CLOCK.tick(fps)", "e": 12080, "s": 11573, "text": null }, { "code": null, "e": 12099, "s": 12080, "text": "The complete code:" }, { "code": "# importing the required librariesimport pygame as pgimport sysimport timefrom pygame.locals import * # declaring the global variables # for storing the 'x' or 'o' # value as characterXO = 'x' # storing the winner's value at# any instant of codewinner = None # to check if the game is a drawdraw = None # to set width of the game windowwidth = 400 # to set height of the game windowheight = 400 # to set background color of the # game windowwhite = (255, 255, 255) # color of the straightlines on that # white game board, dividing board # into 9 partsline_color = (0, 0, 0) # setting up a 3 * 3 board in canvasboard = [[None]*3, [None]*3, [None]*3] # initializing the pygame windowpg.init() # setting fps manuallyfps = 30 # this is used to track timeCLOCK = pg.time.Clock() # this method is used to build the# infrastructure of the displayscreen = pg.display.set_mode((width, height + 100), 0, 32) # setting up a nametag for the # game windowpg.display.set_caption(\"My Tic Tac Toe\") # loading the images as python objectinitiating_window = pg.image.load(\"modified_cover.png\")x_img = pg.image.load(\"X_modified.png\")y_img = pg.image.load(\"o_modified.png\") # resizing imagesinitiating_window = pg.transform.scale(initiating_window, (width, height + 100))x_img = pg.transform.scale(x_img, (80, 80))o_img = pg.transform.scale(y_img, (80, 80)) def game_initiating_window(): # displaying over the screen screen.blit(initiating_window, (0, 0)) # updating the display pg.display.update() time.sleep(3) screen.fill(white) # drawing vertical lines pg.draw.line(screen, line_color, (width / 3, 0), (width / 3, height), 7) pg.draw.line(screen, line_color, (width / 3 * 2, 0), (width / 3 * 2, height), 7) # drawing horizontal lines pg.draw.line(screen, line_color, (0, height / 3), (width, height / 3), 7) pg.draw.line(screen, line_color, (0, height / 3 * 2), (width, height / 3 * 2), 7) draw_status() def draw_status(): # getting the global variable draw # into action global draw if winner is None: message = XO.upper() + \"'s Turn\" else: message = winner.upper() + \" won !\" if draw: message = \"Game Draw !\" # setting a font object font = pg.font.Font(None, 30) # setting the font properties like # color and width of the text text = font.render(message, 1, (255, 255, 255)) # copy the rendered message onto the board # creating a small block at the bottom of the main display screen.fill ((0, 0, 0), (0, 400, 500, 100)) text_rect = text.get_rect(center =(width / 2, 500-50)) screen.blit(text, text_rect) pg.display.update() def check_win(): global board, winner, draw # checking for winning rows for row in range(0, 3): if((board[row][0] == board[row][1] == board[row][2]) and (board [row][0] is not None)): winner = board[row][0] pg.draw.line(screen, (250, 0, 0), (0, (row + 1)*height / 3 -height / 6), (width, (row + 1)*height / 3 - height / 6 ), 4) break # checking for winning columns for col in range(0, 3): if((board[0][col] == board[1][col] == board[2][col]) and (board[0][col] is not None)): winner = board[0][col] pg.draw.line (screen, (250, 0, 0), ((col + 1)* width / 3 - width / 6, 0), \\ ((col + 1)* width / 3 - width / 6, height), 4) break # check for diagonal winners if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None): # game won diagonally left to right winner = board[0][0] pg.draw.line (screen, (250, 70, 70), (50, 50), (350, 350), 4) if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None): # game won diagonally right to left winner = board[0][2] pg.draw.line (screen, (250, 70, 70), (350, 50), (50, 350), 4) if(all([all(row) for row in board]) and winner is None ): draw = True draw_status() def drawXO(row, col): global board, XO # for the first row, the image # should be pasted at a x coordinate # of 30 from the left margin if row == 1: posx = 30 # for the second row, the image # should be pasted at a x coordinate # of 30 from the game line if row == 2: # margin or width / 3 + 30 from # the left margin of the window posx = width / 3 + 30 if row == 3: posx = width / 3 * 2 + 30 if col == 1: posy = 30 if col == 2: posy = height / 3 + 30 if col == 3: posy = height / 3 * 2 + 30 # setting up the required board # value to display board[row-1][col-1] = XO if(XO == 'x'): # pasting x_img over the screen # at a coordinate position of # (pos_y, posx) defined in the # above code screen.blit(x_img, (posy, posx)) XO = 'o' else: screen.blit(o_img, (posy, posx)) XO = 'x' pg.display.update() def user_click(): # get coordinates of mouse click x, y = pg.mouse.get_pos() # get column of mouse click (1-3) if(x<width / 3): col = 1 elif (x<width / 3 * 2): col = 2 elif(x<width): col = 3 else: col = None # get row of mouse click (1-3) if(y<height / 3): row = 1 elif (y<height / 3 * 2): row = 2 elif(y<height): row = 3 else: row = None # after getting the row and col, # we need to draw the images at # the desired positions if(row and col and board[row-1][col-1] is None): global XO drawXO(row, col) check_win() def reset_game(): global board, winner, XO, draw time.sleep(3) XO = 'x' draw = False game_initiating_window() winner = None board = [[None]*3, [None]*3, [None]*3] game_initiating_window() while(True): for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type is MOUSEBUTTONDOWN: user_click() if(winner or draw): reset_game() pg.display.update() CLOCK.tick(fps)", "e": 18513, "s": 12099, "text": null }, { "code": null, "e": 18521, "s": 18513, "text": "Output:" }, { "code": null, "e": 18532, "s": 18521, "text": "Python-gui" }, { "code": null, "e": 18546, "s": 18532, "text": "Python-PyGame" }, { "code": null, "e": 18553, "s": 18546, "text": "Python" }, { "code": null, "e": 18651, "s": 18553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18693, "s": 18651, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 18715, "s": 18693, "text": "Enumerate() in Python" }, { "code": null, "e": 18741, "s": 18715, "text": "Python String | replace()" }, { "code": null, "e": 18773, "s": 18741, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 18802, "s": 18773, "text": "*args and **kwargs in Python" }, { "code": null, "e": 18829, "s": 18802, "text": "Python Classes and Objects" }, { "code": null, "e": 18850, "s": 18829, "text": "Python OOPs Concepts" }, { "code": null, "e": 18886, "s": 18850, "text": "Convert integer to string in Python" }, { "code": null, "e": 18909, "s": 18886, "text": "Introduction To PYTHON" } ]
Restoring and Building with MSBuild
In this chapter, we will discuss how to restore and build your MSBuild (*.csproj) file using the command line utility. To see what commands are available in .NET Core 2.0 preview 1, let us run the following command. dotnet help You will see all the commands like new, restore, build, etc. Following is the default implementation in Program.cs file. using System; namespace MSBuild { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } Let us now execute the following command to see the progress. dotnet build You will see a lot of errors. These errors need to be rectified. Let us now run the following command. dotnet restore You can see that all the packages are restored. Some new folders and files have also been generated. To see the directory structure, let us run the following command. tree /f Following is the directory structure − Let us now rebuild the project running the following command again. dotnet build Now you project will build successfully without any error(s) and MSBuild.dll is also created. To see the output, let us run the following command − dotnet run You can see the following output on your console.
[ { "code": null, "e": 2736, "s": 2520, "text": "In this chapter, we will discuss how to restore and build your MSBuild (*.csproj) file using the command line utility. To see what commands are available in .NET Core 2.0 preview 1, let us run the following command." }, { "code": null, "e": 2750, "s": 2736, "text": "dotnet help \n" }, { "code": null, "e": 2811, "s": 2750, "text": "You will see all the commands like new, restore, build, etc." }, { "code": null, "e": 2871, "s": 2811, "text": "Following is the default implementation in Program.cs file." }, { "code": null, "e": 3032, "s": 2871, "text": "using System; \nnamespace MSBuild { \n class Program { \n static void Main(string[] args) { \n Console.WriteLine(\"Hello World!\"); \n } \n } \n} " }, { "code": null, "e": 3094, "s": 3032, "text": "Let us now execute the following command to see the progress." }, { "code": null, "e": 3108, "s": 3094, "text": "dotnet build\n" }, { "code": null, "e": 3173, "s": 3108, "text": "You will see a lot of errors. These errors need to be rectified." }, { "code": null, "e": 3211, "s": 3173, "text": "Let us now run the following command." }, { "code": null, "e": 3227, "s": 3211, "text": "dotnet restore\n" }, { "code": null, "e": 3328, "s": 3227, "text": "You can see that all the packages are restored. Some new folders and files have also been generated." }, { "code": null, "e": 3394, "s": 3328, "text": "To see the directory structure, let us run the following command." }, { "code": null, "e": 3404, "s": 3394, "text": "tree /f \n" }, { "code": null, "e": 3443, "s": 3404, "text": "Following is the directory structure −" }, { "code": null, "e": 3511, "s": 3443, "text": "Let us now rebuild the project running the following command again." }, { "code": null, "e": 3525, "s": 3511, "text": "dotnet build\n" }, { "code": null, "e": 3619, "s": 3525, "text": "Now you project will build successfully without any error(s) and MSBuild.dll is also created." }, { "code": null, "e": 3673, "s": 3619, "text": "To see the output, let us run the following command −" }, { "code": null, "e": 3686, "s": 3673, "text": "dotnet run \n" } ]
HTML | Viewport meta tag for Responsive Web Design
24 Dec, 2021 What is Viewport?A Browser’s viewport is the area of web page in which the content is visible to the user. The viewport does not have the same size, it varies with the variation in screen size of the devices on which the website is visible. For a laptop, the viewport has a larger size as compared to a smartphone or tablet. Example:The laptop screen is wider On smartphones the page is adjusted due to narrower screen Note: When a page is not made responsive for smaller viewports it looks bad or even breaks on smaller screen. To fix this problem introduce a responsive tag to control the viewport. This tag was firstly introduced by Apple Inc. for Safari iOS. Syntax: <meta name="viewport" content= "width=device-width, initial-scale=1.0"> This is the common setting of viewport used in various mobile-optimized websites. The width property governs the size of the viewport. It is possible to set it to a specific value (“width=600”) in terms of CSS pixels. Here it is set to a special value(“width= device-width”) which is the width of the device in terms of CSS pixels at a scale of 100%. The initial-scale property governs the zoom level when the page is loaded for the first time. Note: The meta tag should be added in the head tag in HTML document. A Responsive tags has the following attributes: width: Width of the virtual viewport of the device. height: Height of the virtual viewport of the device. initial-scale: Zoom level when the page is first visited. minimum-scale: Minimum zoom level to which a user can zoom the page. maximum-scale: Maximum zoom level to which a user can zoom the page. user-scalable: Flag which allows the device to zoom in or out.(value= yes/no). Example: <!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <meta charset="utf-8" name="viewport" content= "width=device-width, initial-scale=1.0"> <style> .gfg { font-size:40px; font-weight:bold; color:green; text-align:center; } .geeks { font-size:17px; text-align:center; } p { text-align:justify; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> <p>Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <p>An extensive Online Test Series for GATE 2019 to boost the preparation for GATE 2019 aspirants. Test series is designed considering the pattern of previous years GATE papers and ensures to resemble with the standard of GATE. This Test Series will help the aspirants track and improve the preparation through questions of various difficulty levels. There will be two Test Series covering the whole syllabus of GATE, including Mathematics and Aptitude. Test Series I will cover the basic and medium difficulty, whereas in Test Series II difficulty will be slightly higher. </p> </body></html> Output:Wide Display output:Narrow Display output: vshylaja CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Dec, 2021" }, { "code": null, "e": 377, "s": 52, "text": "What is Viewport?A Browser’s viewport is the area of web page in which the content is visible to the user. The viewport does not have the same size, it varies with the variation in screen size of the devices on which the website is visible. For a laptop, the viewport has a larger size as compared to a smartphone or tablet." }, { "code": null, "e": 412, "s": 377, "text": "Example:The laptop screen is wider" }, { "code": null, "e": 471, "s": 412, "text": "On smartphones the page is adjusted due to narrower screen" }, { "code": null, "e": 715, "s": 471, "text": "Note: When a page is not made responsive for smaller viewports it looks bad or even breaks on smaller screen. To fix this problem introduce a responsive tag to control the viewport. This tag was firstly introduced by Apple Inc. for Safari iOS." }, { "code": null, "e": 723, "s": 715, "text": "Syntax:" }, { "code": "<meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\">", "e": 795, "s": 723, "text": null }, { "code": null, "e": 1240, "s": 795, "text": "This is the common setting of viewport used in various mobile-optimized websites. The width property governs the size of the viewport. It is possible to set it to a specific value (“width=600”) in terms of CSS pixels. Here it is set to a special value(“width= device-width”) which is the width of the device in terms of CSS pixels at a scale of 100%. The initial-scale property governs the zoom level when the page is loaded for the first time." }, { "code": null, "e": 1309, "s": 1240, "text": "Note: The meta tag should be added in the head tag in HTML document." }, { "code": null, "e": 1357, "s": 1309, "text": "A Responsive tags has the following attributes:" }, { "code": null, "e": 1409, "s": 1357, "text": "width: Width of the virtual viewport of the device." }, { "code": null, "e": 1463, "s": 1409, "text": "height: Height of the virtual viewport of the device." }, { "code": null, "e": 1521, "s": 1463, "text": "initial-scale: Zoom level when the page is first visited." }, { "code": null, "e": 1590, "s": 1521, "text": "minimum-scale: Minimum zoom level to which a user can zoom the page." }, { "code": null, "e": 1659, "s": 1590, "text": "maximum-scale: Maximum zoom level to which a user can zoom the page." }, { "code": null, "e": 1738, "s": 1659, "text": "user-scalable: Flag which allows the device to zoom in or out.(value= yes/no)." }, { "code": null, "e": 1747, "s": 1738, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksforGeeks</title> <meta charset=\"utf-8\" name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <style> .gfg { font-size:40px; font-weight:bold; color:green; text-align:center; } .geeks { font-size:17px; text-align:center; } p { text-align:justify; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> <p>Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <p>An extensive Online Test Series for GATE 2019 to boost the preparation for GATE 2019 aspirants. Test series is designed considering the pattern of previous years GATE papers and ensures to resemble with the standard of GATE. This Test Series will help the aspirants track and improve the preparation through questions of various difficulty levels. There will be two Test Series covering the whole syllabus of GATE, including Mathematics and Aptitude. Test Series I will cover the basic and medium difficulty, whereas in Test Series II difficulty will be slightly higher. </p> </body></html> ", "e": 3451, "s": 1747, "text": null }, { "code": null, "e": 3501, "s": 3451, "text": "Output:Wide Display output:Narrow Display output:" }, { "code": null, "e": 3510, "s": 3501, "text": "vshylaja" }, { "code": null, "e": 3514, "s": 3510, "text": "CSS" }, { "code": null, "e": 3519, "s": 3514, "text": "HTML" }, { "code": null, "e": 3536, "s": 3519, "text": "Web Technologies" }, { "code": null, "e": 3541, "s": 3536, "text": "HTML" }, { "code": null, "e": 3639, "s": 3541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3687, "s": 3639, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3749, "s": 3687, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3799, "s": 3749, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3857, "s": 3799, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3907, "s": 3857, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3955, "s": 3907, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4017, "s": 3955, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4067, "s": 4017, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4091, "s": 4067, "text": "REST API (Introduction)" } ]
How to change the size of Form controls in Bootstrap ?
25 Nov, 2021 Bootstrap allows to change the size of form controls using .form-control classes. For default size .form-control is used, for smaller size we can use .form-control class along with .form-control-sm and for larger size we can use .form-control class along with .form-control-lg. For default size: class="form-control" For small size: class="form-control form-control-sm" For large size: class="form-control form-control-lg" Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script> <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> Add .form-control class for default size, .form-control-sm for small sized form control and .form-control-lg for large sized form control in the class of <input>tag <input class=”form-control form-control-lg” type=”text” placeholder=”.form-control-lg” aria-label=”.form-control-lg example”> <input class=”form-control” type=”text” placeholder=”Default input” aria-label=”default input example”> <input class=”form-control form-control-sm” type=”text” placeholder=”.form-control-sm” aria-label=”.form-control-sm example”> HTML <!DOCTYPE html><html> <head> <title>Bootstrap Form Control Size Example</title> <!--Include Latest Bootstrap, jQuery and CSS CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script> </head> <body style="padding:100px;"> <!-- Add class .form-control-lg after .form-control to display large size form control--> <input class="form-control form-control-lg" type="text" placeholder=".form-control-lg" aria-label=".form-control-lg example"> <br> <!-- Add class .form-control to display default size form control--> <input class="form-control" type="text" placeholder="Default input" aria-label="default input example"> <br> <!-- Add class .form-control-sm after .form-control to display small form control--> <input class="form-control form-control-sm" type="text" placeholder=".form-control-sm" aria-label=".form-control-sm example"> </body></html> surindertarika1234 rajeev0719singh Bootstrap-4 Bootstrap-Questions HTML-Tags Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2021" }, { "code": null, "e": 306, "s": 28, "text": "Bootstrap allows to change the size of form controls using .form-control classes. For default size .form-control is used, for smaller size we can use .form-control class along with .form-control-sm and for larger size we can use .form-control class along with .form-control-lg." }, { "code": null, "e": 325, "s": 306, "text": " For default size:" }, { "code": null, "e": 374, "s": 325, "text": "class=\"form-control\" " }, { "code": null, "e": 390, "s": 374, "text": "For small size:" }, { "code": null, "e": 427, "s": 390, "text": "class=\"form-control form-control-sm\"" }, { "code": null, "e": 443, "s": 427, "text": "For large size:" }, { "code": null, "e": 480, "s": 443, "text": "class=\"form-control form-control-lg\"" }, { "code": null, "e": 579, "s": 480, "text": "Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 961, "s": 579, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script> <script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script> <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script> " }, { "code": null, "e": 1126, "s": 961, "text": "Add .form-control class for default size, .form-control-sm for small sized form control and .form-control-lg for large sized form control in the class of <input>tag" }, { "code": null, "e": 1484, "s": 1126, "text": "<input class=”form-control form-control-lg” type=”text” placeholder=”.form-control-lg” aria-label=”.form-control-lg example”> <input class=”form-control” type=”text” placeholder=”Default input” aria-label=”default input example”> <input class=”form-control form-control-sm” type=”text” placeholder=”.form-control-sm” aria-label=”.form-control-sm example”> " }, { "code": null, "e": 1489, "s": 1484, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap Form Control Size Example</title> <!--Include Latest Bootstrap, jQuery and CSS CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script> </head> <body style=\"padding:100px;\"> <!-- Add class .form-control-lg after .form-control to display large size form control--> <input class=\"form-control form-control-lg\" type=\"text\" placeholder=\".form-control-lg\" aria-label=\".form-control-lg example\"> <br> <!-- Add class .form-control to display default size form control--> <input class=\"form-control\" type=\"text\" placeholder=\"Default input\" aria-label=\"default input example\"> <br> <!-- Add class .form-control-sm after .form-control to display small form control--> <input class=\"form-control form-control-sm\" type=\"text\" placeholder=\".form-control-sm\" aria-label=\".form-control-sm example\"> </body></html>", "e": 2873, "s": 1489, "text": null }, { "code": null, "e": 2892, "s": 2873, "text": "surindertarika1234" }, { "code": null, "e": 2908, "s": 2892, "text": "rajeev0719singh" }, { "code": null, "e": 2920, "s": 2908, "text": "Bootstrap-4" }, { "code": null, "e": 2940, "s": 2920, "text": "Bootstrap-Questions" }, { "code": null, "e": 2950, "s": 2940, "text": "HTML-Tags" }, { "code": null, "e": 2957, "s": 2950, "text": "Picked" }, { "code": null, "e": 2967, "s": 2957, "text": "Bootstrap" }, { "code": null, "e": 2972, "s": 2967, "text": "HTML" }, { "code": null, "e": 2989, "s": 2972, "text": "Web Technologies" }, { "code": null, "e": 2994, "s": 2989, "text": "HTML" } ]
Python program to create dynamically named variables from user input - GeeksforGeeks
19 May, 2021 Given a string input, the task is to write a Python program to create a variable from that input (as a variable name) and to assign it some value. Below are the methods to create dynamically named variables from user input: Method 1: Using globals() method. Python3 # Dynamic_Variable_Name can be# anything the user wantsDynamic_Variable_Name = "geek" # The value 2020 is assigned# to "geek" variableglobals()[Dynamic_Variable_Name] = 2020 # Display variableprint(geek) Output: 2020 Method 2: Using locals() method. Python3 # Dynamic_Variable_Name can be# anything the user wants.Dynamic_Variable_Name = "geek" # The value 2020 is assigned# to "geek" variablelocals()[Dynamic_Variable_Name] = 2020 # Display variableprint(geek) Output: 2020 Method 3: Using exec() method. Python3 # Dynamic_Variable_Name can be# anything the user wants.Dynamic_Variable_Name = "geek" # The value 2020 is assigned# to "geek" variableexec("%s = %d" % (Dynamic_Variable_Name, 2020)) # Display variableprint(geek) Output: 2020 Method 4: Using vars() method Python3 # Dynamic_Variable_Name can be# anything the user wants.Dynamic_Variable_Name = "geek" # The value 2020 is assigned# to "geek" variablevars()[Dynamic_Variable_Name] = 2020 # Display variableprint(geek) Output: 2020 arorakashish0911 python-basics Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 May, 2021" }, { "code": null, "e": 25762, "s": 25537, "text": "Given a string input, the task is to write a Python program to create a variable from that input (as a variable name) and to assign it some value. Below are the methods to create dynamically named variables from user input: " }, { "code": null, "e": 25796, "s": 25762, "text": "Method 1: Using globals() method." }, { "code": null, "e": 25804, "s": 25796, "text": "Python3" }, { "code": "# Dynamic_Variable_Name can be# anything the user wantsDynamic_Variable_Name = \"geek\" # The value 2020 is assigned# to \"geek\" variableglobals()[Dynamic_Variable_Name] = 2020 # Display variableprint(geek)", "e": 26008, "s": 25804, "text": null }, { "code": null, "e": 26016, "s": 26008, "text": "Output:" }, { "code": null, "e": 26021, "s": 26016, "text": "2020" }, { "code": null, "e": 26054, "s": 26021, "text": "Method 2: Using locals() method." }, { "code": null, "e": 26062, "s": 26054, "text": "Python3" }, { "code": "# Dynamic_Variable_Name can be# anything the user wants.Dynamic_Variable_Name = \"geek\" # The value 2020 is assigned# to \"geek\" variablelocals()[Dynamic_Variable_Name] = 2020 # Display variableprint(geek)", "e": 26266, "s": 26062, "text": null }, { "code": null, "e": 26274, "s": 26266, "text": "Output:" }, { "code": null, "e": 26279, "s": 26274, "text": "2020" }, { "code": null, "e": 26310, "s": 26279, "text": "Method 3: Using exec() method." }, { "code": null, "e": 26318, "s": 26310, "text": "Python3" }, { "code": "# Dynamic_Variable_Name can be# anything the user wants.Dynamic_Variable_Name = \"geek\" # The value 2020 is assigned# to \"geek\" variableexec(\"%s = %d\" % (Dynamic_Variable_Name, 2020)) # Display variableprint(geek)", "e": 26531, "s": 26318, "text": null }, { "code": null, "e": 26539, "s": 26531, "text": "Output:" }, { "code": null, "e": 26544, "s": 26539, "text": "2020" }, { "code": null, "e": 26574, "s": 26544, "text": "Method 4: Using vars() method" }, { "code": null, "e": 26582, "s": 26574, "text": "Python3" }, { "code": "# Dynamic_Variable_Name can be# anything the user wants.Dynamic_Variable_Name = \"geek\" # The value 2020 is assigned# to \"geek\" variablevars()[Dynamic_Variable_Name] = 2020 # Display variableprint(geek)", "e": 26784, "s": 26582, "text": null }, { "code": null, "e": 26792, "s": 26784, "text": "Output:" }, { "code": null, "e": 26797, "s": 26792, "text": "2020" }, { "code": null, "e": 26814, "s": 26797, "text": "arorakashish0911" }, { "code": null, "e": 26828, "s": 26814, "text": "python-basics" }, { "code": null, "e": 26835, "s": 26828, "text": "Python" }, { "code": null, "e": 26851, "s": 26835, "text": "Python Programs" }, { "code": null, "e": 26949, "s": 26851, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26981, "s": 26949, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27023, "s": 26981, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27065, "s": 27023, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27121, "s": 27065, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27148, "s": 27121, "text": "Python Classes and Objects" }, { "code": null, "e": 27170, "s": 27148, "text": "Defaultdict in Python" }, { "code": null, "e": 27209, "s": 27170, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27255, "s": 27209, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27293, "s": 27255, "text": "Python | Convert a list to dictionary" } ]
Cowsay in Nodejs using Requests library - GeeksforGeeks
14 Aug, 2021 Prerequisites: Basic knowledge of NodeJS and JavaScript. Also, you should have NodeJS installed on your machine. Using npm. A good resource. npm will get installed with NodeJS itself. Basic knowledge of command line or terminal. Essentially, we are going to use the requests library to make an API call to fetch data from an external source and use that data as we like. The final app has output like this: The application makes an API call and pipes the data into the cowsay npm module The npm modules we are going to use are: cowsay request Project setup : To implement the above application demo, create a demo folder and create a .js file in it. You can use the below method to create a folder and the .js file // inside your terminal or command-line mkdir gfg_folder //make a folder called 'gfg_folder' cd gfg_folder //navigate your terminal into the folder touch gfg.js // make a javascript file called gfg.js Note :I have used different folder name in this article's images. npm install the required modules : In your terminal, run the following command: npm install cowsay request --save The above command will install the modules necessary to implement the application. express module is a web framework cowsay module provides the cow with the cavity which we will fill with the data fetched from the API Code and Explanation:The gfg.js looks like this: gfg.js snip Request module is designed to be the most simple way to make HTTP calls. Almost all the programming languages have a Request module which is used to fetch and post data from and to a server respectively. Explanation of Code in gfg.js: Step 1 : We ‘require’ request and cowsay module that we installed earlier using npm install request cowsay --save Request module will help us in making HTTP calls to fetch data. Cowsay will provide the cow cavity which we will fill Step 2 : We call the request method and pass it the url to hit and method(GET)as the first parameter. This is called ‘making an API call’. This method returns the three objects talked about below. Step 3 : After the url is GET, the callback function is run with the arguments error, response, body. All three of them are of type object. In this function, we will write the code to execute(filling the cow cavity with the data returned from the API call) and display it to the user in the terminal. Step 4 : We put an if-else conditional inside the callback function. The if checks and runs the code if there is no error( !error ) and the response returned is OK ( response.statusCode = 200 ). Else it will execute the else code. Step 5 : We use the console.log() method to print the cow in the terminal. Inside the console.log() method, we use cowsay.say() method. We put the text:body inside the cowsay.say() method. This puts the data fetched(body of response returned) into the cow cavity. Step 6 : We have written the entire code. Now, go to the terminal and write the following command and voila! Your app is working.Command: node gfg.js The entire code of this article is available here sumitgumber28 Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React Node.js fs.readFileSync() Method
[ { "code": null, "e": 24925, "s": 24897, "text": "\n14 Aug, 2021" }, { "code": null, "e": 24940, "s": 24925, "text": "Prerequisites:" }, { "code": null, "e": 25038, "s": 24940, "text": "Basic knowledge of NodeJS and JavaScript. Also, you should have NodeJS installed on your machine." }, { "code": null, "e": 25109, "s": 25038, "text": "Using npm. A good resource. npm will get installed with NodeJS itself." }, { "code": null, "e": 25154, "s": 25109, "text": "Basic knowledge of command line or terminal." }, { "code": null, "e": 25334, "s": 25154, "text": "Essentially, we are going to use the requests library to make an API call to fetch data from an external source and use that data as we like. The final app has output like this: " }, { "code": null, "e": 25414, "s": 25334, "text": "The application makes an API call and pipes the data into the cowsay npm module" }, { "code": null, "e": 25456, "s": 25414, "text": "The npm modules we are going to use are: " }, { "code": null, "e": 25463, "s": 25456, "text": "cowsay" }, { "code": null, "e": 25471, "s": 25463, "text": "request" }, { "code": null, "e": 25645, "s": 25471, "text": "Project setup : To implement the above application demo, create a demo folder and create a .js file in it. You can use the below method to create a folder and the .js file " }, { "code": null, "e": 25922, "s": 25645, "text": "// inside your terminal or command-line\nmkdir gfg_folder //make a folder called 'gfg_folder'\ncd gfg_folder //navigate your terminal into the folder\ntouch gfg.js // make a javascript file called gfg.js\nNote :I have used different folder name in this article's images." }, { "code": null, "e": 26004, "s": 25922, "text": "npm install the required modules : In your terminal, run the following command: " }, { "code": null, "e": 26038, "s": 26004, "text": "npm install cowsay request --save" }, { "code": null, "e": 26122, "s": 26038, "text": "The above command will install the modules necessary to implement the application. " }, { "code": null, "e": 26156, "s": 26122, "text": "express module is a web framework" }, { "code": null, "e": 26257, "s": 26156, "text": "cowsay module provides the cow with the cavity which we will fill with the data fetched from the API" }, { "code": null, "e": 26308, "s": 26257, "text": "Code and Explanation:The gfg.js looks like this: " }, { "code": null, "e": 26320, "s": 26308, "text": "gfg.js snip" }, { "code": null, "e": 26525, "s": 26320, "text": "Request module is designed to be the most simple way to make HTTP calls. Almost all the programming languages have a Request module which is used to fetch and post data from and to a server respectively. " }, { "code": null, "e": 26556, "s": 26525, "text": "Explanation of Code in gfg.js:" }, { "code": null, "e": 26637, "s": 26556, "text": "Step 1 : We ‘require’ request and cowsay module that we installed earlier using " }, { "code": null, "e": 26671, "s": 26637, "text": "npm install request cowsay --save" }, { "code": null, "e": 26735, "s": 26671, "text": "Request module will help us in making HTTP calls to fetch data." }, { "code": null, "e": 26789, "s": 26735, "text": "Cowsay will provide the cow cavity which we will fill" }, { "code": null, "e": 26986, "s": 26789, "text": "Step 2 : We call the request method and pass it the url to hit and method(GET)as the first parameter. This is called ‘making an API call’. This method returns the three objects talked about below." }, { "code": null, "e": 27287, "s": 26986, "text": "Step 3 : After the url is GET, the callback function is run with the arguments error, response, body. All three of them are of type object. In this function, we will write the code to execute(filling the cow cavity with the data returned from the API call) and display it to the user in the terminal." }, { "code": null, "e": 27520, "s": 27287, "text": "Step 4 : We put an if-else conditional inside the callback function. The if checks and runs the code if there is no error( !error ) and the response returned is OK ( response.statusCode = 200 ). Else it will execute the else code. " }, { "code": null, "e": 27786, "s": 27520, "text": "Step 5 : We use the console.log() method to print the cow in the terminal. Inside the console.log() method, we use cowsay.say() method. We put the text:body inside the cowsay.say() method. This puts the data fetched(body of response returned) into the cow cavity. " }, { "code": null, "e": 27926, "s": 27786, "text": "Step 6 : We have written the entire code. Now, go to the terminal and write the following command and voila! Your app is working.Command: " }, { "code": null, "e": 27938, "s": 27926, "text": "node gfg.js" }, { "code": null, "e": 27989, "s": 27938, "text": "The entire code of this article is available here " }, { "code": null, "e": 28003, "s": 27989, "text": "sumitgumber28" }, { "code": null, "e": 28022, "s": 28003, "text": "Technical Scripter" }, { "code": null, "e": 28039, "s": 28022, "text": "Web Technologies" }, { "code": null, "e": 28137, "s": 28039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28177, "s": 28137, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28210, "s": 28177, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28255, "s": 28210, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28298, "s": 28255, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28348, "s": 28298, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28409, "s": 28348, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28471, "s": 28409, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28529, "s": 28471, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28601, "s": 28529, "text": "Differences between Functional Components and Class Components in React" } ]
Python - Filter unequal elements of two lists corresponding same index - GeeksforGeeks
27 Dec, 2019 Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are unequal and have similar index. This kind of problem can come in many domains. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loop + zip()The combination of above functions can be used to solve this problem. In this, we extract combine the index elements using zip and then extract and check for dissimilarity using conditional statement in loop. # Python3 code to demonstrate working of# Unequal Equi-index elements# using loop + zip() # initialize liststest_list1 = ["a", "b", "c", "d"]test_list2 = ["g", "b", "s", "d"] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Unequal Equi-index elements# using loop + zip()res = []for i, j in zip(test_list1, test_list2): if i != j: res.append(i) # printing resultprint("Unequal index elements in lists : " + str(res)) The original list 1 : ['a', 'b', 'c', 'd'] The original list 2 : ['g', 'b', 's', 'd'] Unequal index elements in lists : ['a', 'c'] Method #2 : Using zip() + list comprehensionCombination of these functionalities can also be used to solve this problem. In this, we use similar method as above, just a shorthand logic compressed using list comprehension. # Python3 code to demonstrate working of# Unequal Equi-index elements# using list comprehension + zip() # initialize liststest_list1 = ["a", "b", "c", "d"]test_list2 = ["g", "b", "s", "d"] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # Unequal Equi-index elements# using list comprehension + zip()res = [i for i, j in zip(test_list1, test_list2) if i != j] # printing resultprint("Unequal index elements in lists : " + str(res)) The original list 1 : ['a', 'b', 'c', 'd'] The original list 2 : ['g', 'b', 's', 'd'] Unequal index elements in lists : ['a', 'c'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n27 Dec, 2019" }, { "code": null, "e": 25819, "s": 25537, "text": "Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are unequal and have similar index. This kind of problem can come in many domains. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 26058, "s": 25819, "text": "Method #1 : Using loop + zip()The combination of above functions can be used to solve this problem. In this, we extract combine the index elements using zip and then extract and check for dissimilarity using conditional statement in loop." }, { "code": "# Python3 code to demonstrate working of# Unequal Equi-index elements# using loop + zip() # initialize liststest_list1 = [\"a\", \"b\", \"c\", \"d\"]test_list2 = [\"g\", \"b\", \"s\", \"d\"] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Unequal Equi-index elements# using loop + zip()res = []for i, j in zip(test_list1, test_list2): if i != j: res.append(i) # printing resultprint(\"Unequal index elements in lists : \" + str(res))", "e": 26566, "s": 26058, "text": null }, { "code": null, "e": 26698, "s": 26566, "text": "The original list 1 : ['a', 'b', 'c', 'd']\nThe original list 2 : ['g', 'b', 's', 'd']\nUnequal index elements in lists : ['a', 'c']\n" }, { "code": null, "e": 26922, "s": 26700, "text": "Method #2 : Using zip() + list comprehensionCombination of these functionalities can also be used to solve this problem. In this, we use similar method as above, just a shorthand logic compressed using list comprehension." }, { "code": "# Python3 code to demonstrate working of# Unequal Equi-index elements# using list comprehension + zip() # initialize liststest_list1 = [\"a\", \"b\", \"c\", \"d\"]test_list2 = [\"g\", \"b\", \"s\", \"d\"] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # Unequal Equi-index elements# using list comprehension + zip()res = [i for i, j in zip(test_list1, test_list2) if i != j] # printing resultprint(\"Unequal index elements in lists : \" + str(res))", "e": 27434, "s": 26922, "text": null }, { "code": null, "e": 27566, "s": 27434, "text": "The original list 1 : ['a', 'b', 'c', 'd']\nThe original list 2 : ['g', 'b', 's', 'd']\nUnequal index elements in lists : ['a', 'c']\n" }, { "code": null, "e": 27587, "s": 27566, "text": "Python list-programs" }, { "code": null, "e": 27594, "s": 27587, "text": "Python" }, { "code": null, "e": 27610, "s": 27594, "text": "Python Programs" }, { "code": null, "e": 27708, "s": 27610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27740, "s": 27708, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27782, "s": 27740, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27824, "s": 27782, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27880, "s": 27824, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27907, "s": 27880, "text": "Python Classes and Objects" }, { "code": null, "e": 27929, "s": 27907, "text": "Defaultdict in Python" }, { "code": null, "e": 27968, "s": 27929, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28014, "s": 27968, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28052, "s": 28014, "text": "Python | Convert a list to dictionary" } ]
Create Password Protected Zip File in Java - GeeksforGeeks
04 Apr, 2022 Primarily, java does not have any function or package that will create a password-protected zip file without using some native codes. Java has some useful library which is good but they use some native codes to perform their task that makes their usage platform dependent to some extent. Whereas in the zip4j library we are just using java code without any support of native code, that is the reason that people are using jip4j over other built-in libraries. There is a library called ‘zip4j’ which was written by “Srikanth Reddy Lingala” back in 2008/2009. It is the most comprehensive Java library for zip files. Some important features of the zip4j library are as follows: It will create, add, extract, update, remove files from a zip file.It has support for streams like ZipInputStream and ZipOuputStream.We can use this library to create any password-protected zip file in java.We can zip/unzip any existing file or directory by just specifying the file path.It also provides supports for both AES 128/256 Encryption and standard Zip Encryption. It will create, add, extract, update, remove files from a zip file. It has support for streams like ZipInputStream and ZipOuputStream. We can use this library to create any password-protected zip file in java. We can zip/unzip any existing file or directory by just specifying the file path. It also provides supports for both AES 128/256 Encryption and standard Zip Encryption. Note: ‘zip4j’ is written on JDK 8 and if we try to run this library on JDK 7, then not all features will be supported. Methods: Naive approach using java.util.zip packageEfficient approach Naive approach using java.util.zip package Efficient approach Method 1: Naive approach We don’t have any standard java in-built library to create a password-protected zip file. We can only make a simple zip file with the help of the java.util.zip package. Example Java // Java Program to Create Password Protected Zip File // Importing all input output classesimport java.io.*;// Importing java.nio utility package API// used for manipulating files and directories// mostly working on Path objectimport java.nio.file.*;// Importing all zip classes from// java.util packageimport java.util.zip.*; // Class// Main classpublic class ZipFile { // Method 1 // Creating an existing file as a zip file private static void zipFile(String filePath) { // Try block to check if any exception occurs try { // Creating an object of File type // getting filePath by passing as an argument File file = new File(filePath); // Getting the name of the above file // as an ZIP format String zipFileName = file.getName().concat(".zip"); // Creating FileOutputStream object and passing the // zip file as an argument FileOutputStream fos = new FileOutputStream(zipFileName); // Creating sn object of FileOutputStream and // passing the above object as an argument ZipOutputStream zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry(file.getName())); // Writing the ZipEntry to stream is not enough // as we need to write its content as well // using the putNextEntry() method byte[] bytes = Files.readAllBytes(Paths.get(filePath)); zos.write(bytes, 0, bytes.length); // ZipFile can only hold 1 entry stream at a go, & // if another entry is to be passed then // current entry stream has to be closed closeEntry // Closing the current entry stream // using the closeEntry() method zos.closeEntry(); // Closing the entire stream completely zos.close(); // If file does not find then it will return the file does not exist } // Catch block 1 // Catch block to handle FieNotFoundException catch (FileNotFoundException ex) { // Print and display message System.err.format("The file does not exist", filePath); } // Catch block 2 // Catch block to handle input output exception catch (IOException ex) { // Print and display message System.err.println("ERROR: " + ex); } } // Method 2 // Main driver method public static void main(String[] args) { String filePath = args[0]; // Calling the above method 1 zipFile(filePath); }} Method 2: Efficient approach Procedure: First, create a list of files to be added to the ZIP file andSpecifying the path you can add it to the list. First, create a list of files to be added to the ZIP file and Specifying the path you can add it to the list. Example Java // Java Program to Create Password Protected Zip File // Importing required libraries// Here, lingala is the name of men// who created zip4j libraryimport java.io.File;import java.util.ArrayList;import net.lingala.zip4j.core.ZipFile;import net.lingala.zip4j.exception.ZipException;import net.lingala.zip4j.model.ZipParameters;import net.lingala.zip4j.util.Zip4jConstants; // Class// To create password protected ZIP filepublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check if any exception occurs try { // Creating encryption zipParameters // for password protection ZipParameters zipParameters = new ZipParameters(); // Setting encryption files zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // Setting encryption of files to true zipParameters.setEncryptFiles(true); // Setting encryption method zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); // Set the key strength zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); // Set the password zipParameters.setPassword("password"); // *********CREATE ZIP FILE*************** //Zip file name String destinationZipFilePath = "D:/myZipFile.zip"; // Creating ZIP file ZipFile zipFile = new ZipFile(destinationZipFilePath); // Creating list of files to be added to ZIP file ArrayList<File> list = new ArrayList<File>(); //Add SPECIFIC files list.add(new File("D:/myFile1.txt")); list.add(new File("D:/myFile2.txt")); // Pass and ZIP parameters // for Zip file to be created zipFile.addFiles(list, zipParameters); // Print the destination in the local directory // where ZIP file is created System.out.println("Password protected Zip file" + "have been created at " + destinationZipFilePath); // Catch block to handle the exceptions } catch (ZipException e) { // Print the exception and line number // where tit occurred e.printStackTrace(); } }} Output: After running this code password-protected Zip file of specific files has been created at D:/myZipFile.zip. Output explanation: Before execution in the above image, we can see 1 directory and 2 files named GeeksForGeeks.txt and krishana_97 Now after execution, we can see the new zip file created. This zip file is the password protested zip file. You have to give the correct password to access the file inside this zip. adnanirshad158 akshaysingh98088 rajeev0719singh surinderdawra388 Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25251, "s": 25223, "text": "\n04 Apr, 2022" }, { "code": null, "e": 25711, "s": 25251, "text": "Primarily, java does not have any function or package that will create a password-protected zip file without using some native codes. Java has some useful library which is good but they use some native codes to perform their task that makes their usage platform dependent to some extent. Whereas in the zip4j library we are just using java code without any support of native code, that is the reason that people are using jip4j over other built-in libraries. " }, { "code": null, "e": 25867, "s": 25711, "text": "There is a library called ‘zip4j’ which was written by “Srikanth Reddy Lingala” back in 2008/2009. It is the most comprehensive Java library for zip files." }, { "code": null, "e": 25928, "s": 25867, "text": "Some important features of the zip4j library are as follows:" }, { "code": null, "e": 26303, "s": 25928, "text": "It will create, add, extract, update, remove files from a zip file.It has support for streams like ZipInputStream and ZipOuputStream.We can use this library to create any password-protected zip file in java.We can zip/unzip any existing file or directory by just specifying the file path.It also provides supports for both AES 128/256 Encryption and standard Zip Encryption." }, { "code": null, "e": 26371, "s": 26303, "text": "It will create, add, extract, update, remove files from a zip file." }, { "code": null, "e": 26438, "s": 26371, "text": "It has support for streams like ZipInputStream and ZipOuputStream." }, { "code": null, "e": 26513, "s": 26438, "text": "We can use this library to create any password-protected zip file in java." }, { "code": null, "e": 26595, "s": 26513, "text": "We can zip/unzip any existing file or directory by just specifying the file path." }, { "code": null, "e": 26682, "s": 26595, "text": "It also provides supports for both AES 128/256 Encryption and standard Zip Encryption." }, { "code": null, "e": 26801, "s": 26682, "text": "Note: ‘zip4j’ is written on JDK 8 and if we try to run this library on JDK 7, then not all features will be supported." }, { "code": null, "e": 26810, "s": 26801, "text": "Methods:" }, { "code": null, "e": 26871, "s": 26810, "text": "Naive approach using java.util.zip packageEfficient approach" }, { "code": null, "e": 26914, "s": 26871, "text": "Naive approach using java.util.zip package" }, { "code": null, "e": 26933, "s": 26914, "text": "Efficient approach" }, { "code": null, "e": 26959, "s": 26933, "text": "Method 1: Naive approach " }, { "code": null, "e": 27128, "s": 26959, "text": "We don’t have any standard java in-built library to create a password-protected zip file. We can only make a simple zip file with the help of the java.util.zip package." }, { "code": null, "e": 27136, "s": 27128, "text": "Example" }, { "code": null, "e": 27141, "s": 27136, "text": "Java" }, { "code": "// Java Program to Create Password Protected Zip File // Importing all input output classesimport java.io.*;// Importing java.nio utility package API// used for manipulating files and directories// mostly working on Path objectimport java.nio.file.*;// Importing all zip classes from// java.util packageimport java.util.zip.*; // Class// Main classpublic class ZipFile { // Method 1 // Creating an existing file as a zip file private static void zipFile(String filePath) { // Try block to check if any exception occurs try { // Creating an object of File type // getting filePath by passing as an argument File file = new File(filePath); // Getting the name of the above file // as an ZIP format String zipFileName = file.getName().concat(\".zip\"); // Creating FileOutputStream object and passing the // zip file as an argument FileOutputStream fos = new FileOutputStream(zipFileName); // Creating sn object of FileOutputStream and // passing the above object as an argument ZipOutputStream zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry(file.getName())); // Writing the ZipEntry to stream is not enough // as we need to write its content as well // using the putNextEntry() method byte[] bytes = Files.readAllBytes(Paths.get(filePath)); zos.write(bytes, 0, bytes.length); // ZipFile can only hold 1 entry stream at a go, & // if another entry is to be passed then // current entry stream has to be closed closeEntry // Closing the current entry stream // using the closeEntry() method zos.closeEntry(); // Closing the entire stream completely zos.close(); // If file does not find then it will return the file does not exist } // Catch block 1 // Catch block to handle FieNotFoundException catch (FileNotFoundException ex) { // Print and display message System.err.format(\"The file does not exist\", filePath); } // Catch block 2 // Catch block to handle input output exception catch (IOException ex) { // Print and display message System.err.println(\"ERROR: \" + ex); } } // Method 2 // Main driver method public static void main(String[] args) { String filePath = args[0]; // Calling the above method 1 zipFile(filePath); }}", "e": 29825, "s": 27141, "text": null }, { "code": null, "e": 29854, "s": 29825, "text": "Method 2: Efficient approach" }, { "code": null, "e": 29865, "s": 29854, "text": "Procedure:" }, { "code": null, "e": 29974, "s": 29865, "text": "First, create a list of files to be added to the ZIP file andSpecifying the path you can add it to the list." }, { "code": null, "e": 30036, "s": 29974, "text": "First, create a list of files to be added to the ZIP file and" }, { "code": null, "e": 30084, "s": 30036, "text": "Specifying the path you can add it to the list." }, { "code": null, "e": 30092, "s": 30084, "text": "Example" }, { "code": null, "e": 30097, "s": 30092, "text": "Java" }, { "code": "// Java Program to Create Password Protected Zip File // Importing required libraries// Here, lingala is the name of men// who created zip4j libraryimport java.io.File;import java.util.ArrayList;import net.lingala.zip4j.core.ZipFile;import net.lingala.zip4j.exception.ZipException;import net.lingala.zip4j.model.ZipParameters;import net.lingala.zip4j.util.Zip4jConstants; // Class// To create password protected ZIP filepublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check if any exception occurs try { // Creating encryption zipParameters // for password protection ZipParameters zipParameters = new ZipParameters(); // Setting encryption files zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // Setting encryption of files to true zipParameters.setEncryptFiles(true); // Setting encryption method zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); // Set the key strength zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); // Set the password zipParameters.setPassword(\"password\"); // *********CREATE ZIP FILE*************** //Zip file name String destinationZipFilePath = \"D:/myZipFile.zip\"; // Creating ZIP file ZipFile zipFile = new ZipFile(destinationZipFilePath); // Creating list of files to be added to ZIP file ArrayList<File> list = new ArrayList<File>(); //Add SPECIFIC files list.add(new File(\"D:/myFile1.txt\")); list.add(new File(\"D:/myFile2.txt\")); // Pass and ZIP parameters // for Zip file to be created zipFile.addFiles(list, zipParameters); // Print the destination in the local directory // where ZIP file is created System.out.println(\"Password protected Zip file\" + \"have been created at \" + destinationZipFilePath); // Catch block to handle the exceptions } catch (ZipException e) { // Print the exception and line number // where tit occurred e.printStackTrace(); } }}", "e": 32815, "s": 30097, "text": null }, { "code": null, "e": 32931, "s": 32815, "text": "Output: After running this code password-protected Zip file of specific files has been created at D:/myZipFile.zip." }, { "code": null, "e": 32952, "s": 32931, "text": "Output explanation: " }, { "code": null, "e": 33065, "s": 32952, "text": "Before execution in the above image, we can see 1 directory and 2 files named GeeksForGeeks.txt and krishana_97 " }, { "code": null, "e": 33248, "s": 33065, "text": "Now after execution, we can see the new zip file created. This zip file is the password protested zip file. You have to give the correct password to access the file inside this zip. " }, { "code": null, "e": 33265, "s": 33250, "text": "adnanirshad158" }, { "code": null, "e": 33282, "s": 33265, "text": "akshaysingh98088" }, { "code": null, "e": 33298, "s": 33282, "text": "rajeev0719singh" }, { "code": null, "e": 33315, "s": 33298, "text": "surinderdawra388" }, { "code": null, "e": 33326, "s": 33315, "text": "Java-Files" }, { "code": null, "e": 33333, "s": 33326, "text": "Picked" }, { "code": null, "e": 33338, "s": 33333, "text": "Java" }, { "code": null, "e": 33352, "s": 33338, "text": "Java Programs" }, { "code": null, "e": 33357, "s": 33352, "text": "Java" }, { "code": null, "e": 33455, "s": 33357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33470, "s": 33455, "text": "Stream In Java" }, { "code": null, "e": 33491, "s": 33470, "text": "Constructors in Java" }, { "code": null, "e": 33510, "s": 33491, "text": "Exceptions in Java" }, { "code": null, "e": 33540, "s": 33510, "text": "Functional Interfaces in Java" }, { "code": null, "e": 33586, "s": 33540, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 33612, "s": 33586, "text": "Java Programming Examples" }, { "code": null, "e": 33646, "s": 33612, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 33693, "s": 33646, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 33725, "s": 33693, "text": "How to Iterate HashMap in Java?" } ]
Node.js v8.getHeapStatistics() Method - GeeksforGeeks
28 Jul, 2020 The v8.getHeapStatistics() method is an inbuilt application programming interface of the v8 module which is used to get statistics about heap derived from the v8 version. Syntax: v8.getHeapStatistics(); Parameters: This method does not have any parameters. Return Value: This method returns an object that contains statistics about version 8 heap. The returned object usually contains an array, that consists of following fields: total_heap_size: A number, signifies total heap size. total_heap_size_executable: A number, signifies total executable heap size. total_physical_size: A number, signifies total physical size. total_available_size: A number, signifies the total available size. used_heap_size: A number, signifies used heap size. heap_size_limit: A number, signifies heap size limit. malloced_memory: A number, signifies malloced memory. peak_malloced_memory: A number, signifies maximum malloced memory. does_zap_garbage: A number, specifically a boolean, signifies whether the –zap_code_space option is enabled or not. number_of_native_contexts: A number, signifies a number of native contexts or the top-level contexts currently active. Memory leakage might be indicated by measuring the increment of this number over time. number_of_detached_contexts: A number, signifies a number of detached contexts or contexts that were detached and not yet garbage collected. Memory leakage might be indicated if it has non zero value. Below examples illustrate the use of v8.getHeapStatistics() method in Node.js. Example 1: Filename: index.js // Accessing v8 moduleconst v8 = require('v8'); // Calling v8.getHeapStatistics() console.log(v8.getHeapStatistics()); Run index.js file using the following command: node index.js Output: { total_heap_size: 6537216, total_heap_size_executable: 1048576, total_physical_size: 6537216, total_available_size: 1520717240, used_heap_size: 4199600, heap_size_limit: 1526909922, malloced_memory: 8192, peak_malloced_memory: 406408, does_zap_garbage: 0 } Example 2: Filename: index.js // Accessing v8 moduleconst v8 = require('v8'); // Calling v8.getHeapStatistics() stats = v8.getHeapStatistics();console.log("Heap Stastistics are :"); console.log("total_heap_size:"+stats['total_heap_size']);console.log("used_heap_size:"+stats['used_heap_size']);console.log("heap_size_limit:"+stats['heap_size_limit']);console.log("does_zap_garbage:"+stats['does_zap_garbage']); Run index.js file using the following command: node index.js Output: Heap Stastistics are : total_heap_size:6537216 used_heap_size:4200640 heap_size_limit:1526909922 does_zap_garbage:0 Reference: https://nodejs.org/api/v8.html#v8_v8_getheapstatistics Node.js-V8-Module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 38501, "s": 38473, "text": "\n28 Jul, 2020" }, { "code": null, "e": 38672, "s": 38501, "text": "The v8.getHeapStatistics() method is an inbuilt application programming interface of the v8 module which is used to get statistics about heap derived from the v8 version." }, { "code": null, "e": 38680, "s": 38672, "text": "Syntax:" }, { "code": null, "e": 38704, "s": 38680, "text": "v8.getHeapStatistics();" }, { "code": null, "e": 38758, "s": 38704, "text": "Parameters: This method does not have any parameters." }, { "code": null, "e": 38931, "s": 38758, "text": "Return Value: This method returns an object that contains statistics about version 8 heap. The returned object usually contains an array, that consists of following fields:" }, { "code": null, "e": 38985, "s": 38931, "text": "total_heap_size: A number, signifies total heap size." }, { "code": null, "e": 39061, "s": 38985, "text": "total_heap_size_executable: A number, signifies total executable heap size." }, { "code": null, "e": 39123, "s": 39061, "text": "total_physical_size: A number, signifies total physical size." }, { "code": null, "e": 39191, "s": 39123, "text": "total_available_size: A number, signifies the total available size." }, { "code": null, "e": 39243, "s": 39191, "text": "used_heap_size: A number, signifies used heap size." }, { "code": null, "e": 39297, "s": 39243, "text": "heap_size_limit: A number, signifies heap size limit." }, { "code": null, "e": 39351, "s": 39297, "text": "malloced_memory: A number, signifies malloced memory." }, { "code": null, "e": 39418, "s": 39351, "text": "peak_malloced_memory: A number, signifies maximum malloced memory." }, { "code": null, "e": 39534, "s": 39418, "text": "does_zap_garbage: A number, specifically a boolean, signifies whether the –zap_code_space option is enabled or not." }, { "code": null, "e": 39740, "s": 39534, "text": "number_of_native_contexts: A number, signifies a number of native contexts or the top-level contexts currently active. Memory leakage might be indicated by measuring the increment of this number over time." }, { "code": null, "e": 39941, "s": 39740, "text": "number_of_detached_contexts: A number, signifies a number of detached contexts or contexts that were detached and not yet garbage collected. Memory leakage might be indicated if it has non zero value." }, { "code": null, "e": 40020, "s": 39941, "text": "Below examples illustrate the use of v8.getHeapStatistics() method in Node.js." }, { "code": null, "e": 40050, "s": 40020, "text": "Example 1: Filename: index.js" }, { "code": "// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.getHeapStatistics() console.log(v8.getHeapStatistics());", "e": 40170, "s": 40050, "text": null }, { "code": null, "e": 40217, "s": 40170, "text": "Run index.js file using the following command:" }, { "code": null, "e": 40231, "s": 40217, "text": "node index.js" }, { "code": null, "e": 40239, "s": 40231, "text": "Output:" }, { "code": null, "e": 40514, "s": 40239, "text": "{ total_heap_size: 6537216,\n total_heap_size_executable: 1048576,\n total_physical_size: 6537216,\n total_available_size: 1520717240,\n used_heap_size: 4199600,\n heap_size_limit: 1526909922,\n malloced_memory: 8192,\n peak_malloced_memory: 406408,\n does_zap_garbage: 0 }\n" }, { "code": null, "e": 40544, "s": 40514, "text": "Example 2: Filename: index.js" }, { "code": "// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.getHeapStatistics() stats = v8.getHeapStatistics();console.log(\"Heap Stastistics are :\"); console.log(\"total_heap_size:\"+stats['total_heap_size']);console.log(\"used_heap_size:\"+stats['used_heap_size']);console.log(\"heap_size_limit:\"+stats['heap_size_limit']);console.log(\"does_zap_garbage:\"+stats['does_zap_garbage']);", "e": 40927, "s": 40544, "text": null }, { "code": null, "e": 40974, "s": 40927, "text": "Run index.js file using the following command:" }, { "code": null, "e": 40988, "s": 40974, "text": "node index.js" }, { "code": null, "e": 40996, "s": 40988, "text": "Output:" }, { "code": null, "e": 41113, "s": 40996, "text": "Heap Stastistics are :\ntotal_heap_size:6537216\nused_heap_size:4200640\nheap_size_limit:1526909922\ndoes_zap_garbage:0\n" }, { "code": null, "e": 41179, "s": 41113, "text": "Reference: https://nodejs.org/api/v8.html#v8_v8_getheapstatistics" }, { "code": null, "e": 41197, "s": 41179, "text": "Node.js-V8-Module" }, { "code": null, "e": 41205, "s": 41197, "text": "Node.js" }, { "code": null, "e": 41222, "s": 41205, "text": "Web Technologies" }, { "code": null, "e": 41320, "s": 41222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41368, "s": 41320, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 41401, "s": 41368, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 41431, "s": 41401, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 41451, "s": 41431, "text": "How to update NPM ?" }, { "code": null, "e": 41505, "s": 41451, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 41545, "s": 41505, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41590, "s": 41545, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41633, "s": 41590, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41683, "s": 41633, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Add array elements in Ruby - GeeksforGeeks
20 Jul, 2021 In this article, we will learn how to add elements to an array in Ruby.Method #1: Using Index Ruby # Ruby program to add elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str[4] = "new_ele";print str # in we skip the elementsstr[6] = "test"; Output: ["GFG", "G4G", "Sudo", "Geeks", "new_ele"] ["GFG", "G4G", "Sudo", "Geeks", "new_ele", nil, "test"] Method #2: Insert at next available index (using push() method) – Ruby # Ruby program to add elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str.push("Geeksforgeeks")print str Output: ["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"] Method #3: Using << syntax instead of the push method – Ruby # Ruby program to add elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str << "Geeksforgeeks"print str Output: ["GFG", "G4G", "Sudo", "Geeks", "Geeksforgeeks"] Method #4: Add element at the beginning – Ruby # Ruby program to add elements # in array # creating string using []str = ["GFG", "G4G", "Sudo", "Geeks"] str.unshift("ele_1")print str Output: ["ele_1", "GFG", "G4G", "Sudo", "Geeks"] surinderdawra388 Ruby Array Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Include v/s Extend in Ruby Global Variable in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | Numeric round() function Ruby | String capitalize() Method
[ { "code": null, "e": 24833, "s": 24805, "text": "\n20 Jul, 2021" }, { "code": null, "e": 24928, "s": 24833, "text": "In this article, we will learn how to add elements to an array in Ruby.Method #1: Using Index " }, { "code": null, "e": 24933, "s": 24928, "text": "Ruby" }, { "code": "# Ruby program to add elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str[4] = \"new_ele\";print str # in we skip the elementsstr[6] = \"test\";", "e": 25114, "s": 24933, "text": null }, { "code": null, "e": 25122, "s": 25114, "text": "Output:" }, { "code": null, "e": 25222, "s": 25122, "text": "[\"GFG\", \"G4G\", \"Sudo\", \"Geeks\", \"new_ele\"]\n\n[\"GFG\", \"G4G\", \"Sudo\", \"Geeks\", \"new_ele\", nil, \"test\"]" }, { "code": null, "e": 25288, "s": 25222, "text": "Method #2: Insert at next available index (using push() method) –" }, { "code": null, "e": 25293, "s": 25288, "text": "Ruby" }, { "code": "# Ruby program to add elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str.push(\"Geeksforgeeks\")print str", "e": 25438, "s": 25293, "text": null }, { "code": null, "e": 25446, "s": 25438, "text": "Output:" }, { "code": null, "e": 25497, "s": 25446, "text": " [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\", \"Geeksforgeeks\"] " }, { "code": null, "e": 25554, "s": 25497, "text": "Method #3: Using << syntax instead of the push method – " }, { "code": null, "e": 25559, "s": 25554, "text": "Ruby" }, { "code": "# Ruby program to add elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str << \"Geeksforgeeks\"print str", "e": 25701, "s": 25559, "text": null }, { "code": null, "e": 25709, "s": 25701, "text": "Output:" }, { "code": null, "e": 25760, "s": 25709, "text": " [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\", \"Geeksforgeeks\"] " }, { "code": null, "e": 25804, "s": 25760, "text": "Method #4: Add element at the beginning – " }, { "code": null, "e": 25809, "s": 25804, "text": "Ruby" }, { "code": "# Ruby program to add elements # in array # creating string using []str = [\"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] str.unshift(\"ele_1\")print str", "e": 25949, "s": 25809, "text": null }, { "code": null, "e": 25957, "s": 25949, "text": "Output:" }, { "code": null, "e": 26000, "s": 25957, "text": " [\"ele_1\", \"GFG\", \"G4G\", \"Sudo\", \"Geeks\"] " }, { "code": null, "e": 26019, "s": 26002, "text": "surinderdawra388" }, { "code": null, "e": 26030, "s": 26019, "text": "Ruby Array" }, { "code": null, "e": 26035, "s": 26030, "text": "Ruby" }, { "code": null, "e": 26133, "s": 26035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26160, "s": 26133, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 26184, "s": 26160, "text": "Global Variable in Ruby" }, { "code": null, "e": 26214, "s": 26184, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 26240, "s": 26214, "text": "Ruby | Types of Variables" }, { "code": null, "e": 26283, "s": 26240, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 26305, "s": 26283, "text": "Ruby | Case Statement" }, { "code": null, "e": 26336, "s": 26305, "text": "Ruby | Array select() function" }, { "code": null, "e": 26354, "s": 26336, "text": "Ruby | Data Types" }, { "code": null, "e": 26386, "s": 26354, "text": "Ruby | Numeric round() function" } ]
HeapSort - GeeksforGeeks
17 Jan, 2022 Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the minimum element and place the minimum element at the beginning. We repeat the same process for the remaining elements. What is Binary Heap? Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source Wikipedia)A Binary Heap is a Complete Binary Tree where items are stored in a special order such that the value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called max heap and the latter is called min-heap. The heap can be represented by a binary tree or array. Why array based representation for Binary Heap? Since a Binary Heap is a Complete Binary Tree, it can be easily represented as an array and the array-based representation is space-efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and the right child by 2 * I + 2 (assuming the indexing starts at 0). How to “heapify” a tree? The process of reshaping a binary tree into a Heap data structure is known as ‘heapify’. A binary tree is a tree data structure that has two child nodes at max. If a node’s children nodes are ‘heapified’, then only ‘heapify’ process can be applied over that node. A heap should always be a complete binary tree. Starting from a complete binary tree, we can modify it to become a Max-Heap by running a function called ‘heapify’ on all the non-leaf elements of the heap. i.e. ‘heapify’ uses recursion. Algorithm for “heapify”: heapify(array) Root = array[0] Largest = largest( array[0] , array [2 * 0 + 1]. array[2 * 0 + 2]) if(Root != Largest) Swap(Root, Largest) Example of “heapify”: 30(0) / \ 70(1) 50(2) Child (70(1)) is greater than the parent (30(0)) Swap Child (70(1)) with the parent (30(0)) 70(0) / \ 30(1) 50(2) Heap Sort Algorithm for sorting in increasing order: 1. Build a max heap from the input data. 2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of the tree. 3. Repeat step 2 while the size of the heap is greater than 1. How to build the heap? Heapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom-up order.Lets understand with the help of an example: Input data: 4, 10, 3, 5, 1 4(0) / \ 10(1) 3(2) / \ 5(3) 1(4) The numbers in bracket represent the indices in the array representation of data. Applying heapify procedure to index 1: 4(0) / \ 10(1) 3(2) / \ 5(3) 1(4) Applying heapify procedure to index 0: 10(0) / \ 5(1) 3(2) / \ 4(3) 1(4) The heapify procedure calls itself recursively to build heap in top down manner. C++ Java Python3 C# PHP Javascript // C++ program for implementation of Heap Sort#include <iostream> using namespace std; // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapvoid heapify(int arr[], int n, int i){ int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); }} // main function to do heap sortvoid heapSort(int arr[], int n){ // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end swap(arr[0], arr[i]); // call max heapify on the reduced heap heapify(arr, i, 0); }} /* A utility function to print array of size n */void printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n";} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << "Sorted array is \n"; printArray(arr, n);} // Java program for implementation of Heap Sortpublic class HeapSort { public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver code public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6, 7 }; int n = arr.length; HeapSort ob = new HeapSort(); ob.sort(arr); System.out.println("Sorted array is"); printArray(arr); }} # Python program for implementation of heap Sort # To heapify subtree rooted at index i.# n is size of heap def heapify(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # greater than root if l < n and arr[largest] < arr[l]: largest = l # See if right child of root exists and is # greater than root if r < n and arr[largest] < arr[r]: largest = r # Change root, if needed if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # swap # Heapify the root. heapify(arr, n, largest) # The main function to sort an array of given size def heapSort(arr): n = len(arr) # Build a maxheap. for i in range(n//2 - 1, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # Driver codearr = [12, 11, 13, 5, 6, 7]heapSort(arr)n = len(arr)print("Sorted array is")for i in range(n): print("%d" % arr[i],end=" ")# This code is contributed by Mohit Kumra // C# program for implementation of Heap Sortusing System; public class HeapSort { public void sort(int[] arr) { int n = arr.Length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int[] arr, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.Read(); } // Driver code public static void Main() { int[] arr = { 12, 11, 13, 5, 6, 7 }; int n = arr.Length; HeapSort ob = new HeapSort(); ob.sort(arr); Console.WriteLine("Sorted array is"); printArray(arr); }} // This code is contributed// by Akanksha Rai(Abby_akku) <?php // Php program for implementation of Heap Sort // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapfunction heapify(&$arr, $n, $i){ $largest = $i; // Initialize largest as root $l = 2*$i + 1; // left = 2*i + 1 $r = 2*$i + 2; // right = 2*i + 2 // If left child is larger than root if ($l < $n && $arr[$l] > $arr[$largest]) $largest = $l; // If right child is larger than largest so far if ($r < $n && $arr[$r] > $arr[$largest]) $largest = $r; // If largest is not root if ($largest != $i) { $swap = $arr[$i]; $arr[$i] = $arr[$largest]; $arr[$largest] = $swap; // Recursively heapify the affected sub-tree heapify($arr, $n, $largest); }} // main function to do heap sortfunction heapSort(&$arr, $n){ // Build heap (rearrange array) for ($i = $n / 2 - 1; $i >= 0; $i--) heapify($arr, $n, $i); // One by one extract an element from heap for ($i = $n-1; $i > 0; $i--) { // Move current root to end $temp = $arr[0]; $arr[0] = $arr[$i]; $arr[$i] = $temp; // call max heapify on the reduced heap heapify($arr, $i, 0); }} /* A utility function to print array of size n */function printArray(&$arr, $n){ for ($i = 0; $i < $n; ++$i) echo ($arr[$i]." ") ; } // Driver program $arr = array(12, 11, 13, 5, 6, 7); $n = sizeof($arr)/sizeof($arr[0]); heapSort($arr, $n); echo 'Sorted array is ' . "\n"; printArray($arr , $n); // This code is contributed by Shivi_Aggarwal?> <script> // JavaScript program for implementation// of Heap Sort function sort( arr) { var n = arr.length; // Build heap (rearrange array) for (var i = Math.floor(n / 2) - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (var i = n - 1; i > 0; i--) { // Move current root to end var temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap function heapify(arr, n, i) { var largest = i; // Initialize largest as root var l = 2 * i + 1; // left = 2*i + 1 var r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { var swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + " "); } var arr = [ 5, 12, 11, 13, 4, 6, 7 ]; var n = arr.length; sort(arr); document.write( "Sorted array is <br>"); printArray(arr, n); // This code is contributed by SoumikMondal </script> Sorted array is 5 6 7 11 12 13 Here is previous C code for reference. Notes: Heap sort is an in-place algorithm. Its typical implementation is not stable, but can be made stable (See this) Time Complexity: Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n) and the overall time complexity of Heap Sort is O(nLogn). Advantages of heapsort – Efficiency – The time required to perform Heap sort increases logarithmically while other algorithms may grow exponentially slower as the number of items to sort increases. This sorting algorithm is very efficient. Memory Usage – Memory usage is minimal because apart from what is necessary to hold the initial list of items to be sorted, it needs no additional memory space to work Simplicity – It is simpler to understand than other equally efficient sorting algorithms because it does not use advanced computer science concepts such as recursion Applications of HeapSort 1. Sort a nearly sorted (or K sorted) array 2. k largest(or smallest) elements in an array Heap sort algorithm has limited uses because Quicksort and Mergesort are better in practice. Nevertheless, the Heap data structure itself is enormously used. See Applications of Heap Data Structurehttps://youtu.be/MtQL_ll5KhQSnapshots: Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz:QuickSort, Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb Sort, Pigeonhole Sort Coding practice for sorting. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Shivi_Aggarwal Akanksha_Rai RishiAdvani Vibhav Gupta kushjaing rishiraj1996 Ameya Gharpure jainabhi279 triptisharma25220 SoumikMondal nathanfriendgeeksforgeeks volumezero9786 amartajisce amartyaghoshgfg 24*7 Innovation Labs Amazon Belzabar Heap Sort Intuit Oracle Samsung SAP Labs Visa Heap Sorting Amazon Samsung 24*7 Innovation Labs Oracle Visa SAP Labs Belzabar Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 K'th Smallest/Largest Element in Unsorted Array | Set 1 k largest(or smallest) elements in an array Building Heap from Array Insertion and Deletion in Heaps
[ { "code": null, "e": 39005, "s": 38977, "text": "\n17 Jan, 2022" }, { "code": null, "e": 39267, "s": 39005, "text": "Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the minimum element and place the minimum element at the beginning. We repeat the same process for the remaining elements." }, { "code": null, "e": 39807, "s": 39267, "text": "What is Binary Heap? Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source Wikipedia)A Binary Heap is a Complete Binary Tree where items are stored in a special order such that the value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called max heap and the latter is called min-heap. The heap can be represented by a binary tree or array." }, { "code": null, "e": 40155, "s": 39807, "text": "Why array based representation for Binary Heap? Since a Binary Heap is a Complete Binary Tree, it can be easily represented as an array and the array-based representation is space-efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and the right child by 2 * I + 2 (assuming the indexing starts at 0)." }, { "code": null, "e": 40180, "s": 40155, "text": "How to “heapify” a tree?" }, { "code": null, "e": 40493, "s": 40180, "text": "The process of reshaping a binary tree into a Heap data structure is known as ‘heapify’. A binary tree is a tree data structure that has two child nodes at max. If a node’s children nodes are ‘heapified’, then only ‘heapify’ process can be applied over that node. A heap should always be a complete binary tree. " }, { "code": null, "e": 40681, "s": 40493, "text": "Starting from a complete binary tree, we can modify it to become a Max-Heap by running a function called ‘heapify’ on all the non-leaf elements of the heap. i.e. ‘heapify’ uses recursion." }, { "code": null, "e": 40706, "s": 40681, "text": "Algorithm for “heapify”:" }, { "code": null, "e": 40860, "s": 40706, "text": "heapify(array)\n Root = array[0]\n Largest = largest( array[0] , array [2 * 0 + 1]. array[2 * 0 + 2])\n if(Root != Largest)\n Swap(Root, Largest)" }, { "code": null, "e": 40882, "s": 40860, "text": "Example of “heapify”:" }, { "code": null, "e": 41118, "s": 40882, "text": " 30(0) \n / \\ \n 70(1) 50(2)\n\nChild (70(1)) is greater than the parent (30(0))\n\nSwap Child (70(1)) with the parent (30(0))\n 70(0) \n / \\ \n 30(1) 50(2)" }, { "code": null, "e": 41470, "s": 41118, "text": "Heap Sort Algorithm for sorting in increasing order: 1. Build a max heap from the input data. 2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of the tree. 3. Repeat step 2 while the size of the heap is greater than 1." }, { "code": null, "e": 41685, "s": 41470, "text": "How to build the heap? Heapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom-up order.Lets understand with the help of an example:" }, { "code": null, "e": 42164, "s": 41685, "text": "Input data: 4, 10, 3, 5, 1\n 4(0)\n / \\\n 10(1) 3(2)\n / \\\n 5(3) 1(4)\n\nThe numbers in bracket represent the indices in the array \nrepresentation of data.\n\nApplying heapify procedure to index 1:\n 4(0)\n / \\\n 10(1) 3(2)\n / \\\n5(3) 1(4)\n\nApplying heapify procedure to index 0:\n 10(0)\n / \\\n 5(1) 3(2)\n / \\\n 4(3) 1(4)\nThe heapify procedure calls itself recursively to build heap\n in top down manner." }, { "code": null, "e": 42168, "s": 42164, "text": "C++" }, { "code": null, "e": 42173, "s": 42168, "text": "Java" }, { "code": null, "e": 42181, "s": 42173, "text": "Python3" }, { "code": null, "e": 42184, "s": 42181, "text": "C#" }, { "code": null, "e": 42188, "s": 42184, "text": "PHP" }, { "code": null, "e": 42199, "s": 42188, "text": "Javascript" }, { "code": "// C++ program for implementation of Heap Sort#include <iostream> using namespace std; // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapvoid heapify(int arr[], int n, int i){ int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); }} // main function to do heap sortvoid heapSort(int arr[], int n){ // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end swap(arr[0], arr[i]); // call max heapify on the reduced heap heapify(arr, i, 0); }} /* A utility function to print array of size n */void printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; cout << \"\\n\";} // Driver codeint main(){ int arr[] = { 12, 11, 13, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << \"Sorted array is \\n\"; printArray(arr, n);}", "e": 43683, "s": 42199, "text": null }, { "code": "// Java program for implementation of Heap Sortpublic class HeapSort { public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver code public static void main(String args[]) { int arr[] = { 12, 11, 13, 5, 6, 7 }; int n = arr.length; HeapSort ob = new HeapSort(); ob.sort(arr); System.out.println(\"Sorted array is\"); printArray(arr); }}", "e": 45540, "s": 43683, "text": null }, { "code": "# Python program for implementation of heap Sort # To heapify subtree rooted at index i.# n is size of heap def heapify(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # greater than root if l < n and arr[largest] < arr[l]: largest = l # See if right child of root exists and is # greater than root if r < n and arr[largest] < arr[r]: largest = r # Change root, if needed if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # swap # Heapify the root. heapify(arr, n, largest) # The main function to sort an array of given size def heapSort(arr): n = len(arr) # Build a maxheap. for i in range(n//2 - 1, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # Driver codearr = [12, 11, 13, 5, 6, 7]heapSort(arr)n = len(arr)print(\"Sorted array is\")for i in range(n): print(\"%d\" % arr[i],end=\" \")# This code is contributed by Mohit Kumra", "e": 46711, "s": 45540, "text": null }, { "code": "// C# program for implementation of Heap Sortusing System; public class HeapSort { public void sort(int[] arr) { int n = arr.Length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int[] arr, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.Read(); } // Driver code public static void Main() { int[] arr = { 12, 11, 13, 5, 6, 7 }; int n = arr.Length; HeapSort ob = new HeapSort(); ob.sort(arr); Console.WriteLine(\"Sorted array is\"); printArray(arr); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 48614, "s": 46711, "text": null }, { "code": "<?php // Php program for implementation of Heap Sort // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapfunction heapify(&$arr, $n, $i){ $largest = $i; // Initialize largest as root $l = 2*$i + 1; // left = 2*i + 1 $r = 2*$i + 2; // right = 2*i + 2 // If left child is larger than root if ($l < $n && $arr[$l] > $arr[$largest]) $largest = $l; // If right child is larger than largest so far if ($r < $n && $arr[$r] > $arr[$largest]) $largest = $r; // If largest is not root if ($largest != $i) { $swap = $arr[$i]; $arr[$i] = $arr[$largest]; $arr[$largest] = $swap; // Recursively heapify the affected sub-tree heapify($arr, $n, $largest); }} // main function to do heap sortfunction heapSort(&$arr, $n){ // Build heap (rearrange array) for ($i = $n / 2 - 1; $i >= 0; $i--) heapify($arr, $n, $i); // One by one extract an element from heap for ($i = $n-1; $i > 0; $i--) { // Move current root to end $temp = $arr[0]; $arr[0] = $arr[$i]; $arr[$i] = $temp; // call max heapify on the reduced heap heapify($arr, $i, 0); }} /* A utility function to print array of size n */function printArray(&$arr, $n){ for ($i = 0; $i < $n; ++$i) echo ($arr[$i].\" \") ; } // Driver program $arr = array(12, 11, 13, 5, 6, 7); $n = sizeof($arr)/sizeof($arr[0]); heapSort($arr, $n); echo 'Sorted array is ' . \"\\n\"; printArray($arr , $n); // This code is contributed by Shivi_Aggarwal?>", "e": 50219, "s": 48614, "text": null }, { "code": "<script> // JavaScript program for implementation// of Heap Sort function sort( arr) { var n = arr.length; // Build heap (rearrange array) for (var i = Math.floor(n / 2) - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (var i = n - 1; i > 0; i--) { // Move current root to end var temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap function heapify(arr, n, i) { var largest = i; // Initialize largest as root var l = 2 * i + 1; // left = 2*i + 1 var r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { var swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + \" \"); } var arr = [ 5, 12, 11, 13, 4, 6, 7 ]; var n = arr.length; sort(arr); document.write( \"Sorted array is <br>\"); printArray(arr, n); // This code is contributed by SoumikMondal </script>", "e": 51961, "s": 50219, "text": null }, { "code": null, "e": 51994, "s": 51961, "text": "Sorted array is \n5 6 7 11 12 13 " }, { "code": null, "e": 52033, "s": 51994, "text": "Here is previous C code for reference." }, { "code": null, "e": 52152, "s": 52033, "text": "Notes: Heap sort is an in-place algorithm. Its typical implementation is not stable, but can be made stable (See this)" }, { "code": null, "e": 52314, "s": 52152, "text": "Time Complexity: Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n) and the overall time complexity of Heap Sort is O(nLogn)." }, { "code": null, "e": 52339, "s": 52314, "text": "Advantages of heapsort –" }, { "code": null, "e": 52555, "s": 52339, "text": "Efficiency – The time required to perform Heap sort increases logarithmically while other algorithms may grow exponentially slower as the number of items to sort increases. This sorting algorithm is very efficient." }, { "code": null, "e": 52723, "s": 52555, "text": "Memory Usage – Memory usage is minimal because apart from what is necessary to hold the initial list of items to be sorted, it needs no additional memory space to work" }, { "code": null, "e": 52890, "s": 52723, "text": "Simplicity – It is simpler to understand than other equally efficient sorting algorithms because it does not use advanced computer science concepts such as recursion" }, { "code": null, "e": 53244, "s": 52890, "text": "Applications of HeapSort 1. Sort a nearly sorted (or K sorted) array 2. k largest(or smallest) elements in an array Heap sort algorithm has limited uses because Quicksort and Mergesort are better in practice. Nevertheless, the Heap data structure itself is enormously used. See Applications of Heap Data Structurehttps://youtu.be/MtQL_ll5KhQSnapshots: " }, { "code": null, "e": 53476, "s": 53256, "text": "Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz:QuickSort, Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort, Counting Sort, Bucket Sort, ShellSort, Comb Sort, Pigeonhole Sort" }, { "code": null, "e": 53505, "s": 53476, "text": "Coding practice for sorting." }, { "code": null, "e": 53631, "s": 53505, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 53646, "s": 53631, "text": "Shivi_Aggarwal" }, { "code": null, "e": 53659, "s": 53646, "text": "Akanksha_Rai" }, { "code": null, "e": 53671, "s": 53659, "text": "RishiAdvani" }, { "code": null, "e": 53684, "s": 53671, "text": "Vibhav Gupta" }, { "code": null, "e": 53694, "s": 53684, "text": "kushjaing" }, { "code": null, "e": 53707, "s": 53694, "text": "rishiraj1996" }, { "code": null, "e": 53722, "s": 53707, "text": "Ameya Gharpure" }, { "code": null, "e": 53734, "s": 53722, "text": "jainabhi279" }, { "code": null, "e": 53752, "s": 53734, "text": "triptisharma25220" }, { "code": null, "e": 53765, "s": 53752, "text": "SoumikMondal" }, { "code": null, "e": 53791, "s": 53765, "text": "nathanfriendgeeksforgeeks" }, { "code": null, "e": 53806, "s": 53791, "text": "volumezero9786" }, { "code": null, "e": 53818, "s": 53806, "text": "amartajisce" }, { "code": null, "e": 53834, "s": 53818, "text": "amartyaghoshgfg" }, { "code": null, "e": 53855, "s": 53834, "text": "24*7 Innovation Labs" }, { "code": null, "e": 53862, "s": 53855, "text": "Amazon" }, { "code": null, "e": 53871, "s": 53862, "text": "Belzabar" }, { "code": null, "e": 53881, "s": 53871, "text": "Heap Sort" }, { "code": null, "e": 53888, "s": 53881, "text": "Intuit" }, { "code": null, "e": 53895, "s": 53888, "text": "Oracle" }, { "code": null, "e": 53903, "s": 53895, "text": "Samsung" }, { "code": null, "e": 53912, "s": 53903, "text": "SAP Labs" }, { "code": null, "e": 53917, "s": 53912, "text": "Visa" }, { "code": null, "e": 53922, "s": 53917, "text": "Heap" }, { "code": null, "e": 53930, "s": 53922, "text": "Sorting" }, { "code": null, "e": 53937, "s": 53930, "text": "Amazon" }, { "code": null, "e": 53945, "s": 53937, "text": "Samsung" }, { "code": null, "e": 53966, "s": 53945, "text": "24*7 Innovation Labs" }, { "code": null, "e": 53973, "s": 53966, "text": "Oracle" }, { "code": null, "e": 53978, "s": 53973, "text": "Visa" }, { "code": null, "e": 53987, "s": 53978, "text": "SAP Labs" }, { "code": null, "e": 53996, "s": 53987, "text": "Belzabar" }, { "code": null, "e": 54004, "s": 53996, "text": "Sorting" }, { "code": null, "e": 54009, "s": 54004, "text": "Heap" }, { "code": null, "e": 54107, "s": 54009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54138, "s": 54107, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 54194, "s": 54138, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 54238, "s": 54194, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 54263, "s": 54238, "text": "Building Heap from Array" } ]
Python Tkinter - ScrolledText Widget - GeeksforGeeks
21 Apr, 2020 Tkinter is a built-in standard python library. With the help of Tkinter, many GUI applications can be created easily. There are various types of widgets available in Tkinter such as button, frame, label, menu, scrolledtext, canvas and many more. A widget is an element that provides various controls. ScrolledText widget is a text widget with a scroll bar. The tkinter.scrolledtext module provides the text widget along with a scroll bar. This widget helps the user enter multiple lines of text with convenience. Instead of adding a Scroll bar to a text widget, we can make use of a scrolledtext widget that helps to enter any number of lines of text. Example 1 : Python code displaying scrolledText widget. # Python program demonstrating# ScrolledText widget in tkinter import tkinter as tkfrom tkinter import ttkfrom tkinter import scrolledtext # Creating tkinter main windowwin = tk.Tk()win.title("ScrolledText Widget") # Title Labelttk.Label(win, text = "ScrolledText Widget Example", font = ("Times New Roman", 15), background = 'green', foreground = "white").grid(column = 0, row = 0) # Creating scrolled text # area widgettext_area = scrolledtext.ScrolledText(win, wrap = tk.WORD, width = 40, height = 10, font = ("Times New Roman", 15)) text_area.grid(column = 0, pady = 10, padx = 10) # Placing cursor in the text areatext_area.focus()win.mainloop() Output : Example 2 : ScrolledText widget making tkinter text Read only. # Importing required modules import tkinter as tkimport tkinter.scrolledtext as st # Creating tkinter windowwin = tk.Tk()win.title("ScrolledText Widget") # Title Labeltk.Label(win, text = "ScrolledText Widget Example", font = ("Times New Roman", 15), background = 'green', foreground = "white").grid(column = 0, row = 0) # Creating scrolled text area# widget with Read only by# disabling the statetext_area = st.ScrolledText(win, width = 30, height = 8, font = ("Times New Roman", 15)) text_area.grid(column = 0, pady = 10, padx = 10) # Inserting Text which is read onlytext_area.insert(tk.INSERT,"""\This is a scrolledtext widget to make tkinter text read only.HiGeeks !!!Geeks !!!Geeks !!! Geeks !!!Geeks !!!Geeks !!!Geeks !!!""") # Making the text read onlytext_area.configure(state ='disabled')win.mainloop() Output : In the first example, as you can see the cursor, the user can enter any number of lines of text. In the second example, the user can just read the text which is displayed in the text box and cannot edit/enter any lines of text. We may observe that the scroll bar disappears automatically if the text entered by the user is less than the size of the widget. Python-tkinter Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 42675, "s": 42647, "text": "\n21 Apr, 2020" }, { "code": null, "e": 43327, "s": 42675, "text": "Tkinter is a built-in standard python library. With the help of Tkinter, many GUI applications can be created easily. There are various types of widgets available in Tkinter such as button, frame, label, menu, scrolledtext, canvas and many more. A widget is an element that provides various controls. ScrolledText widget is a text widget with a scroll bar. The tkinter.scrolledtext module provides the text widget along with a scroll bar. This widget helps the user enter multiple lines of text with convenience. Instead of adding a Scroll bar to a text widget, we can make use of a scrolledtext widget that helps to enter any number of lines of text." }, { "code": null, "e": 43383, "s": 43327, "text": "Example 1 : Python code displaying scrolledText widget." }, { "code": "# Python program demonstrating# ScrolledText widget in tkinter import tkinter as tkfrom tkinter import ttkfrom tkinter import scrolledtext # Creating tkinter main windowwin = tk.Tk()win.title(\"ScrolledText Widget\") # Title Labelttk.Label(win, text = \"ScrolledText Widget Example\", font = (\"Times New Roman\", 15), background = 'green', foreground = \"white\").grid(column = 0, row = 0) # Creating scrolled text # area widgettext_area = scrolledtext.ScrolledText(win, wrap = tk.WORD, width = 40, height = 10, font = (\"Times New Roman\", 15)) text_area.grid(column = 0, pady = 10, padx = 10) # Placing cursor in the text areatext_area.focus()win.mainloop()", "e": 44312, "s": 43383, "text": null }, { "code": null, "e": 44321, "s": 44312, "text": "Output :" }, { "code": null, "e": 44384, "s": 44321, "text": "Example 2 : ScrolledText widget making tkinter text Read only." }, { "code": "# Importing required modules import tkinter as tkimport tkinter.scrolledtext as st # Creating tkinter windowwin = tk.Tk()win.title(\"ScrolledText Widget\") # Title Labeltk.Label(win, text = \"ScrolledText Widget Example\", font = (\"Times New Roman\", 15), background = 'green', foreground = \"white\").grid(column = 0, row = 0) # Creating scrolled text area# widget with Read only by# disabling the statetext_area = st.ScrolledText(win, width = 30, height = 8, font = (\"Times New Roman\", 15)) text_area.grid(column = 0, pady = 10, padx = 10) # Inserting Text which is read onlytext_area.insert(tk.INSERT,\"\"\"\\This is a scrolledtext widget to make tkinter text read only.HiGeeks !!!Geeks !!!Geeks !!! Geeks !!!Geeks !!!Geeks !!!Geeks !!!\"\"\") # Making the text read onlytext_area.configure(state ='disabled')win.mainloop()", "e": 45393, "s": 44384, "text": null }, { "code": null, "e": 45402, "s": 45393, "text": "Output :" }, { "code": null, "e": 45759, "s": 45402, "text": "In the first example, as you can see the cursor, the user can enter any number of lines of text. In the second example, the user can just read the text which is displayed in the text box and cannot edit/enter any lines of text. We may observe that the scroll bar disappears automatically if the text entered by the user is less than the size of the widget." }, { "code": null, "e": 45774, "s": 45759, "text": "Python-tkinter" }, { "code": null, "e": 45781, "s": 45774, "text": "Python" }, { "code": null, "e": 45797, "s": 45781, "text": "Write From Home" }, { "code": null, "e": 45895, "s": 45797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45923, "s": 45895, "text": "Read JSON file using Python" }, { "code": null, "e": 45973, "s": 45923, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 45995, "s": 45973, "text": "Python map() function" }, { "code": null, "e": 46039, "s": 45995, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 46074, "s": 46039, "text": "Read a file line by line in Python" }, { "code": null, "e": 46110, "s": 46074, "text": "Convert integer to string in Python" }, { "code": null, "e": 46146, "s": 46110, "text": "Convert string to integer in Python" }, { "code": null, "e": 46207, "s": 46146, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 46223, "s": 46207, "text": "Python infinity" } ]
mailx in Linux - GeeksforGeeks
24 Jul, 2020 Linux has an inbuilt Mail User Agent program called mailx. As the name suggests, it is a console application that is used for sending and receiving emails. The mailx utility is an enhanced version of the mail command. Along with the functionality provided by the original mail command, it provides extra features like the ability to send attachments by using the -a flag. The mailx command is available from a variety of different packages: bsd-mailx heirloom-mailx mailutils For Ubuntu/Debian: sudo apt-get install bsd-mailx For fedore/centos: sudo yum install mailx Note: Even though the mailx command is a newer version of the original mail utility, it can still be referenced with the ‘mail’ keyword. 1. Writing the message directly in the command line: To send a simple email, use the “-s” flag to set the subject in quotes which is followed by the email of the receiver. After this, mailx waits for the content of the email. To enter new lines, keep hitting enter. After the content is written, press Ctrl+D & EOT will be displayed by mailx. $ mail -s "A mail sent using mailx" [email protected] Hey person, Hope you're fine these days Thanks EOT 2. Taking the message from a file $ mail -s "A mail sent using mailx" [email protected] < /path/to/file 3. Using pipes $ echo "Example Message" | mail - s "A mail sent using mailx" [email protected] 4. Sending same Mail to Multiple Recipients: We can send the same email to multiple receivers (not by cc or bcc) as follows: $ mail - s "A mail sent using mailx" [email protected], [email protected] < /path/to/file 5. Adding CC & BCC We can send a carbon copy (CC) or a blind carbon copy (BCC) to send the same email to multiple recipients (visibly or in a hidden manner). For CC, we use the “-c” option & for BCC we use the “-b” option which is followed by the email addresses. $ mail - s "A mail sent using mailx" [email protected] -c [email protected] -b [email protected] 6. Adding AttachmentsAttachments are a vital part of email communication. We can attach documents, images, text files, etc. by using the “-a” option followed by the path of the file that we want to attach. $ mail - s "A mail sent using mailx" [email protected] -a Attachment.txt Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25677, "s": 25649, "text": "\n24 Jul, 2020" }, { "code": null, "e": 26120, "s": 25677, "text": "Linux has an inbuilt Mail User Agent program called mailx. As the name suggests, it is a console application that is used for sending and receiving emails. The mailx utility is an enhanced version of the mail command. Along with the functionality provided by the original mail command, it provides extra features like the ability to send attachments by using the -a flag. The mailx command is available from a variety of different packages: " }, { "code": null, "e": 26131, "s": 26120, "text": "bsd-mailx " }, { "code": null, "e": 26147, "s": 26131, "text": "heirloom-mailx " }, { "code": null, "e": 26159, "s": 26147, "text": "mailutils " }, { "code": null, "e": 26179, "s": 26159, "text": "For Ubuntu/Debian: " }, { "code": null, "e": 26211, "s": 26179, "text": "sudo apt-get install bsd-mailx\n" }, { "code": null, "e": 26232, "s": 26211, "text": "For fedore/centos: " }, { "code": null, "e": 26256, "s": 26232, "text": "sudo yum install mailx\n" }, { "code": null, "e": 26395, "s": 26256, "text": "Note: Even though the mailx command is a newer version of the original mail utility, it can still be referenced with the ‘mail’ keyword. " }, { "code": null, "e": 26740, "s": 26395, "text": "1. Writing the message directly in the command line: To send a simple email, use the “-s” flag to set the subject in quotes which is followed by the email of the receiver. After this, mailx waits for the content of the email. To enter new lines, keep hitting enter. After the content is written, press Ctrl+D & EOT will be displayed by mailx. " }, { "code": null, "e": 26847, "s": 26740, "text": "$ mail -s \"A mail sent using mailx\" [email protected]\nHey person,\nHope you're fine these days\nThanks\nEOT\n" }, { "code": null, "e": 26883, "s": 26847, "text": "2. Taking the message from a file " }, { "code": null, "e": 26955, "s": 26883, "text": "$ mail -s \"A mail sent using mailx\" [email protected] < /path/to/file\n" }, { "code": null, "e": 26972, "s": 26955, "text": "3. Using pipes " }, { "code": null, "e": 27054, "s": 26972, "text": "$ echo \"Example Message\" | mail - s \"A mail sent using mailx\" [email protected]\n" }, { "code": null, "e": 27180, "s": 27054, "text": "4. Sending same Mail to Multiple Recipients: We can send the same email to multiple receivers (not by cc or bcc) as follows: " }, { "code": null, "e": 27279, "s": 27180, "text": "$ mail - s \"A mail sent using mailx\" [email protected], [email protected] < /path/to/file\n" }, { "code": null, "e": 27299, "s": 27279, "text": "5. Adding CC & BCC " }, { "code": null, "e": 27545, "s": 27299, "text": "We can send a carbon copy (CC) or a blind carbon copy (BCC) to send the same email to multiple recipients (visibly or in a hidden manner). For CC, we use the “-c” option & for BCC we use the “-b” option which is followed by the email addresses. " }, { "code": null, "e": 27658, "s": 27545, "text": "$ mail - s \"A mail sent using mailx\" [email protected] -c [email protected] -b [email protected] \n" }, { "code": null, "e": 27865, "s": 27658, "text": "6. Adding AttachmentsAttachments are a vital part of email communication. We can attach documents, images, text files, etc. by using the “-a” option followed by the path of the file that we want to attach. " }, { "code": null, "e": 27943, "s": 27865, "text": "$ mail - s \"A mail sent using mailx\" [email protected] -a Attachment.txt\n" }, { "code": null, "e": 27950, "s": 27943, "text": "Picked" }, { "code": null, "e": 27961, "s": 27950, "text": "Linux-Unix" }, { "code": null, "e": 28059, "s": 27961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28094, "s": 28059, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28128, "s": 28094, "text": "mv command in Linux with examples" }, { "code": null, "e": 28154, "s": 28128, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28183, "s": 28154, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28220, "s": 28183, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28257, "s": 28220, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28299, "s": 28257, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28325, "s": 28299, "text": "Thread functions in C/C++" }, { "code": null, "e": 28361, "s": 28325, "text": "uniq Command in LINUX with examples" } ]
Python - Draw Octagonal shape Using Turtle Graphics - GeeksforGeeks
19 Oct, 2020 In this article, we will learn how to Make an Octagon using Turtle Graphics in Python. For that lets first know what is Turtle Graphics. backward(length): moves the pen in the backward direction by x unit. right(angle): rotate the pen in the clockwise direction by an angle x. left(angle): rotate the pen in the anticlockwise direction by an angle x. penup(): stop drawing of the turtle pen. pendown(): start drawing of the turtle pen. Import the turtle modules. Get a screen to draw on Define an instance for the turtle. For a drawing, an Octagon executes a loop 8 times. In every iteration move the turtle 100 units forward and move it left 45 degrees( corresponding to 135 degrees between two sides, so 180-135=45 degrees). This will make up an angle of 135 degrees between 2 sides. 8 iterations will make up an Octagon perfectly. Below is the Python implementation of the above approach: Python3 # import for turtle moduleimport turtle # making a workScreenws = turtle.Screen() # defining a turtle instancegeekyTurtle = turtle.Turtle() # iterating the loop 8 timesfor i in range(8): # moving turtle 100 units forward geekyTurtle.forward(100) # turning turtle 45 degrees so # as to make perfect angle for an octagon geekyTurtle.left(45) Output: Octagon anshitaagarwal Python-turtle Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25863, "s": 25835, "text": "\n19 Oct, 2020" }, { "code": null, "e": 26000, "s": 25863, "text": "In this article, we will learn how to Make an Octagon using Turtle Graphics in Python. For that lets first know what is Turtle Graphics." }, { "code": null, "e": 26069, "s": 26000, "text": "backward(length): moves the pen in the backward direction by x unit." }, { "code": null, "e": 26140, "s": 26069, "text": "right(angle): rotate the pen in the clockwise direction by an angle x." }, { "code": null, "e": 26214, "s": 26140, "text": "left(angle): rotate the pen in the anticlockwise direction by an angle x." }, { "code": null, "e": 26255, "s": 26214, "text": "penup(): stop drawing of the turtle pen." }, { "code": null, "e": 26299, "s": 26255, "text": "pendown(): start drawing of the turtle pen." }, { "code": null, "e": 26326, "s": 26299, "text": "Import the turtle modules." }, { "code": null, "e": 26350, "s": 26326, "text": "Get a screen to draw on" }, { "code": null, "e": 26385, "s": 26350, "text": "Define an instance for the turtle." }, { "code": null, "e": 26436, "s": 26385, "text": "For a drawing, an Octagon executes a loop 8 times." }, { "code": null, "e": 26590, "s": 26436, "text": "In every iteration move the turtle 100 units forward and move it left 45 degrees( corresponding to 135 degrees between two sides, so 180-135=45 degrees)." }, { "code": null, "e": 26649, "s": 26590, "text": "This will make up an angle of 135 degrees between 2 sides." }, { "code": null, "e": 26755, "s": 26649, "text": "8 iterations will make up an Octagon perfectly. Below is the Python implementation of the above approach:" }, { "code": null, "e": 26763, "s": 26755, "text": "Python3" }, { "code": "# import for turtle moduleimport turtle # making a workScreenws = turtle.Screen() # defining a turtle instancegeekyTurtle = turtle.Turtle() # iterating the loop 8 timesfor i in range(8): # moving turtle 100 units forward geekyTurtle.forward(100) # turning turtle 45 degrees so # as to make perfect angle for an octagon geekyTurtle.left(45)", "e": 27126, "s": 26763, "text": null }, { "code": null, "e": 27134, "s": 27126, "text": "Output:" }, { "code": null, "e": 27142, "s": 27134, "text": "Octagon" }, { "code": null, "e": 27157, "s": 27142, "text": "anshitaagarwal" }, { "code": null, "e": 27171, "s": 27157, "text": "Python-turtle" }, { "code": null, "e": 27178, "s": 27171, "text": "Python" }, { "code": null, "e": 27194, "s": 27178, "text": "Python Programs" }, { "code": null, "e": 27292, "s": 27194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27310, "s": 27292, "text": "Python Dictionary" }, { "code": null, "e": 27345, "s": 27310, "text": "Read a file line by line in Python" }, { "code": null, "e": 27377, "s": 27345, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27399, "s": 27377, "text": "Enumerate() in Python" }, { "code": null, "e": 27441, "s": 27399, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27484, "s": 27441, "text": "Python program to convert a list to string" }, { "code": null, "e": 27506, "s": 27484, "text": "Defaultdict in Python" }, { "code": null, "e": 27545, "s": 27506, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27591, "s": 27545, "text": "Python | Split string into list of characters" } ]
How to change the checkbox value using jQuery ? - GeeksforGeeks
03 Aug, 2021 The Checkboxes are used to let a user select one or more options for a limited number of choices. The :checkbox selector selects input elements with type checkbox.Syntax: $('#textboxID').val($("#checkboxID").is(':checked')); In the above syntax, basically the return value of the checked or unchecked checkbox is being assigned to the textbox. Below examples will illustrate the approach:Example 1: Here the return value of the checkbox is assigned to the textbox with a function click() whenever the checkbox is clicked to check or uncheck, it assigns the respective return value into the textbox. So, if we want to assign a certain user-defined value in the textbox according to check then we can do that with the use of if/else statement. html <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function() { // Set initial state $('#textbox2').val($(this).is(':checked')); // It gets checked to false as uncheck // is the default $('#checkbox1').click(function() { $('#textbox2').val($(this).is(':checked')); }); }); </script></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <input type="checkbox" id="checkbox1" /> Check if true, Uncheck if false. <br><br> <input type="text" id="textbox2" /> </center></body> </html> Output: Example 2: This example contains more than one checkboxes. javascript <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <script> $(document).ready(function() { // Set initial state $('#textbox1').val('no'); // Returns yes or no in textbox1 // when checked and unchecked $('#checkbox1').click(function() { if ($("#checkbox1").is(":checked") == true) { $('#textbox1').val('yes'); } else { $('#textbox1').val('no'); } }); // Returns male in textbox2 if checkbox2 checked. $('#checkbox2').click(function() { if ($('#checkbox2').is(":checked") == true) { $('#textbox2').val('Male'); } else { $('#textbox2').val(''); } }); // Returns female in textbox2 // if checkbox2 checked. $('#checkbox3').change(function() { if ($('#checkbox3').is(":checked") == true) { $('#textbox2').val('Female'); } else { $('#textbox2').val(''); } }); }); </script></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <input type="checkbox" id="checkbox1" /> Check If yes! <br> <input type="text" id="textbox1" /> <br> <input type="checkbox" id="checkbox2" /> Male <input type="checkbox" id="checkbox3" /> Female <br> <input type="text" id="textbox2" /> </center></body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. adnanirshad158 jQuery-Misc Picked JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples jQuery | change() with Examples Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26898, "s": 26870, "text": "\n03 Aug, 2021" }, { "code": null, "e": 27071, "s": 26898, "text": "The Checkboxes are used to let a user select one or more options for a limited number of choices. The :checkbox selector selects input elements with type checkbox.Syntax: " }, { "code": null, "e": 27125, "s": 27071, "text": "$('#textboxID').val($(\"#checkboxID\").is(':checked'));" }, { "code": null, "e": 27644, "s": 27125, "text": "In the above syntax, basically the return value of the checked or unchecked checkbox is being assigned to the textbox. Below examples will illustrate the approach:Example 1: Here the return value of the checkbox is assigned to the textbox with a function click() whenever the checkbox is clicked to check or uncheck, it assigns the respective return value into the textbox. So, if we want to assign a certain user-defined value in the textbox according to check then we can do that with the use of if/else statement. " }, { "code": null, "e": 27649, "s": 27644, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script> $(document).ready(function() { // Set initial state $('#textbox2').val($(this).is(':checked')); // It gets checked to false as uncheck // is the default $('#checkbox1').click(function() { $('#textbox2').val($(this).is(':checked')); }); }); </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <input type=\"checkbox\" id=\"checkbox1\" /> Check if true, Uncheck if false. <br><br> <input type=\"text\" id=\"textbox2\" /> </center></body> </html>", "e": 28540, "s": 27649, "text": null }, { "code": null, "e": 28550, "s": 28540, "text": "Output: " }, { "code": null, "e": 28611, "s": 28550, "text": "Example 2: This example contains more than one checkboxes. " }, { "code": null, "e": 28622, "s": 28611, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> </script> <script> $(document).ready(function() { // Set initial state $('#textbox1').val('no'); // Returns yes or no in textbox1 // when checked and unchecked $('#checkbox1').click(function() { if ($(\"#checkbox1\").is(\":checked\") == true) { $('#textbox1').val('yes'); } else { $('#textbox1').val('no'); } }); // Returns male in textbox2 if checkbox2 checked. $('#checkbox2').click(function() { if ($('#checkbox2').is(\":checked\") == true) { $('#textbox2').val('Male'); } else { $('#textbox2').val(''); } }); // Returns female in textbox2 // if checkbox2 checked. $('#checkbox3').change(function() { if ($('#checkbox3').is(\":checked\") == true) { $('#textbox2').val('Female'); } else { $('#textbox2').val(''); } }); }); </script></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> A Computer Science Portal for Geeks </p> <input type=\"checkbox\" id=\"checkbox1\" /> Check If yes! <br> <input type=\"text\" id=\"textbox1\" /> <br> <input type=\"checkbox\" id=\"checkbox2\" /> Male <input type=\"checkbox\" id=\"checkbox3\" /> Female <br> <input type=\"text\" id=\"textbox2\" /> </center></body> </html>", "e": 30483, "s": 28622, "text": null }, { "code": null, "e": 30493, "s": 30483, "text": "Output: " }, { "code": null, "e": 30763, "s": 30495, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 30778, "s": 30763, "text": "adnanirshad158" }, { "code": null, "e": 30790, "s": 30778, "text": "jQuery-Misc" }, { "code": null, "e": 30797, "s": 30790, "text": "Picked" }, { "code": null, "e": 30804, "s": 30797, "text": "JQuery" }, { "code": null, "e": 30821, "s": 30804, "text": "Web Technologies" }, { "code": null, "e": 30848, "s": 30821, "text": "Web technologies Questions" }, { "code": null, "e": 30946, "s": 30848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31001, "s": 30946, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 31074, "s": 31001, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 31097, "s": 31074, "text": "jQuery | ajax() Method" }, { "code": null, "e": 31133, "s": 31097, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 31165, "s": 31133, "text": "jQuery | change() with Examples" }, { "code": null, "e": 31205, "s": 31165, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31238, "s": 31205, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31283, "s": 31238, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31326, "s": 31283, "text": "How to fetch data from an API in ReactJS ?" } ]