title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
MATLAB Annotation
15 Dec, 2021 Annotations in MATLAB is a way of adding explanation or notes to the plots. Annotations add more information to the plots. There are different syntax formations for adding annotations to a plot: annotation(lineType,x,y) annotation(lineType) annotation(shapeType,dim) annotation(shapeType) annotation(___,Name,Value) Let’s discuss all the above functions in detail: Creates a line or arrow annotation between two points in the current figure. lineType takes different values as ‘line’, ‘arrow’, ‘doublearrow’, or ‘textarrow’. x and y are two-element vectors of the form [x_begin x_end] and [y_begin y_end], respectively. Annotation has starting point as (x_begin,y_begin) and ending point as (x_end,y_end). Example : Draw a plot y = x using plot(1:10). Specify x and y values i.e starting point as (0.4, 0.8) and ending point as (0.6. 0.6). Specify lineType as ‘arrow’ with x and y as two-element vectors. Matlab % Plots y = x line from 1 to 10plot(1:10) x = [0.4 0.6];y = [0.8 0.6]; % annotation with lineType 'arrow'annotation('arrow',x,y) Output : Creates an annotation of specified “lineType” with default position starting from (0.3, 0.3) and ending at (0.4, 0.4). Example : Draw a plot y = -x. Specify lineType as ‘arrow’. Matlab % Plot y = -x from 1 to 10x = [1:10]y = -xplot(x,y) % annotation of lineType 'arrow'% at default positionsannotation('arrow') Output : Creates an annotation in the shape of a rectangle or eclipse with given dim to the plot. ShapeType takes values as ‘rectangle’, ‘ellipse’, or ‘textbox‘. dim is a vector of size 4 as [x y w h], where (x, y) is the lower-left endpoint of rectangle and w, h are width and height of rectangle respectively. Example : Plot the graph y=x^2 from 0 to 10. Specify dim as the lower-left endpoint (0.2, 0.3) with width and height as 0.3 and 0.3 respectively. Specify annotation of shape textbox by including a string in the textbox. Matlab % Plot y = x^2 from 0 to 10x = [0:10]y = x.*xplot(x,y) % Dimensions of textboxdim = [0.2 0.3 0.3 0.3]str = 'Parabola y = x^2'; % Annotation of shapeType 'textbox'% at "dim" with "str"% content inside the textboxannotation('textbox',dim,'String',str); Output : Creates the annotation with the mentioned shape in the default position so that the lower-left endpoint is at (0.3, 0.3) and the width and height are both 0.1. Example : Plot the graph y = x^2. Create an annotation of shapeType = ‘rectangle’ with default positions of the rectangle. Matlab % Plot y = ^2 from 0 to 10x = [0:10]y = x.*xplot(x,y) % Annotation with shapeType='rectangle'% with default positions% of rectangleannotation('rectangle'); Output : Creates an annotation by specifying properties as Name-Value pair arguments. Some of the properties are like String, color, FaceColor, FaceAlpha etc. Example : Plot the graph y = x^3-12x. Specified the eclipse annotation with color as ‘red’ and interior color as ‘green’ and FaceAlpha = 0.3. specifies FaceColor is slightly transparent. Matlab % Plot y = x^3 - 12x from -5 to +5x = linspace(-5,5);y = x.^3 - 12*x;plot(x,y) % Dimensions of eclipsedim = [.3 .50 .25 .15]; % eclipse takes dimensions as it'll% fit into specified% rectangle dimension% Annotation with color , FaceColoe and% FaceALpha of eclipseannotation('ellipse',dim,'color','red','FaceColor','green','FaceAlpha',.3) Output : surindertarika1234 MATLAB-graphs Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Dec, 2021" }, { "code": null, "e": 223, "s": 28, "text": "Annotations in MATLAB is a way of adding explanation or notes to the plots. Annotations add more information to the plots. There are different syntax formations for adding annotations to a plot:" }, { "code": null, "e": 248, "s": 223, "text": "annotation(lineType,x,y)" }, { "code": null, "e": 269, "s": 248, "text": "annotation(lineType)" }, { "code": null, "e": 295, "s": 269, "text": "annotation(shapeType,dim)" }, { "code": null, "e": 317, "s": 295, "text": "annotation(shapeType)" }, { "code": null, "e": 344, "s": 317, "text": "annotation(___,Name,Value)" }, { "code": null, "e": 393, "s": 344, "text": "Let’s discuss all the above functions in detail:" }, { "code": null, "e": 470, "s": 393, "text": "Creates a line or arrow annotation between two points in the current figure." }, { "code": null, "e": 553, "s": 470, "text": "lineType takes different values as ‘line’, ‘arrow’, ‘doublearrow’, or ‘textarrow’." }, { "code": null, "e": 648, "s": 553, "text": "x and y are two-element vectors of the form [x_begin x_end] and [y_begin y_end], respectively." }, { "code": null, "e": 734, "s": 648, "text": "Annotation has starting point as (x_begin,y_begin) and ending point as (x_end,y_end)." }, { "code": null, "e": 744, "s": 734, "text": "Example :" }, { "code": null, "e": 780, "s": 744, "text": "Draw a plot y = x using plot(1:10)." }, { "code": null, "e": 868, "s": 780, "text": "Specify x and y values i.e starting point as (0.4, 0.8) and ending point as (0.6. 0.6)." }, { "code": null, "e": 933, "s": 868, "text": "Specify lineType as ‘arrow’ with x and y as two-element vectors." }, { "code": null, "e": 940, "s": 933, "text": "Matlab" }, { "code": "% Plots y = x line from 1 to 10plot(1:10) x = [0.4 0.6];y = [0.8 0.6]; % annotation with lineType 'arrow'annotation('arrow',x,y)", "e": 1069, "s": 940, "text": null }, { "code": null, "e": 1079, "s": 1069, "text": "Output : " }, { "code": null, "e": 1198, "s": 1079, "text": "Creates an annotation of specified “lineType” with default position starting from (0.3, 0.3) and ending at (0.4, 0.4)." }, { "code": null, "e": 1209, "s": 1198, "text": "Example : " }, { "code": null, "e": 1229, "s": 1209, "text": "Draw a plot y = -x." }, { "code": null, "e": 1258, "s": 1229, "text": "Specify lineType as ‘arrow’." }, { "code": null, "e": 1265, "s": 1258, "text": "Matlab" }, { "code": "% Plot y = -x from 1 to 10x = [1:10]y = -xplot(x,y) % annotation of lineType 'arrow'% at default positionsannotation('arrow')", "e": 1391, "s": 1265, "text": null }, { "code": null, "e": 1401, "s": 1391, "text": "Output : " }, { "code": null, "e": 1490, "s": 1401, "text": "Creates an annotation in the shape of a rectangle or eclipse with given dim to the plot." }, { "code": null, "e": 1554, "s": 1490, "text": "ShapeType takes values as ‘rectangle’, ‘ellipse’, or ‘textbox‘." }, { "code": null, "e": 1704, "s": 1554, "text": "dim is a vector of size 4 as [x y w h], where (x, y) is the lower-left endpoint of rectangle and w, h are width and height of rectangle respectively." }, { "code": null, "e": 1715, "s": 1704, "text": "Example : " }, { "code": null, "e": 1750, "s": 1715, "text": "Plot the graph y=x^2 from 0 to 10." }, { "code": null, "e": 1851, "s": 1750, "text": "Specify dim as the lower-left endpoint (0.2, 0.3) with width and height as 0.3 and 0.3 respectively." }, { "code": null, "e": 1925, "s": 1851, "text": "Specify annotation of shape textbox by including a string in the textbox." }, { "code": null, "e": 1932, "s": 1925, "text": "Matlab" }, { "code": "% Plot y = x^2 from 0 to 10x = [0:10]y = x.*xplot(x,y) % Dimensions of textboxdim = [0.2 0.3 0.3 0.3]str = 'Parabola y = x^2'; % Annotation of shapeType 'textbox'% at \"dim\" with \"str\"% content inside the textboxannotation('textbox',dim,'String',str);", "e": 2183, "s": 1932, "text": null }, { "code": null, "e": 2193, "s": 2183, "text": "Output : " }, { "code": null, "e": 2353, "s": 2193, "text": "Creates the annotation with the mentioned shape in the default position so that the lower-left endpoint is at (0.3, 0.3) and the width and height are both 0.1." }, { "code": null, "e": 2364, "s": 2353, "text": "Example : " }, { "code": null, "e": 2388, "s": 2364, "text": "Plot the graph y = x^2." }, { "code": null, "e": 2477, "s": 2388, "text": "Create an annotation of shapeType = ‘rectangle’ with default positions of the rectangle." }, { "code": null, "e": 2484, "s": 2477, "text": "Matlab" }, { "code": "% Plot y = ^2 from 0 to 10x = [0:10]y = x.*xplot(x,y) % Annotation with shapeType='rectangle'% with default positions% of rectangleannotation('rectangle');", "e": 2640, "s": 2484, "text": null }, { "code": null, "e": 2649, "s": 2640, "text": "Output :" }, { "code": null, "e": 2726, "s": 2649, "text": "Creates an annotation by specifying properties as Name-Value pair arguments." }, { "code": null, "e": 2799, "s": 2726, "text": "Some of the properties are like String, color, FaceColor, FaceAlpha etc." }, { "code": null, "e": 2810, "s": 2799, "text": "Example : " }, { "code": null, "e": 2838, "s": 2810, "text": "Plot the graph y = x^3-12x." }, { "code": null, "e": 2987, "s": 2838, "text": "Specified the eclipse annotation with color as ‘red’ and interior color as ‘green’ and FaceAlpha = 0.3. specifies FaceColor is slightly transparent." }, { "code": null, "e": 2994, "s": 2987, "text": "Matlab" }, { "code": "% Plot y = x^3 - 12x from -5 to +5x = linspace(-5,5);y = x.^3 - 12*x;plot(x,y) % Dimensions of eclipsedim = [.3 .50 .25 .15]; % eclipse takes dimensions as it'll% fit into specified% rectangle dimension% Annotation with color , FaceColoe and% FaceALpha of eclipseannotation('ellipse',dim,'color','red','FaceColor','green','FaceAlpha',.3)", "e": 3332, "s": 2994, "text": null }, { "code": null, "e": 3342, "s": 3332, "text": "Output : " }, { "code": null, "e": 3363, "s": 3344, "text": "surindertarika1234" }, { "code": null, "e": 3377, "s": 3363, "text": "MATLAB-graphs" }, { "code": null, "e": 3384, "s": 3377, "text": "Picked" }, { "code": null, "e": 3391, "s": 3384, "text": "MATLAB" } ]
Gaussian Elimination to Solve Linear Equations
14 Jul, 2022 The article focuses on using an algorithm for solving a system of linear equations. We will deal with the matrix of coefficients. Gaussian Elimination does not work on singular matrices (they lead to division by zero). Input: For N unknowns, input is an augmented matrix of size N x (N+1). One extra column is for Right Hand Side (RHS) mat[N][N+1] = {{3.0, 2.0,-4.0, 3.0}, {2.0, 3.0, 3.0, 15.0}, {5.0, -3, 1.0, 14.0} }; Output: Solution to equations is: 3.000000 1.000000 2.000000 Explanation: Given matrix represents following equations 3.0X1 + 2.0X2 - 4.0X3 = 3.0 2.0X1 + 3.0X2 + 3.0X3 = 15.0 5.0X1 - 3.0X2 + X3 = 14.0 There is a unique solution for given equations, solutions is, X1 = 3.0, X2 = 1.0, X3 = 2.0, Row echelon form: Matrix is said to be in r.e.f. if the following conditions hold: The first non-zero element in each row, called the leading coefficient, is 1.Each leading coefficient is in a column to the right of the previous row leading coefficient.Rows with all zeros are below rows with at least one non-zero element. The first non-zero element in each row, called the leading coefficient, is 1. Each leading coefficient is in a column to the right of the previous row leading coefficient. Rows with all zeros are below rows with at least one non-zero element. Reduced row echelon form: Matrix is said to be in r.r.e.f. if the following conditions hold – All the conditions for r.e.f.The leading coefficient in each row is the only non-zero entry in its column. All the conditions for r.e.f. The leading coefficient in each row is the only non-zero entry in its column. The algorithm is majorly about performing a sequence of operations on the rows of the matrix. What we would like to keep in mind while performing these operations is that we want to convert the matrix into an upper triangular matrix in row echelon form. The operations can be: Swapping two rowsMultiplying a row by a non-zero scalarAdding to one row a multiple of another Swapping two rows Multiplying a row by a non-zero scalar Adding to one row a multiple of another The process: Forward elimination: reduction to row echelon form. Using it one can tell whether there are no solutions, or unique solution, or infinitely many solutions.Back substitution: further reduction to reduced row echelon form. Forward elimination: reduction to row echelon form. Using it one can tell whether there are no solutions, or unique solution, or infinitely many solutions. Back substitution: further reduction to reduced row echelon form. Algorithm: Partial pivoting: Find the kth pivot by swapping rows, to move the entry with the largest absolute value to the pivot position. This imparts computational stability to the algorithm.For each row below the pivot, calculate the factor f which makes the kth entry zero, and for every element in the row subtract the fth multiple of the corresponding element in the kth row.Repeat above steps for each unknown. We will be left with a partial r.e.f. matrix. Partial pivoting: Find the kth pivot by swapping rows, to move the entry with the largest absolute value to the pivot position. This imparts computational stability to the algorithm. For each row below the pivot, calculate the factor f which makes the kth entry zero, and for every element in the row subtract the fth multiple of the corresponding element in the kth row. Repeat above steps for each unknown. We will be left with a partial r.e.f. matrix. Below is the implementation of above algorithm. C++ Java Python3 C# PHP Javascript // C++ program to demonstrate working of Gaussian Elimination// method#include<bits/stdc++.h>using namespace std; #define N 3 // Number of unknowns // function to reduce matrix to r.e.f. Returns a value to// indicate whether matrix is singular or notint forwardElim(double mat[N][N+1]); // function to calculate the values of the unknownsvoid backSub(double mat[N][N+1]); // function to get matrix contentvoid gaussianElimination(double mat[N][N+1]){ /* reduction into r.e.f. */ int singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { printf("Singular Matrix.\n"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag][N]) printf("Inconsistent System."); else printf("May have infinitely many " "solutions."); return; } /* get solution to system and print it using backward substitution */ backSub(mat);} // function for elementary operation of swapping two rowsvoid swap_row(double mat[N][N+1], int i, int j){ //printf("Swapped rows %d and %d\n", i, j); for (int k=0; k<=N; k++) { double temp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = temp; }} // function to print matrix content at any stagevoid print(double mat[N][N+1]){ for (int i=0; i<N; i++, printf("\n")) for (int j=0; j<=N; j++) printf("%lf ", mat[i][j]); printf("\n");} // function to reduce matrix to r.e.f.int forwardElim(double mat[N][N+1]){ for (int k=0; k<N; k++) { // Initialize maximum value and index for pivot int i_max = k; int v_max = mat[i_max][k]; /* find greater amplitude for pivot if any */ for (int i = k+1; i < N; i++) if (abs(mat[i][k]) > v_max) v_max = mat[i][k], i_max = i; /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (!mat[k][i_max]) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for (int i=k+1; i<N; i++) { /* factor f to set current row kth element to 0, * and subsequently remaining kth column to 0 */ double f = mat[i][k]/mat[k][k]; /* subtract fth multiple of corresponding kth row element*/ for (int j=k+1; j<=N; j++) mat[i][j] -= mat[k][j]*f; /* filling lower triangular matrix with zeros*/ mat[i][k] = 0; } //print(mat); //for matrix state } //print(mat); //for matrix state return -1;} // function to calculate the values of the unknownsvoid backSub(double mat[N][N+1]){ double x[N]; // An array to store solution /* Start calculating from last equation up to the first */ for (int i = N-1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i][N]; /* Initialize j to i+1 since matrix is upper triangular*/ for (int j=i+1; j<N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i][j]*x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = x[i]/mat[i][i]; } printf("\nSolution for the system:\n"); for (int i=0; i<N; i++) printf("%lf\n", x[i]);} // Driver programint main(){ /* input matrix */ double mat[N][N+1] = {{3.0, 2.0,-4.0, 3.0}, {2.0, 3.0, 3.0, 15.0}, {5.0, -3, 1.0, 14.0} }; gaussianElimination(mat); return 0;} // Java program to demonstrate working of Gaussian Elimination// methodimport java.io.*;class GFG{ public static int N = 3; // Number of unknowns // function to get matrix content static void gaussianElimination(double mat[][]) { /* reduction into r.e.f. */ int singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { System.out.println("Singular Matrix."); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag][N] != 0) System.out.print("Inconsistent System."); else System.out.print( "May have infinitely many solutions."); return; } /* get solution to system and print it using backward substitution */ backSub(mat); } // function for elementary operation of swapping two // rows static void swap_row(double mat[][], int i, int j) { // printf("Swapped rows %d and %d\n", i, j); for (int k = 0; k <= N; k++) { double temp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = temp; } } // function to print matrix content at any stage static void print(double mat[][]) { for (int i = 0; i < N; i++, System.out.println()) for (int j = 0; j <= N; j++) System.out.print(mat[i][j]); System.out.println(); } // function to reduce matrix to r.e.f. static int forwardElim(double mat[][]) { for (int k = 0; k < N; k++) { // Initialize maximum value and index for pivot int i_max = k; int v_max = (int)mat[i_max][k]; /* find greater amplitude for pivot if any */ for (int i = k + 1; i < N; i++) if (Math.abs(mat[i][k]) > v_max) { v_max = (int)mat[i][k]; i_max = i; } /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (mat[k][i_max] == 0) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for (int i = k + 1; i < N; i++) { /* factor f to set current row kth element * to 0, and subsequently remaining kth * column to 0 */ double f = mat[i][k] / mat[k][k]; /* subtract fth multiple of corresponding kth row element*/ for (int j = k + 1; j <= N; j++) mat[i][j] -= mat[k][j] * f; /* filling lower triangular matrix with * zeros*/ mat[i][k] = 0; } // print(mat); //for matrix state } // print(mat); //for matrix state return -1; } // function to calculate the values of the unknowns static void backSub(double mat[][]) { double x[] = new double[N]; // An array to store solution /* Start calculating from last equation up to the first */ for (int i = N - 1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i][N]; /* Initialize j to i+1 since matrix is upper triangular*/ for (int j = i + 1; j < N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i][j] * x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = x[i] / mat[i][i]; } System.out.println(); System.out.println("Solution for the system:"); for (int i = 0; i < N; i++) { System.out.format("%.6f", x[i]); System.out.println(); } } // Driver program public static void main(String[] args) { /* input matrix */ double mat[][] = { { 3.0, 2.0, -4.0, 3.0 }, { 2.0, 3.0, 3.0, 15.0 }, { 5.0, -3, 1.0, 14.0 } }; gaussianElimination(mat); }} // This code is contributed by Dharanendra L V. # Python3 program to demonstrate working of# Gaussian Elimination methodN = 3 # function to get matrix contentdef gaussianElimination(mat): # reduction into r.e.f. singular_flag = forwardElim(mat) # if matrix is singular if (singular_flag != -1): print("Singular Matrix.") # if the RHS of equation corresponding to # zero row is 0, * system has infinitely # many solutions, else inconsistent*/ if (mat[singular_flag][N]): print("Inconsistent System.") else: print("May have infinitely many solutions.") return # get solution to system and print it using # backward substitution backSub(mat) # function for elementary operation of swapping two rowsdef swap_row(mat, i, j): for k in range(N + 1): temp = mat[i][k] mat[i][k] = mat[j][k] mat[j][k] = temp # function to reduce matrix to r.e.f.def forwardElim(mat): for k in range(N): # Initialize maximum value and index for pivot i_max = k v_max = mat[i_max][k] # find greater amplitude for pivot if any for i in range(k + 1, N): if (abs(mat[i][k]) > v_max): v_max = mat[i][k] i_max = i # if a principal diagonal element is zero, # it denotes that matrix is singular, and # will lead to a division-by-zero later. if not mat[k][i_max]: return k # Matrix is singular # Swap the greatest value row with current row if (i_max != k): swap_row(mat, k, i_max) for i in range(k + 1, N): # factor f to set current row kth element to 0, # and subsequently remaining kth column to 0 */ f = mat[i][k]/mat[k][k] # subtract fth multiple of corresponding kth # row element*/ for j in range(k + 1, N + 1): mat[i][j] -= mat[k][j]*f # filling lower triangular matrix with zeros*/ mat[i][k] = 0 # print(mat); //for matrix state # print(mat); //for matrix state return -1 # function to calculate the values of the unknownsdef backSub(mat): x = [None for _ in range(N)] # An array to store solution # Start calculating from last equation up to the # first */ for i in range(N-1, -1, -1): # start with the RHS of the equation */ x[i] = mat[i][N] # Initialize j to i+1 since matrix is upper # triangular*/ for j in range(i + 1, N): # subtract all the lhs values # except the coefficient of the variable # whose value is being calculated */ x[i] -= mat[i][j]*x[j] # divide the RHS by the coefficient of the # unknown being calculated x[i] = (x[i]/mat[i][i]) print("\nSolution for the system:") for i in range(N): print("{:.8f}".format(x[i])) # Driver program # input matrixmat = [[3.0, 2.0, -4.0, 3.0], [2.0, 3.0, 3.0, 15.0], [5.0, -3, 1.0, 14.0]]gaussianElimination(mat) # This code is contributed by phasing17 // C# program to demonstrate working// of Gaussian Elimination methodusing System; class GFG{ // Number of unknownspublic static int N = 3; // Function to get matrix contentstatic void gaussianElimination(double [,]mat){ /* reduction into r.e.f. */ int singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { Console.WriteLine("Singular Matrix."); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag,N] != 0) Console.Write("Inconsistent System."); else Console.Write("May have infinitely " + "many solutions."); return; } /* get solution to system and print it using backward substitution */ backSub(mat);} // Function for elementary operation of swapping two// rowsstatic void swap_row(double [,]mat, int i, int j){ // printf("Swapped rows %d and %d\n", i, j); for(int k = 0; k <= N; k++) { double temp = mat[i, k]; mat[i, k] = mat[j, k]; mat[j, k] = temp; }} // Function to print matrix content at any stagestatic void print(double [,]mat){ for(int i = 0; i < N; i++, Console.WriteLine()) for(int j = 0; j <= N; j++) Console.Write(mat[i, j]); Console.WriteLine();} // Function to reduce matrix to r.e.f.static int forwardElim(double [,]mat){ for(int k = 0; k < N; k++) { // Initialize maximum value and index for pivot int i_max = k; int v_max = (int)mat[i_max, k]; /* find greater amplitude for pivot if any */ for(int i = k + 1; i < N; i++) { if (Math.Abs(mat[i, k]) > v_max) { v_max = (int)mat[i, k]; i_max = i; } /* If a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (mat[k, i_max] == 0) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for(int i = k + 1; i < N; i++) { /* factor f to set current row kth element * to 0, and subsequently remaining kth * column to 0 */ double f = mat[i, k] / mat[k, k]; /* subtract fth multiple of corresponding kth row element*/ for(int j = k + 1; j <= N; j++) mat[i, j] -= mat[k, j] * f; /* filling lower triangular matrix with * zeros*/ mat[i, k] = 0; } } // print(mat); //for matrix state } // print(mat); //for matrix state return -1;} // Function to calculate the values of the unknownsstatic void backSub(double [,]mat){ // An array to store solution double []x = new double[N]; /* Start calculating from last equation up to the first */ for(int i = N - 1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i,N]; /* Initialize j to i+1 since matrix is upper triangular*/ for(int j = i + 1; j < N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i,j] * x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = x[i] / mat[i,i]; } Console.WriteLine(); Console.WriteLine("Solution for the system:"); for(int i = 0; i < N; i++) { Console.Write("{0:F6}", x[i]); Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ /* input matrix */ double [,]mat = { { 3.0, 2.0, -4.0, 3.0 }, { 2.0, 3.0, 3.0, 15.0 }, { 5.0, -3, 1.0, 14.0 } }; gaussianElimination(mat);}} // This code is contributed by shikhasingrajput <?php// PHP program to demonstrate working// of Gaussian Elimination method $N = 3; // Number of unknowns // function to get matrix contentfunction gaussianElimination($mat){ global $N; /* reduction into r.e.f. */ $singular_flag = forwardElim($mat); /* if matrix is singular */ if ($singular_flag != -1) { print("Singular Matrix.\n"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if ($mat[$singular_flag][$N]) print("Inconsistent System."); else print("May have infinitely many solutions."); return; } /* get solution to system and print it using backward substitution */ backSub($mat);} // function for elementary operation// of swapping two rowsfunction swap_row(&$mat, $i, $j){ global $N; //printf("Swapped rows %d and %d\n", i, j); for ($k = 0; $k <= $N; $k++) { $temp = $mat[$i][$k]; $mat[$i][$k] = $mat[$j][$k]; $mat[$j][$k] = $temp; }} // function to print matrix content at any stagefunction print1($mat){ global $N; for ($i=0; $i<$N; $i++, print("\n")) for ($j=0; $j<=$N; $j++) print($mat[$i][$j]); print("\n");} // function to reduce matrix to r.e.f.function forwardElim(&$mat){ global $N; for ($k=0; $k<$N; $k++) { // Initialize maximum value and index for pivot $i_max = $k; $v_max = $mat[$i_max][$k]; /* find greater amplitude for pivot if any */ for ($i = $k+1; $i < $N; $i++) if (abs($mat[$i][$k]) > $v_max) { $v_max = $mat[$i][$k]; $i_max = $i; } /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (!$mat[$k][$i_max]) return $k; // Matrix is singular /* Swap the greatest value row with current row */ if ($i_max != $k) swap_row($mat, $k, $i_max); for ($i = $k + 1; $i < $N; $i++) { /* factor f to set current row kth element to 0, * and subsequently remaining kth column to 0 */ $f = $mat[$i][$k]/$mat[$k][$k]; /* subtract fth multiple of corresponding kth row element*/ for ($j = $k + 1; $j <= $N; $j++) $mat[$i][$j] -= $mat[$k][$j] * $f; /* filling lower triangular matrix with zeros*/ $mat[$i][$k] = 0; } //print(mat); //for matrix state } //print(mat); //for matrix state return -1;} // function to calculate the values of the unknownsfunction backSub(&$mat){ global $N; $x = array_fill(0, $N, 0); // An array to store solution /* Start calculating from last equation up to the first */ for ($i = $N - 1; $i >= 0; $i--) { /* start with the RHS of the equation */ $x[$i] = $mat[$i][$N]; /* Initialize j to i+1 since matrix is upper triangular*/ for ($j = $i + 1; $j < $N; $j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ $x[$i] -= $mat[$i][$j] * $x[$j]; } /* divide the RHS by the coefficient of the unknown being calculated */ $x[$i] = $x[$i] / $mat[$i][$i]; } print("\nSolution for the system:\n"); for ($i = 0; $i < $N; $i++) print(number_format(strval($x[$i]), 6)."\n");} // Driver program /* input matrix */ $mat = array(array(3.0, 2.0,-4.0, 3.0), array(2.0, 3.0, 3.0, 15.0), array(5.0, -3, 1.0, 14.0)); gaussianElimination($mat); // This code is contributed by mits?> // JavaScript program to demonstrate working of Gaussian Elimination// method let N = 3; // function to get matrix contentfunction gaussianElimination(mat){ /* reduction into r.e.f. */ let singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { console.log("Singular Matrix."); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag][N]) console.log("Inconsistent System."); else console.log("May have infinitely many solutions."); return; } /* get solution to system and print it using backward substitution */ backSub(mat);} // function for elementary operation of swapping two rowsfunction swap_row(mat, i, j){ //printf("Swapped rows %d and %d\n", i, j); for (var k=0; k<=N; k++) { let temp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = temp; }} // function to print matrix content at any stagefunction print(mat){ for (var i=0; i<N; i++, console.log("")) for (var j=0; j<=N; j++) process.stdout.write("" + mat[i][j]); console.log("");} // function to reduce matrix to r.e.f.function forwardElim(mat){ for (var k=0; k<N; k++) { // Initialize maximum value and index for pivot var i_max = k; var v_max = mat[i_max][k]; /* find greater amplitude for pivot if any */ for (var i = k+1; i < N; i++) if (Math.abs(mat[i][k]) > v_max) v_max = mat[i][k], i_max = i; /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (!mat[k][i_max]) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for (var i=k+1; i<N; i++) { /* factor f to set current row kth element to 0, * and subsequently remaining kth column to 0 */ let f = mat[i][k]/mat[k][k]; /* subtract fth multiple of corresponding kth row element*/ for (var j=k+1; j<=N; j++) mat[i][j] -= mat[k][j]*f; /* filling lower triangular matrix with zeros*/ mat[i][k] = 0; } //print(mat); //for matrix state } //print(mat); //for matrix state return -1;} // function to calculate the values of the unknownsfunction backSub(mat){ let x = new Array(N); // An array to store solution /* Start calculating from last equation up to the first */ for (var i = N-1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i][N]; /* Initialize j to i+1 since matrix is upper triangular*/ for (var j=i+1; j<N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i][j]*x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = Math.round(x[i]/mat[i][i]); } console.log("\nSolution for the system:"); for (var i=0; i<N; i++) console.log(x[i].toFixed(8));} // Driver program /* input matrix */let mat = [[3.0, 2.0,-4.0, 3.0], [2.0, 3.0, 3.0, 15.0], [5.0, -3, 1.0, 14.0]]; gaussianElimination(mat); // This code is contributed by phasing17 Output: Solution for the system: 3.000000 1.000000 2.000000 Illustration: Time Complexity: Since for each pivot we traverse the part to its right for each row below it, O(n)*(O(n)*O(n)) = O(n3).We can also apply Gaussian Elimination for calculating: Rank of a matrixDeterminant of a matrixInverse of an invertible square matrix Rank of a matrix Determinant of a matrix Inverse of an invertible square matrix This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar Akanksha_Rai nidhi_biet dharanendralv23 shikhasingrajput simmytarika5 phasing17 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jul, 2022" }, { "code": null, "e": 271, "s": 52, "text": "The article focuses on using an algorithm for solving a system of linear equations. We will deal with the matrix of coefficients. Gaussian Elimination does not work on singular matrices (they lead to division by zero)." }, { "code": null, "e": 862, "s": 271, "text": "Input: For N unknowns, input is an augmented \n matrix of size N x (N+1). One extra \n column is for Right Hand Side (RHS)\n mat[N][N+1] = {{3.0, 2.0,-4.0, 3.0},\n {2.0, 3.0, 3.0, 15.0},\n {5.0, -3, 1.0, 14.0}\n };\nOutput: Solution to equations is:\n 3.000000\n 1.000000\n 2.000000\n\nExplanation:\nGiven matrix represents following equations\n3.0X1 + 2.0X2 - 4.0X3 = 3.0\n2.0X1 + 3.0X2 + 3.0X3 = 15.0\n5.0X1 - 3.0X2 + X3 = 14.0\n\nThere is a unique solution for given equations, \nsolutions is, X1 = 3.0, X2 = 1.0, X3 = 2.0, " }, { "code": null, "e": 948, "s": 864, "text": "Row echelon form: Matrix is said to be in r.e.f. if the following conditions hold: " }, { "code": null, "e": 1189, "s": 948, "text": "The first non-zero element in each row, called the leading coefficient, is 1.Each leading coefficient is in a column to the right of the previous row leading coefficient.Rows with all zeros are below rows with at least one non-zero element." }, { "code": null, "e": 1267, "s": 1189, "text": "The first non-zero element in each row, called the leading coefficient, is 1." }, { "code": null, "e": 1361, "s": 1267, "text": "Each leading coefficient is in a column to the right of the previous row leading coefficient." }, { "code": null, "e": 1432, "s": 1361, "text": "Rows with all zeros are below rows with at least one non-zero element." }, { "code": null, "e": 1529, "s": 1434, "text": "Reduced row echelon form: Matrix is said to be in r.r.e.f. if the following conditions hold – " }, { "code": null, "e": 1636, "s": 1529, "text": "All the conditions for r.e.f.The leading coefficient in each row is the only non-zero entry in its column." }, { "code": null, "e": 1666, "s": 1636, "text": "All the conditions for r.e.f." }, { "code": null, "e": 1744, "s": 1666, "text": "The leading coefficient in each row is the only non-zero entry in its column." }, { "code": null, "e": 2022, "s": 1744, "text": "The algorithm is majorly about performing a sequence of operations on the rows of the matrix. What we would like to keep in mind while performing these operations is that we want to convert the matrix into an upper triangular matrix in row echelon form. The operations can be: " }, { "code": null, "e": 2117, "s": 2022, "text": "Swapping two rowsMultiplying a row by a non-zero scalarAdding to one row a multiple of another" }, { "code": null, "e": 2135, "s": 2117, "text": "Swapping two rows" }, { "code": null, "e": 2174, "s": 2135, "text": "Multiplying a row by a non-zero scalar" }, { "code": null, "e": 2214, "s": 2174, "text": "Adding to one row a multiple of another" }, { "code": null, "e": 2229, "s": 2214, "text": "The process: " }, { "code": null, "e": 2450, "s": 2229, "text": "Forward elimination: reduction to row echelon form. Using it one can tell whether there are no solutions, or unique solution, or infinitely many solutions.Back substitution: further reduction to reduced row echelon form." }, { "code": null, "e": 2606, "s": 2450, "text": "Forward elimination: reduction to row echelon form. Using it one can tell whether there are no solutions, or unique solution, or infinitely many solutions." }, { "code": null, "e": 2672, "s": 2606, "text": "Back substitution: further reduction to reduced row echelon form." }, { "code": null, "e": 2685, "s": 2672, "text": "Algorithm: " }, { "code": null, "e": 3138, "s": 2685, "text": "Partial pivoting: Find the kth pivot by swapping rows, to move the entry with the largest absolute value to the pivot position. This imparts computational stability to the algorithm.For each row below the pivot, calculate the factor f which makes the kth entry zero, and for every element in the row subtract the fth multiple of the corresponding element in the kth row.Repeat above steps for each unknown. We will be left with a partial r.e.f. matrix." }, { "code": null, "e": 3321, "s": 3138, "text": "Partial pivoting: Find the kth pivot by swapping rows, to move the entry with the largest absolute value to the pivot position. This imparts computational stability to the algorithm." }, { "code": null, "e": 3510, "s": 3321, "text": "For each row below the pivot, calculate the factor f which makes the kth entry zero, and for every element in the row subtract the fth multiple of the corresponding element in the kth row." }, { "code": null, "e": 3593, "s": 3510, "text": "Repeat above steps for each unknown. We will be left with a partial r.e.f. matrix." }, { "code": null, "e": 3643, "s": 3593, "text": "Below is the implementation of above algorithm. " }, { "code": null, "e": 3647, "s": 3643, "text": "C++" }, { "code": null, "e": 3652, "s": 3647, "text": "Java" }, { "code": null, "e": 3660, "s": 3652, "text": "Python3" }, { "code": null, "e": 3663, "s": 3660, "text": "C#" }, { "code": null, "e": 3667, "s": 3663, "text": "PHP" }, { "code": null, "e": 3678, "s": 3667, "text": "Javascript" }, { "code": "// C++ program to demonstrate working of Gaussian Elimination// method#include<bits/stdc++.h>using namespace std; #define N 3 // Number of unknowns // function to reduce matrix to r.e.f. Returns a value to// indicate whether matrix is singular or notint forwardElim(double mat[N][N+1]); // function to calculate the values of the unknownsvoid backSub(double mat[N][N+1]); // function to get matrix contentvoid gaussianElimination(double mat[N][N+1]){ /* reduction into r.e.f. */ int singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { printf(\"Singular Matrix.\\n\"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag][N]) printf(\"Inconsistent System.\"); else printf(\"May have infinitely many \" \"solutions.\"); return; } /* get solution to system and print it using backward substitution */ backSub(mat);} // function for elementary operation of swapping two rowsvoid swap_row(double mat[N][N+1], int i, int j){ //printf(\"Swapped rows %d and %d\\n\", i, j); for (int k=0; k<=N; k++) { double temp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = temp; }} // function to print matrix content at any stagevoid print(double mat[N][N+1]){ for (int i=0; i<N; i++, printf(\"\\n\")) for (int j=0; j<=N; j++) printf(\"%lf \", mat[i][j]); printf(\"\\n\");} // function to reduce matrix to r.e.f.int forwardElim(double mat[N][N+1]){ for (int k=0; k<N; k++) { // Initialize maximum value and index for pivot int i_max = k; int v_max = mat[i_max][k]; /* find greater amplitude for pivot if any */ for (int i = k+1; i < N; i++) if (abs(mat[i][k]) > v_max) v_max = mat[i][k], i_max = i; /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (!mat[k][i_max]) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for (int i=k+1; i<N; i++) { /* factor f to set current row kth element to 0, * and subsequently remaining kth column to 0 */ double f = mat[i][k]/mat[k][k]; /* subtract fth multiple of corresponding kth row element*/ for (int j=k+1; j<=N; j++) mat[i][j] -= mat[k][j]*f; /* filling lower triangular matrix with zeros*/ mat[i][k] = 0; } //print(mat); //for matrix state } //print(mat); //for matrix state return -1;} // function to calculate the values of the unknownsvoid backSub(double mat[N][N+1]){ double x[N]; // An array to store solution /* Start calculating from last equation up to the first */ for (int i = N-1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i][N]; /* Initialize j to i+1 since matrix is upper triangular*/ for (int j=i+1; j<N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i][j]*x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = x[i]/mat[i][i]; } printf(\"\\nSolution for the system:\\n\"); for (int i=0; i<N; i++) printf(\"%lf\\n\", x[i]);} // Driver programint main(){ /* input matrix */ double mat[N][N+1] = {{3.0, 2.0,-4.0, 3.0}, {2.0, 3.0, 3.0, 15.0}, {5.0, -3, 1.0, 14.0} }; gaussianElimination(mat); return 0;}", "e": 7663, "s": 3678, "text": null }, { "code": "// Java program to demonstrate working of Gaussian Elimination// methodimport java.io.*;class GFG{ public static int N = 3; // Number of unknowns // function to get matrix content static void gaussianElimination(double mat[][]) { /* reduction into r.e.f. */ int singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { System.out.println(\"Singular Matrix.\"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag][N] != 0) System.out.print(\"Inconsistent System.\"); else System.out.print( \"May have infinitely many solutions.\"); return; } /* get solution to system and print it using backward substitution */ backSub(mat); } // function for elementary operation of swapping two // rows static void swap_row(double mat[][], int i, int j) { // printf(\"Swapped rows %d and %d\\n\", i, j); for (int k = 0; k <= N; k++) { double temp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = temp; } } // function to print matrix content at any stage static void print(double mat[][]) { for (int i = 0; i < N; i++, System.out.println()) for (int j = 0; j <= N; j++) System.out.print(mat[i][j]); System.out.println(); } // function to reduce matrix to r.e.f. static int forwardElim(double mat[][]) { for (int k = 0; k < N; k++) { // Initialize maximum value and index for pivot int i_max = k; int v_max = (int)mat[i_max][k]; /* find greater amplitude for pivot if any */ for (int i = k + 1; i < N; i++) if (Math.abs(mat[i][k]) > v_max) { v_max = (int)mat[i][k]; i_max = i; } /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (mat[k][i_max] == 0) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for (int i = k + 1; i < N; i++) { /* factor f to set current row kth element * to 0, and subsequently remaining kth * column to 0 */ double f = mat[i][k] / mat[k][k]; /* subtract fth multiple of corresponding kth row element*/ for (int j = k + 1; j <= N; j++) mat[i][j] -= mat[k][j] * f; /* filling lower triangular matrix with * zeros*/ mat[i][k] = 0; } // print(mat); //for matrix state } // print(mat); //for matrix state return -1; } // function to calculate the values of the unknowns static void backSub(double mat[][]) { double x[] = new double[N]; // An array to store solution /* Start calculating from last equation up to the first */ for (int i = N - 1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i][N]; /* Initialize j to i+1 since matrix is upper triangular*/ for (int j = i + 1; j < N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i][j] * x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = x[i] / mat[i][i]; } System.out.println(); System.out.println(\"Solution for the system:\"); for (int i = 0; i < N; i++) { System.out.format(\"%.6f\", x[i]); System.out.println(); } } // Driver program public static void main(String[] args) { /* input matrix */ double mat[][] = { { 3.0, 2.0, -4.0, 3.0 }, { 2.0, 3.0, 3.0, 15.0 }, { 5.0, -3, 1.0, 14.0 } }; gaussianElimination(mat); }} // This code is contributed by Dharanendra L V.", "e": 11727, "s": 7663, "text": null }, { "code": "# Python3 program to demonstrate working of# Gaussian Elimination methodN = 3 # function to get matrix contentdef gaussianElimination(mat): # reduction into r.e.f. singular_flag = forwardElim(mat) # if matrix is singular if (singular_flag != -1): print(\"Singular Matrix.\") # if the RHS of equation corresponding to # zero row is 0, * system has infinitely # many solutions, else inconsistent*/ if (mat[singular_flag][N]): print(\"Inconsistent System.\") else: print(\"May have infinitely many solutions.\") return # get solution to system and print it using # backward substitution backSub(mat) # function for elementary operation of swapping two rowsdef swap_row(mat, i, j): for k in range(N + 1): temp = mat[i][k] mat[i][k] = mat[j][k] mat[j][k] = temp # function to reduce matrix to r.e.f.def forwardElim(mat): for k in range(N): # Initialize maximum value and index for pivot i_max = k v_max = mat[i_max][k] # find greater amplitude for pivot if any for i in range(k + 1, N): if (abs(mat[i][k]) > v_max): v_max = mat[i][k] i_max = i # if a principal diagonal element is zero, # it denotes that matrix is singular, and # will lead to a division-by-zero later. if not mat[k][i_max]: return k # Matrix is singular # Swap the greatest value row with current row if (i_max != k): swap_row(mat, k, i_max) for i in range(k + 1, N): # factor f to set current row kth element to 0, # and subsequently remaining kth column to 0 */ f = mat[i][k]/mat[k][k] # subtract fth multiple of corresponding kth # row element*/ for j in range(k + 1, N + 1): mat[i][j] -= mat[k][j]*f # filling lower triangular matrix with zeros*/ mat[i][k] = 0 # print(mat); //for matrix state # print(mat); //for matrix state return -1 # function to calculate the values of the unknownsdef backSub(mat): x = [None for _ in range(N)] # An array to store solution # Start calculating from last equation up to the # first */ for i in range(N-1, -1, -1): # start with the RHS of the equation */ x[i] = mat[i][N] # Initialize j to i+1 since matrix is upper # triangular*/ for j in range(i + 1, N): # subtract all the lhs values # except the coefficient of the variable # whose value is being calculated */ x[i] -= mat[i][j]*x[j] # divide the RHS by the coefficient of the # unknown being calculated x[i] = (x[i]/mat[i][i]) print(\"\\nSolution for the system:\") for i in range(N): print(\"{:.8f}\".format(x[i])) # Driver program # input matrixmat = [[3.0, 2.0, -4.0, 3.0], [2.0, 3.0, 3.0, 15.0], [5.0, -3, 1.0, 14.0]]gaussianElimination(mat) # This code is contributed by phasing17", "e": 14844, "s": 11727, "text": null }, { "code": "// C# program to demonstrate working// of Gaussian Elimination methodusing System; class GFG{ // Number of unknownspublic static int N = 3; // Function to get matrix contentstatic void gaussianElimination(double [,]mat){ /* reduction into r.e.f. */ int singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { Console.WriteLine(\"Singular Matrix.\"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag,N] != 0) Console.Write(\"Inconsistent System.\"); else Console.Write(\"May have infinitely \" + \"many solutions.\"); return; } /* get solution to system and print it using backward substitution */ backSub(mat);} // Function for elementary operation of swapping two// rowsstatic void swap_row(double [,]mat, int i, int j){ // printf(\"Swapped rows %d and %d\\n\", i, j); for(int k = 0; k <= N; k++) { double temp = mat[i, k]; mat[i, k] = mat[j, k]; mat[j, k] = temp; }} // Function to print matrix content at any stagestatic void print(double [,]mat){ for(int i = 0; i < N; i++, Console.WriteLine()) for(int j = 0; j <= N; j++) Console.Write(mat[i, j]); Console.WriteLine();} // Function to reduce matrix to r.e.f.static int forwardElim(double [,]mat){ for(int k = 0; k < N; k++) { // Initialize maximum value and index for pivot int i_max = k; int v_max = (int)mat[i_max, k]; /* find greater amplitude for pivot if any */ for(int i = k + 1; i < N; i++) { if (Math.Abs(mat[i, k]) > v_max) { v_max = (int)mat[i, k]; i_max = i; } /* If a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (mat[k, i_max] == 0) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for(int i = k + 1; i < N; i++) { /* factor f to set current row kth element * to 0, and subsequently remaining kth * column to 0 */ double f = mat[i, k] / mat[k, k]; /* subtract fth multiple of corresponding kth row element*/ for(int j = k + 1; j <= N; j++) mat[i, j] -= mat[k, j] * f; /* filling lower triangular matrix with * zeros*/ mat[i, k] = 0; } } // print(mat); //for matrix state } // print(mat); //for matrix state return -1;} // Function to calculate the values of the unknownsstatic void backSub(double [,]mat){ // An array to store solution double []x = new double[N]; /* Start calculating from last equation up to the first */ for(int i = N - 1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i,N]; /* Initialize j to i+1 since matrix is upper triangular*/ for(int j = i + 1; j < N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i,j] * x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = x[i] / mat[i,i]; } Console.WriteLine(); Console.WriteLine(\"Solution for the system:\"); for(int i = 0; i < N; i++) { Console.Write(\"{0:F6}\", x[i]); Console.WriteLine(); }} // Driver codepublic static void Main(String[] args){ /* input matrix */ double [,]mat = { { 3.0, 2.0, -4.0, 3.0 }, { 2.0, 3.0, 3.0, 15.0 }, { 5.0, -3, 1.0, 14.0 } }; gaussianElimination(mat);}} // This code is contributed by shikhasingrajput", "e": 19228, "s": 14844, "text": null }, { "code": "<?php// PHP program to demonstrate working// of Gaussian Elimination method $N = 3; // Number of unknowns // function to get matrix contentfunction gaussianElimination($mat){ global $N; /* reduction into r.e.f. */ $singular_flag = forwardElim($mat); /* if matrix is singular */ if ($singular_flag != -1) { print(\"Singular Matrix.\\n\"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if ($mat[$singular_flag][$N]) print(\"Inconsistent System.\"); else print(\"May have infinitely many solutions.\"); return; } /* get solution to system and print it using backward substitution */ backSub($mat);} // function for elementary operation// of swapping two rowsfunction swap_row(&$mat, $i, $j){ global $N; //printf(\"Swapped rows %d and %d\\n\", i, j); for ($k = 0; $k <= $N; $k++) { $temp = $mat[$i][$k]; $mat[$i][$k] = $mat[$j][$k]; $mat[$j][$k] = $temp; }} // function to print matrix content at any stagefunction print1($mat){ global $N; for ($i=0; $i<$N; $i++, print(\"\\n\")) for ($j=0; $j<=$N; $j++) print($mat[$i][$j]); print(\"\\n\");} // function to reduce matrix to r.e.f.function forwardElim(&$mat){ global $N; for ($k=0; $k<$N; $k++) { // Initialize maximum value and index for pivot $i_max = $k; $v_max = $mat[$i_max][$k]; /* find greater amplitude for pivot if any */ for ($i = $k+1; $i < $N; $i++) if (abs($mat[$i][$k]) > $v_max) { $v_max = $mat[$i][$k]; $i_max = $i; } /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (!$mat[$k][$i_max]) return $k; // Matrix is singular /* Swap the greatest value row with current row */ if ($i_max != $k) swap_row($mat, $k, $i_max); for ($i = $k + 1; $i < $N; $i++) { /* factor f to set current row kth element to 0, * and subsequently remaining kth column to 0 */ $f = $mat[$i][$k]/$mat[$k][$k]; /* subtract fth multiple of corresponding kth row element*/ for ($j = $k + 1; $j <= $N; $j++) $mat[$i][$j] -= $mat[$k][$j] * $f; /* filling lower triangular matrix with zeros*/ $mat[$i][$k] = 0; } //print(mat); //for matrix state } //print(mat); //for matrix state return -1;} // function to calculate the values of the unknownsfunction backSub(&$mat){ global $N; $x = array_fill(0, $N, 0); // An array to store solution /* Start calculating from last equation up to the first */ for ($i = $N - 1; $i >= 0; $i--) { /* start with the RHS of the equation */ $x[$i] = $mat[$i][$N]; /* Initialize j to i+1 since matrix is upper triangular*/ for ($j = $i + 1; $j < $N; $j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ $x[$i] -= $mat[$i][$j] * $x[$j]; } /* divide the RHS by the coefficient of the unknown being calculated */ $x[$i] = $x[$i] / $mat[$i][$i]; } print(\"\\nSolution for the system:\\n\"); for ($i = 0; $i < $N; $i++) print(number_format(strval($x[$i]), 6).\"\\n\");} // Driver program /* input matrix */ $mat = array(array(3.0, 2.0,-4.0, 3.0), array(2.0, 3.0, 3.0, 15.0), array(5.0, -3, 1.0, 14.0)); gaussianElimination($mat); // This code is contributed by mits?>", "e": 23069, "s": 19228, "text": null }, { "code": "// JavaScript program to demonstrate working of Gaussian Elimination// method let N = 3; // function to get matrix contentfunction gaussianElimination(mat){ /* reduction into r.e.f. */ let singular_flag = forwardElim(mat); /* if matrix is singular */ if (singular_flag != -1) { console.log(\"Singular Matrix.\"); /* if the RHS of equation corresponding to zero row is 0, * system has infinitely many solutions, else inconsistent*/ if (mat[singular_flag][N]) console.log(\"Inconsistent System.\"); else console.log(\"May have infinitely many solutions.\"); return; } /* get solution to system and print it using backward substitution */ backSub(mat);} // function for elementary operation of swapping two rowsfunction swap_row(mat, i, j){ //printf(\"Swapped rows %d and %d\\n\", i, j); for (var k=0; k<=N; k++) { let temp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = temp; }} // function to print matrix content at any stagefunction print(mat){ for (var i=0; i<N; i++, console.log(\"\")) for (var j=0; j<=N; j++) process.stdout.write(\"\" + mat[i][j]); console.log(\"\");} // function to reduce matrix to r.e.f.function forwardElim(mat){ for (var k=0; k<N; k++) { // Initialize maximum value and index for pivot var i_max = k; var v_max = mat[i_max][k]; /* find greater amplitude for pivot if any */ for (var i = k+1; i < N; i++) if (Math.abs(mat[i][k]) > v_max) v_max = mat[i][k], i_max = i; /* if a principal diagonal element is zero, * it denotes that matrix is singular, and * will lead to a division-by-zero later. */ if (!mat[k][i_max]) return k; // Matrix is singular /* Swap the greatest value row with current row */ if (i_max != k) swap_row(mat, k, i_max); for (var i=k+1; i<N; i++) { /* factor f to set current row kth element to 0, * and subsequently remaining kth column to 0 */ let f = mat[i][k]/mat[k][k]; /* subtract fth multiple of corresponding kth row element*/ for (var j=k+1; j<=N; j++) mat[i][j] -= mat[k][j]*f; /* filling lower triangular matrix with zeros*/ mat[i][k] = 0; } //print(mat); //for matrix state } //print(mat); //for matrix state return -1;} // function to calculate the values of the unknownsfunction backSub(mat){ let x = new Array(N); // An array to store solution /* Start calculating from last equation up to the first */ for (var i = N-1; i >= 0; i--) { /* start with the RHS of the equation */ x[i] = mat[i][N]; /* Initialize j to i+1 since matrix is upper triangular*/ for (var j=i+1; j<N; j++) { /* subtract all the lhs values * except the coefficient of the variable * whose value is being calculated */ x[i] -= mat[i][j]*x[j]; } /* divide the RHS by the coefficient of the unknown being calculated */ x[i] = Math.round(x[i]/mat[i][i]); } console.log(\"\\nSolution for the system:\"); for (var i=0; i<N; i++) console.log(x[i].toFixed(8));} // Driver program /* input matrix */let mat = [[3.0, 2.0,-4.0, 3.0], [2.0, 3.0, 3.0, 15.0], [5.0, -3, 1.0, 14.0]]; gaussianElimination(mat); // This code is contributed by phasing17", "e": 26689, "s": 23069, "text": null }, { "code": null, "e": 26698, "s": 26689, "text": "Output: " }, { "code": null, "e": 26750, "s": 26698, "text": "Solution for the system:\n3.000000\n1.000000\n2.000000" }, { "code": null, "e": 26766, "s": 26750, "text": "Illustration: " }, { "code": null, "e": 26942, "s": 26766, "text": "Time Complexity: Since for each pivot we traverse the part to its right for each row below it, O(n)*(O(n)*O(n)) = O(n3).We can also apply Gaussian Elimination for calculating:" }, { "code": null, "e": 27020, "s": 26942, "text": "Rank of a matrixDeterminant of a matrixInverse of an invertible square matrix" }, { "code": null, "e": 27037, "s": 27020, "text": "Rank of a matrix" }, { "code": null, "e": 27061, "s": 27037, "text": "Determinant of a matrix" }, { "code": null, "e": 27100, "s": 27061, "text": "Inverse of an invertible square matrix" }, { "code": null, "e": 27271, "s": 27100, "text": "This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 27284, "s": 27271, "text": "Mithun Kumar" }, { "code": null, "e": 27297, "s": 27284, "text": "Akanksha_Rai" }, { "code": null, "e": 27308, "s": 27297, "text": "nidhi_biet" }, { "code": null, "e": 27324, "s": 27308, "text": "dharanendralv23" }, { "code": null, "e": 27341, "s": 27324, "text": "shikhasingrajput" }, { "code": null, "e": 27354, "s": 27341, "text": "simmytarika5" }, { "code": null, "e": 27364, "s": 27354, "text": "phasing17" }, { "code": null, "e": 27377, "s": 27364, "text": "Mathematical" }, { "code": null, "e": 27390, "s": 27377, "text": "Mathematical" } ]
Flutter – Read and Write Data on Firebase
10 Nov, 2020 Firebase helps developers to manage their mobile app easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from firebase. We will be using flutter for this. To do this job we need to follow the 3-step procedure: Adding firebase to our appFirebase Setup Implement using Code Adding firebase to our app Firebase Setup Implement using Code To interact with firebase we have to register our app to firebase. Follow this link to complete the initial setup. After completing the above setup follow these steps: Step 1: After creating your project on the left-hand side you will see these options Step2: Select the cloud Firestore and then select create database and then select test mode and press next. Step 3: Select any location or you can keep it as it is and press enable After creating Cloud Firestore you will see the empty database, now you have to just create a table and add data to it later we will add data from our app. Follow the below steps to create a collection(tables). Step 1: Press Start collection Step 2: Enter a name for collection id and select auto id for its document Step 3: Press Add Field and add Field and Value as key-value pair Step 4: Finally this is how your final screen will look Step 1: In your flutter project open pubspec.yaml and under dependencies add the following packages: dependencies: flutter: sdk: flutter firebase_core: "^0.5.0" cloud_firestore: ^0.14.1 Save the above file. Note: While adding the above code ensure that the code added should on the same level as flutter. Step 2: In the terminal execute the following line. flutter pub get Before executing the above lines of code check whether you are in the right directory or not. The above code gets all the packages. If any error occurs please check your spacing while adding packages and also check that you have added the correct version of those packages. Step 3: Write Data Dart import 'package:flutter/material.dart';import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root // of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Firebase', home: AddData(), ); }} class AddData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: Text("geeksforgeeks"), ), body:Center( child: FloatingActionButton( backgroundColor: Colors.green, child: Icon(Icons.add), onPressed: () { FirebaseFirestore.instance .collection('data') .add({'text': 'data added through app'}); }, ), ), ); }} Output : Explanation: In the above code, we have created a floating action button in the center of the screen. When we press that button the key-value pair which we defined is sent to firebase and stored in it. Data will get stored repeatedly if the button is pressed multiple times. Step 4: Read Data Dart import 'package:flutter/material.dart';import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Firebase', home: AddData(), ); }} class AddData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: Text("geeksforgeeks"), ), body: StreamBuilder( stream: FirebaseFirestore.instance.collection('data').snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } return ListView( children: snapshot.data.docs.map((document) { return Container( child: Center(child: Text(document['text'])), ); }).toList(), ); }, ), ); }} Output: Explanation: In the above code, we fetch data from firebase and store it as a snapshot of our data. To print that data on screen we build a List view that displays the data as text. android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Nov, 2020" }, { "code": null, "e": 418, "s": 52, "text": "Firebase helps developers to manage their mobile app easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from firebase. We will be using flutter for this. To do this job we need to follow the 3-step procedure:" }, { "code": null, "e": 480, "s": 418, "text": "Adding firebase to our appFirebase Setup Implement using Code" }, { "code": null, "e": 507, "s": 480, "text": "Adding firebase to our app" }, { "code": null, "e": 523, "s": 507, "text": "Firebase Setup " }, { "code": null, "e": 544, "s": 523, "text": "Implement using Code" }, { "code": null, "e": 659, "s": 544, "text": "To interact with firebase we have to register our app to firebase. Follow this link to complete the initial setup." }, { "code": null, "e": 712, "s": 659, "text": "After completing the above setup follow these steps:" }, { "code": null, "e": 797, "s": 712, "text": "Step 1: After creating your project on the left-hand side you will see these options" }, { "code": null, "e": 906, "s": 797, "text": "Step2: Select the cloud Firestore and then select create database and then select test mode and press next." }, { "code": null, "e": 979, "s": 906, "text": "Step 3: Select any location or you can keep it as it is and press enable" }, { "code": null, "e": 1190, "s": 979, "text": "After creating Cloud Firestore you will see the empty database, now you have to just create a table and add data to it later we will add data from our app. Follow the below steps to create a collection(tables)." }, { "code": null, "e": 1221, "s": 1190, "text": "Step 1: Press Start collection" }, { "code": null, "e": 1296, "s": 1221, "text": "Step 2: Enter a name for collection id and select auto id for its document" }, { "code": null, "e": 1362, "s": 1296, "text": "Step 3: Press Add Field and add Field and Value as key-value pair" }, { "code": null, "e": 1418, "s": 1362, "text": "Step 4: Finally this is how your final screen will look" }, { "code": null, "e": 1519, "s": 1418, "text": "Step 1: In your flutter project open pubspec.yaml and under dependencies add the following packages:" }, { "code": null, "e": 1611, "s": 1519, "text": "dependencies:\n flutter:\n sdk: flutter\n firebase_core: \"^0.5.0\"\n cloud_firestore: ^0.14.1\n" }, { "code": null, "e": 1632, "s": 1611, "text": "Save the above file." }, { "code": null, "e": 1730, "s": 1632, "text": "Note: While adding the above code ensure that the code added should on the same level as flutter." }, { "code": null, "e": 1782, "s": 1730, "text": "Step 2: In the terminal execute the following line." }, { "code": null, "e": 1799, "s": 1782, "text": "flutter pub get\n" }, { "code": null, "e": 2073, "s": 1799, "text": "Before executing the above lines of code check whether you are in the right directory or not. The above code gets all the packages. If any error occurs please check your spacing while adding packages and also check that you have added the correct version of those packages." }, { "code": null, "e": 2092, "s": 2073, "text": "Step 3: Write Data" }, { "code": null, "e": 2097, "s": 2092, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root // of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Firebase', home: AddData(), ); }} class AddData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: Text(\"geeksforgeeks\"), ), body:Center( child: FloatingActionButton( backgroundColor: Colors.green, child: Icon(Icons.add), onPressed: () { FirebaseFirestore.instance .collection('data') .add({'text': 'data added through app'}); }, ), ), ); }}", "e": 3115, "s": 2097, "text": null }, { "code": null, "e": 3124, "s": 3115, "text": "Output :" }, { "code": null, "e": 3400, "s": 3124, "text": "Explanation: In the above code, we have created a floating action button in the center of the screen. When we press that button the key-value pair which we defined is sent to firebase and stored in it. Data will get stored repeatedly if the button is pressed multiple times. " }, { "code": null, "e": 3418, "s": 3400, "text": "Step 4: Read Data" }, { "code": null, "e": 3423, "s": 3418, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Firebase', home: AddData(), ); }} class AddData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: Text(\"geeksforgeeks\"), ), body: StreamBuilder( stream: FirebaseFirestore.instance.collection('data').snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } return ListView( children: snapshot.data.docs.map((document) { return Container( child: Center(child: Text(document['text'])), ); }).toList(), ); }, ), ); }}", "e": 4636, "s": 3423, "text": null }, { "code": null, "e": 4644, "s": 4636, "text": "Output:" }, { "code": null, "e": 4826, "s": 4644, "text": "Explanation: In the above code, we fetch data from firebase and store it as a snapshot of our data. To print that data on screen we build a List view that displays the data as text." }, { "code": null, "e": 4834, "s": 4826, "text": "android" }, { "code": null, "e": 4842, "s": 4834, "text": "Flutter" }, { "code": null, "e": 4847, "s": 4842, "text": "Dart" }, { "code": null, "e": 4855, "s": 4847, "text": "Flutter" } ]
Move all negative elements to end in order with extra space allowed
06 Jul, 2022 Given an unsorted array arr[] of both negative and positive integer. The task is place all negative element at the end of array without changing the order of positive element and negative element. Examples: Input : arr[] = {1, -1, 3, 2, -7, -5, 11, 6 } Output : 1 3 2 11 6 -1 -7 -5 Input : arr[] = {-5, 7, -3, -4, 9, 10, -1, 11} Output : 7 9 10 11 -5 -3 -4 -1 We have discussed different approaches to this problem in below post.Rearrange positive and negative numbers with constant extra space The problem becomes easier if we are allowed to use extra space. Idea is create an empty array (temp[]). First we store all positive element of given array and then we store all negative element of array in Temp[]. Finally we copy temp[] to original array. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to Move All -ve Element At End// Without changing order Of Array Element#include<bits/stdc++.h>using namespace std; // Moves all -ve element to end of array in// same order.void segregateElements(int arr[], int n){ // Create an empty array to store result int temp[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n ; i++) if (arr[i] >= 0 ) temp[j++] = arr[i]; // If array contains all positive or all negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0 ; i < n ; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] memcpy(arr, temp, sizeof(temp));} // Driver programint main(){ int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 }; int n = sizeof(arr)/sizeof(arr[0]); segregateElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to Move All -ve Element At End// Without changing order Of Array Elementimport java.util.Arrays; class GFG { // Moves all -ve element to end of array in // same order. static void segregateElements(int arr[], int n) { // Create an empty array to store result int temp[] = new int[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n; i++) if (arr[i] >= 0) temp[j++] = arr[i]; // If array contains all positive or all // negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0; i < n; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver code public static void main(String arg[]) { int arr[] = { 1, -1, -3, -2, 7, 5, 11, 6 }; int n = arr.length; segregateElements(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} // This code is contributed by Anant Agarwal. # Python program to Move All -ve Element At End# Without changing order Of Array Element # Moves all -ve element to end of array in# same order.def move(arr,n): j = 0 ans=[None]*n i=0;j=n-1 for k in range(n): if arr[k]>=0: ans[i]=arr[k] i+=1 else: ans[j]=arr[k] j-=1 ans[i:]=ans[n-1:i-1:-1] return ans # Driver programarr = [1 ,-1 ,-3 , -2, 7, 5, 11, 6 ]n = len(arr)print(move(arr, n)) # Contributed by Venkatesh hegde // C# program to Move All -ve Element At End// Without changing order Of Array Elementusing System; class GFG { // Moves all -ve element to // end of array in same order. static void segregateElements(int[] arr, int n) { // Create an empty array to store result int[] temp = new int[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n; i++) if (arr[i] >= 0) temp[j++] = arr[i]; // If array contains all positive or all // negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0; i < n; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver code public static void Main() { int[] arr = { 1, -1, -3, -2, 7, 5, 11, 6 }; int n = arr.Length; segregateElements(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This Code is contributed by vt_m. <?php// PHP program to Move All -ve Element At End// Without changing order Of Array Element // Moves all -ve element to end of// array in same order.function segregateElements(&$arr, $n){ // Create an empty array to store result $temp = array(0, $n, NULL); // Traversal array and store +ve // element in temp array $j = 0; // index of temp for ($i = 0; $i < $n ; $i++) if ($arr[$i] >= 0 ) $temp[$j++] = $arr[$i]; // If array contains all positive // or all negative. if ($j == $n || $j == 0) return; // Store -ve element in temp array for ($i = 0 ; $i < $n ; $i++) if ($arr[$i] < 0) $temp[$j++] = $arr[$i]; // Copy contents of temp[] to arr[] for($i = 0; $i < $n; $i++) $arr[$i] = $temp[$i];} // Driver Code$arr = array(1 ,-1 ,-3 , -2, 7, 5, 11, 6 );$n = sizeof($arr); segregateElements($arr, $n); for ($i = 0; $i < $n; $i++)echo $arr[$i] ." "; // This code is contributed// by ChitraNayal?> <script> // Javascript program to Move All -ve Element At End// Without changing order Of Array Element // Moves all -ve element to end of array in// same order.function segregateElements(arr, n){ // Create an empty array to store result let temp= new Array(n); // Traversal array and store +ve element in // temp array let j = 0; // index of temp for (let i = 0; i < n ; i++) if (arr[i] >= 0 ) temp[j++] = arr[i]; // If array contains all positive or all negative. if (j == n || j == 0) return; // Store -ve element in temp array for (let i = 0 ; i < n ; i++) if (arr[i] < 0) temp[j++] = arr[i]; for (let i = 0; i < n ; i++) arr[i] = temp[i];} // Driver program let arr= [1 ,-1 ,-3 , -2, 7, 5, 11, 6];let n = arr.length; segregateElements(arr, n); for (let i = 0; i < n; i++)document.write(arr[i] + " "); </script> 1 7 5 11 6 -1 -3 -2 Time Complexity : O(n) Auxiliary space : O(n) Related Articles: Rearrange positive and negative numbers with constant extra space Rearrange positive and negative numbers in O(n) time and O(1) extra space This article is contributed by Nishant_Singh (Pintu). 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. ukasp mohit kumar 29 venkateshhegde18 vyomkeshpandey amartyaghoshgfg tarakki100 hardikkoriintern array-rearrange Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 250, "s": 52, "text": "Given an unsorted array arr[] of both negative and positive integer. The task is place all negative element at the end of array without changing the order of positive element and negative element. " }, { "code": null, "e": 261, "s": 250, "text": "Examples: " }, { "code": null, "e": 432, "s": 261, "text": "Input : arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }\nOutput : 1 3 2 11 6 -1 -7 -5 \n\nInput : arr[] = {-5, 7, -3, -4, 9, 10, -1, 11}\nOutput : 7 9 10 11 -5 -3 -4 -1 " }, { "code": null, "e": 567, "s": 432, "text": "We have discussed different approaches to this problem in below post.Rearrange positive and negative numbers with constant extra space" }, { "code": null, "e": 824, "s": 567, "text": "The problem becomes easier if we are allowed to use extra space. Idea is create an empty array (temp[]). First we store all positive element of given array and then we store all negative element of array in Temp[]. Finally we copy temp[] to original array." }, { "code": null, "e": 840, "s": 824, "text": "Implementation:" }, { "code": null, "e": 844, "s": 840, "text": "C++" }, { "code": null, "e": 849, "s": 844, "text": "Java" }, { "code": null, "e": 857, "s": 849, "text": "Python3" }, { "code": null, "e": 860, "s": 857, "text": "C#" }, { "code": null, "e": 864, "s": 860, "text": "PHP" }, { "code": null, "e": 875, "s": 864, "text": "Javascript" }, { "code": "// C++ program to Move All -ve Element At End// Without changing order Of Array Element#include<bits/stdc++.h>using namespace std; // Moves all -ve element to end of array in// same order.void segregateElements(int arr[], int n){ // Create an empty array to store result int temp[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n ; i++) if (arr[i] >= 0 ) temp[j++] = arr[i]; // If array contains all positive or all negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0 ; i < n ; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] memcpy(arr, temp, sizeof(temp));} // Driver programint main(){ int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 }; int n = sizeof(arr)/sizeof(arr[0]); segregateElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 1866, "s": 875, "text": null }, { "code": "// Java program to Move All -ve Element At End// Without changing order Of Array Elementimport java.util.Arrays; class GFG { // Moves all -ve element to end of array in // same order. static void segregateElements(int arr[], int n) { // Create an empty array to store result int temp[] = new int[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n; i++) if (arr[i] >= 0) temp[j++] = arr[i]; // If array contains all positive or all // negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0; i < n; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver code public static void main(String arg[]) { int arr[] = { 1, -1, -3, -2, 7, 5, 11, 6 }; int n = arr.length; segregateElements(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }} // This code is contributed by Anant Agarwal.", "e": 3104, "s": 1866, "text": null }, { "code": "# Python program to Move All -ve Element At End# Without changing order Of Array Element # Moves all -ve element to end of array in# same order.def move(arr,n): j = 0 ans=[None]*n i=0;j=n-1 for k in range(n): if arr[k]>=0: ans[i]=arr[k] i+=1 else: ans[j]=arr[k] j-=1 ans[i:]=ans[n-1:i-1:-1] return ans # Driver programarr = [1 ,-1 ,-3 , -2, 7, 5, 11, 6 ]n = len(arr)print(move(arr, n)) # Contributed by Venkatesh hegde", "e": 3592, "s": 3104, "text": null }, { "code": "// C# program to Move All -ve Element At End// Without changing order Of Array Elementusing System; class GFG { // Moves all -ve element to // end of array in same order. static void segregateElements(int[] arr, int n) { // Create an empty array to store result int[] temp = new int[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n; i++) if (arr[i] >= 0) temp[j++] = arr[i]; // If array contains all positive or all // negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0; i < n; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver code public static void Main() { int[] arr = { 1, -1, -3, -2, 7, 5, 11, 6 }; int n = arr.Length; segregateElements(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This Code is contributed by vt_m.", "e": 4767, "s": 3592, "text": null }, { "code": "<?php// PHP program to Move All -ve Element At End// Without changing order Of Array Element // Moves all -ve element to end of// array in same order.function segregateElements(&$arr, $n){ // Create an empty array to store result $temp = array(0, $n, NULL); // Traversal array and store +ve // element in temp array $j = 0; // index of temp for ($i = 0; $i < $n ; $i++) if ($arr[$i] >= 0 ) $temp[$j++] = $arr[$i]; // If array contains all positive // or all negative. if ($j == $n || $j == 0) return; // Store -ve element in temp array for ($i = 0 ; $i < $n ; $i++) if ($arr[$i] < 0) $temp[$j++] = $arr[$i]; // Copy contents of temp[] to arr[] for($i = 0; $i < $n; $i++) $arr[$i] = $temp[$i];} // Driver Code$arr = array(1 ,-1 ,-3 , -2, 7, 5, 11, 6 );$n = sizeof($arr); segregateElements($arr, $n); for ($i = 0; $i < $n; $i++)echo $arr[$i] .\" \"; // This code is contributed// by ChitraNayal?>", "e": 5753, "s": 4767, "text": null }, { "code": "<script> // Javascript program to Move All -ve Element At End// Without changing order Of Array Element // Moves all -ve element to end of array in// same order.function segregateElements(arr, n){ // Create an empty array to store result let temp= new Array(n); // Traversal array and store +ve element in // temp array let j = 0; // index of temp for (let i = 0; i < n ; i++) if (arr[i] >= 0 ) temp[j++] = arr[i]; // If array contains all positive or all negative. if (j == n || j == 0) return; // Store -ve element in temp array for (let i = 0 ; i < n ; i++) if (arr[i] < 0) temp[j++] = arr[i]; for (let i = 0; i < n ; i++) arr[i] = temp[i];} // Driver program let arr= [1 ,-1 ,-3 , -2, 7, 5, 11, 6];let n = arr.length; segregateElements(arr, n); for (let i = 0; i < n; i++)document.write(arr[i] + \" \"); </script>", "e": 6648, "s": 5753, "text": null }, { "code": null, "e": 6669, "s": 6648, "text": "1 7 5 11 6 -1 -3 -2 " }, { "code": null, "e": 6716, "s": 6669, "text": "Time Complexity : O(n) Auxiliary space : O(n) " }, { "code": null, "e": 6874, "s": 6716, "text": "Related Articles: Rearrange positive and negative numbers with constant extra space Rearrange positive and negative numbers in O(n) time and O(1) extra space" }, { "code": null, "e": 7180, "s": 6874, "text": "This article is contributed by Nishant_Singh (Pintu). 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. " }, { "code": null, "e": 7186, "s": 7180, "text": "ukasp" }, { "code": null, "e": 7201, "s": 7186, "text": "mohit kumar 29" }, { "code": null, "e": 7218, "s": 7201, "text": "venkateshhegde18" }, { "code": null, "e": 7233, "s": 7218, "text": "vyomkeshpandey" }, { "code": null, "e": 7249, "s": 7233, "text": "amartyaghoshgfg" }, { "code": null, "e": 7260, "s": 7249, "text": "tarakki100" }, { "code": null, "e": 7277, "s": 7260, "text": "hardikkoriintern" }, { "code": null, "e": 7293, "s": 7277, "text": "array-rearrange" }, { "code": null, "e": 7300, "s": 7293, "text": "Arrays" }, { "code": null, "e": 7307, "s": 7300, "text": "Arrays" } ]
Check whether a character is Uppercase or not in Java
To check whether a character is in Uppercase or not in Java, use the Character.isUpperCase() method. We have a character to be checked. char val = 'K'; Now let us use the Character.isUpperCase() method. if (Character.isUpperCase(val)) { System.out.println("Character is in Uppercase!"); }else { System.out.println("Character is in Lowercase!"); } Let us see the complete example now to check for Uppercase in Java. Live Demo public class Demo { public static void main(String []args) { System.out.println("Checking for Uppercase character..."); char val = 'K'; System.out.println("Character: "+val); if (Character.isUpperCase(val)) { System.out.println("Character is in Uppercase!"); }else { System.out.println("Character is in Lowercase!"); } } } Checking for Uppercase character... Character: K Character is in Uppercase!
[ { "code": null, "e": 1163, "s": 1062, "text": "To check whether a character is in Uppercase or not in Java, use the Character.isUpperCase() method." }, { "code": null, "e": 1198, "s": 1163, "text": "We have a character to be checked." }, { "code": null, "e": 1214, "s": 1198, "text": "char val = 'K';" }, { "code": null, "e": 1265, "s": 1214, "text": "Now let us use the Character.isUpperCase() method." }, { "code": null, "e": 1415, "s": 1265, "text": "if (Character.isUpperCase(val)) {\n System.out.println(\"Character is in Uppercase!\");\n}else {\n System.out.println(\"Character is in Lowercase!\");\n}" }, { "code": null, "e": 1483, "s": 1415, "text": "Let us see the complete example now to check for Uppercase in Java." }, { "code": null, "e": 1494, "s": 1483, "text": " Live Demo" }, { "code": null, "e": 1877, "s": 1494, "text": "public class Demo {\n public static void main(String []args) {\n System.out.println(\"Checking for Uppercase character...\");\n char val = 'K';\n System.out.println(\"Character: \"+val);\n if (Character.isUpperCase(val)) {\n System.out.println(\"Character is in Uppercase!\");\n }else {\n System.out.println(\"Character is in Lowercase!\");\n }\n }\n}" }, { "code": null, "e": 1953, "s": 1877, "text": "Checking for Uppercase character...\nCharacter: K\nCharacter is in Uppercase!" } ]
Rock Paper and Scissor Game Using Tkinter
Tkinter is one of the Python-based libraries used to create and develop Desktop User interfaces and applications. Using the Tkinter library and its packages, we will create a Rock Paper Scissor Game Application. The game can be played between two people using hand gestures. The condition for winning the game is, If player A gets Paper and Player B gets scissors, then Scissor wins. If player A gets Paper and Player B gets scissors, then Scissor wins. If player A gets Paper and Player B gets Rock, then Paper wins. If player A gets Paper and Player B gets Rock, then Paper wins. Similarly, If player A gets Rock and Player B gets scissors, then Rock wins. If player A gets Rock and Player B gets scissors, then Rock wins. Following these game conditions, we will first create the GUI for the game user interface. The user can play with the device as the opponent itself. Our GUI application will have the following features, The application will have a Title following the User and Opponent. The application will have a Title following the User and Opponent. To denote the hand gestures for Rock, Paper, and scissors, we will create three buttons for each. To denote the hand gestures for Rock, Paper, and scissors, we will create three buttons for each. Once the game gets started, it will show the final winner on the application window. Once the game gets started, it will show the final winner on the application window. Reset button to reset the Game. Reset button to reset the Game. #import required libraries from tkinter import * from tkinter import ttk import random #Create an instance of tkinter frame win= Tk() #Set the geometry of the window win.geometry("750x450") #Set the title of the window win.title("Rock Paper Scissors...") #Default value for Computer computer_options = { "0":"Rock", "1":"Paper", "2":"Scissor" } #Disable all the Buttons after first Match def button_disable(): b1.config(state= "disabled") b2.config(state= "disabled") b3.config(state= "disabled") #Define function for Rock def isrock(): value = computer_options[str(random.randint(0,2))] if value == "Rock": match_result = "Match Draw" elif value=="Scissor": match_result = "Wohoo! You Won" else: match_result = "Computer Win" label.config(text = match_result) l1.config(text = "Rock") l3.config(text =value) button_disable() #Function for Paper def ispaper(): value = computer_options[str(random.randint(0, 2))] if value == "Paper": match_result = "Match Draw" elif value=="Scissor": match_result = "Computer Win" else: match_result = "Amazingg..You won" label.config(text = match_result) l1.config(text = "Paper") l3.config(text = value) button_disable() #Function for Scissor def isscissor(): value = computer_options[str(random.randint(0,2))] if value == "Rock": match_result = "Computer Win" elif value == "Scissor": match_result = "Match Draw" else: match_result = "You Win... :D" label.config(text = match_result) l1.config(text = "Scissor") l3.config(text = value) button_disable() #Reset the Game def reset(): b1.config(state= "active") b2.config(state= "active") b3.config(state= "active") l1.config(text = "Player") l3.config(text = "Computer") label.config(text = "") #Create a LabelFrame labelframe= LabelFrame(win, text= "Rock Paper Scissor", font= ('Century 20 bold'),labelanchor= "n",bd=5,bg= "khaki3",width= 600, height= 450, cursor= "target") labelframe.pack(expand= True, fill= BOTH) #Label for Player l1= Label(labelframe, text="Player", font= ('Helvetica 18 bold')) l1.place(relx= .18, rely= .1) #Label for VS l2= Label(labelframe, text="VS", font= ('Helvetica 18 bold'), bg="khaki3") l2.place(relx= .45, rely= .1) #Label for Computer l3= Label(labelframe, text="Computer", font= ('Helvetica 18 bold')) l3.place(relx= .65, rely= .1) #Create a label to display the Conditions label= Label(labelframe, text="", font=('Coveat', 25,'bold'), bg= "khaki3") label.pack(pady=150) #Create Button Set for Rock, Paper and Scissor b1= Button(labelframe, text= "Rock", font= 10, width= 7, command= isrock) b1.place(relx=.25, rely= .62) b2= Button(labelframe, text= "Paper", font= 10, width= 7 ,command= ispaper) b2.place(relx= .41,rely= .62) b3= Button(labelframe, text= "Scissor", font= 10, width= 7, command= isscissor) b3.place(relx= .58, rely= .62) #Button to reset the Game reset= Button(labelframe, text= "Reset",bg= "OrangeRed3", fg= "white",width= 7, font= 10, command= reset) reset.place(relx= .8, rely= .62) win.mainloop() Running the above code will display the GUI of the game. We can now play by clicking any of the buttons "Rock," "Paper," or "Scissor."
[ { "code": null, "e": 1376, "s": 1062, "text": "Tkinter is one of the Python-based libraries used to create and develop Desktop User interfaces and applications. Using the Tkinter library and its packages, we will create a Rock Paper Scissor Game Application. The game can be played between two people using hand gestures. The condition for winning the game is," }, { "code": null, "e": 1446, "s": 1376, "text": "If player A gets Paper and Player B gets scissors, then Scissor wins." }, { "code": null, "e": 1516, "s": 1446, "text": "If player A gets Paper and Player B gets scissors, then Scissor wins." }, { "code": null, "e": 1580, "s": 1516, "text": "If player A gets Paper and Player B gets Rock, then Paper wins." }, { "code": null, "e": 1644, "s": 1580, "text": "If player A gets Paper and Player B gets Rock, then Paper wins." }, { "code": null, "e": 1655, "s": 1644, "text": "Similarly," }, { "code": null, "e": 1721, "s": 1655, "text": "If player A gets Rock and Player B gets scissors, then Rock wins." }, { "code": null, "e": 1787, "s": 1721, "text": "If player A gets Rock and Player B gets scissors, then Rock wins." }, { "code": null, "e": 1990, "s": 1787, "text": "Following these game conditions, we will first create the GUI for the game user interface. The user can play with the device as the opponent itself. Our GUI application will have the following features," }, { "code": null, "e": 2057, "s": 1990, "text": "The application will have a Title following the User and Opponent." }, { "code": null, "e": 2124, "s": 2057, "text": "The application will have a Title following the User and Opponent." }, { "code": null, "e": 2222, "s": 2124, "text": "To denote the hand gestures for Rock, Paper, and scissors, we will create three buttons for each." }, { "code": null, "e": 2320, "s": 2222, "text": "To denote the hand gestures for Rock, Paper, and scissors, we will create three buttons for each." }, { "code": null, "e": 2405, "s": 2320, "text": "Once the game gets started, it will show the final winner on the application window." }, { "code": null, "e": 2490, "s": 2405, "text": "Once the game gets started, it will show the final winner on the application window." }, { "code": null, "e": 2522, "s": 2490, "text": "Reset button to reset the Game." }, { "code": null, "e": 2554, "s": 2522, "text": "Reset button to reset the Game." }, { "code": null, "e": 5673, "s": 2554, "text": "#import required libraries\nfrom tkinter import *\nfrom tkinter import ttk\nimport random\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of the window\nwin.geometry(\"750x450\")\n\n#Set the title of the window\nwin.title(\"Rock Paper Scissors...\")\n\n#Default value for Computer\ncomputer_options = {\n \"0\":\"Rock\",\n \"1\":\"Paper\",\n \"2\":\"Scissor\"\n}\n\n#Disable all the Buttons after first Match\ndef button_disable():\n b1.config(state= \"disabled\")\n b2.config(state= \"disabled\")\n b3.config(state= \"disabled\")\n\n#Define function for Rock\ndef isrock():\n value = computer_options[str(random.randint(0,2))]\n if value == \"Rock\":\n match_result = \"Match Draw\"\n elif value==\"Scissor\":\n match_result = \"Wohoo! You Won\"\n else:\n match_result = \"Computer Win\"\n label.config(text = match_result)\n l1.config(text = \"Rock\")\n l3.config(text =value)\n button_disable()\n\n#Function for Paper\ndef ispaper():\n value = computer_options[str(random.randint(0, 2))]\n if value == \"Paper\":\n match_result = \"Match Draw\"\n elif value==\"Scissor\":\n match_result = \"Computer Win\"\n else:\n match_result = \"Amazingg..You won\"\n label.config(text = match_result)\n l1.config(text = \"Paper\")\n l3.config(text = value)\n button_disable()\n\n#Function for Scissor\ndef isscissor():\n value = computer_options[str(random.randint(0,2))]\n if value == \"Rock\":\n match_result = \"Computer Win\"\n elif value == \"Scissor\":\n match_result = \"Match Draw\"\n else:\n match_result = \"You Win... :D\"\n label.config(text = match_result)\n l1.config(text = \"Scissor\")\n l3.config(text = value)\n button_disable()\n\n#Reset the Game\ndef reset():\n b1.config(state= \"active\")\n b2.config(state= \"active\")\n b3.config(state= \"active\")\n l1.config(text = \"Player\")\n l3.config(text = \"Computer\")\n label.config(text = \"\")\n\n#Create a LabelFrame\nlabelframe= LabelFrame(win, text= \"Rock Paper Scissor\", font= ('Century 20 bold'),labelanchor= \"n\",bd=5,bg= \"khaki3\",width= 600, height= 450, cursor= \"target\")\nlabelframe.pack(expand= True, fill= BOTH)\n\n#Label for Player\nl1= Label(labelframe, text=\"Player\", font= ('Helvetica 18 bold'))\nl1.place(relx= .18, rely= .1)\n\n#Label for VS\nl2= Label(labelframe, text=\"VS\", font= ('Helvetica 18 bold'), bg=\"khaki3\")\nl2.place(relx= .45, rely= .1)\n\n#Label for Computer\nl3= Label(labelframe, text=\"Computer\", font= ('Helvetica 18 bold'))\nl3.place(relx= .65, rely= .1)\n\n#Create a label to display the Conditions\nlabel= Label(labelframe, text=\"\", font=('Coveat', 25,'bold'), bg= \"khaki3\")\nlabel.pack(pady=150)\n\n#Create Button Set for Rock, Paper and Scissor\nb1= Button(labelframe, text= \"Rock\", font= 10, width= 7, command= isrock)\nb1.place(relx=.25, rely= .62)\nb2= Button(labelframe, text= \"Paper\", font= 10, width= 7 ,command= ispaper)\nb2.place(relx= .41,rely= .62)\nb3= Button(labelframe, text= \"Scissor\", font= 10, width= 7, command= isscissor)\nb3.place(relx= .58, rely= .62)\n\n#Button to reset the Game\nreset= Button(labelframe, text= \"Reset\",bg= \"OrangeRed3\", fg= \"white\",width= 7, font= 10, command= reset)\nreset.place(relx= .8, rely= .62)\nwin.mainloop()" }, { "code": null, "e": 5808, "s": 5673, "text": "Running the above code will display the GUI of the game. We can now play by clicking any of the buttons \"Rock,\" \"Paper,\" or \"Scissor.\"" } ]
deque insert() function in C++ STL - GeeksforGeeks
12 Dec, 2018 The deque::insert() function is a built-in function in C++ which is used to insert elements in the deque.The insert() function can be used in three ways: Extends deque by inserting a new element val at a position. Extends deque by inserting n new element of value val in the deque. Extends deque by inserting new element in the range [first, last). Syntax: deque_name.insert (iterator position, const value_type& val) or deque_name.insert (iterator position, size_type n, const value_type& val) or deque_name.insert (iterator position, InputIterator first, InputIterator last) Parameters: The function accepts four parameters which are specified as below: position – Specifies the position where the element/elements are to be inserted. val – specifies the value to be assigned to newly inserted element. n – specifies the number of elements to insert. Each element is initialized to a copy of val. first, last – specifies the iterators specifying a range of elements which is to be inserted. The range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. Return value: The function returns an iterator that points to the first of the newly inserted elements. Below programs illustrate the above function:Program 1: // CPP program to illustrate the// deque::insert() function// insert elements by iterator#include <bits/stdc++.h>using namespace std; int main(){ deque<int> dq = { 1, 2, 3, 4, 5 }; deque<int>::iterator it = dq.begin(); ++it; it = dq.insert(it, 10); // 1 10 2 3 4 5 std::cout << "Deque contains:"; for (it = dq.begin(); it != dq.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0;} Deque contains: 1 10 2 3 4 5 Program 2: // CPP program to illustrate the// deque::insert() function// program for second syntax#include <bits/stdc++.h>using namespace std; int main(){ deque<int> dq = { 1, 2, 3, 4, 5 }; deque<int>::iterator it = dq.begin(); // 0 0 1 2 3 4 5 dq.insert(it, 2, 0); std::cout << "Deque contains:"; for (it = dq.begin(); it != dq.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0;} Deque contains: 0 0 1 2 3 4 5 Program 3: // CPP program to illustrate the// deque::insert() function// program for third syntax#include <bits/stdc++.h>using namespace std; int main(){ deque<int> dq = { 1, 2, 3, 4, 5 }; deque<int>::iterator it = dq.begin(); ++it; vector<int> v(2, 10); // 1 10 10 2 3 4 5 dq.insert(it, v.begin(), v.end()); std::cout << "Deque contains:"; for (it = dq.begin(); it != dq.end(); ++it) cout << ' ' << *it; cout << '\n'; return 0;} Deque contains: 1 10 10 2 3 4 5 BhushanPagare cpp-deque CPP-Functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ List in C++ Standard Template Library (STL)
[ { "code": null, "e": 25477, "s": 25449, "text": "\n12 Dec, 2018" }, { "code": null, "e": 25631, "s": 25477, "text": "The deque::insert() function is a built-in function in C++ which is used to insert elements in the deque.The insert() function can be used in three ways:" }, { "code": null, "e": 25691, "s": 25631, "text": "Extends deque by inserting a new element val at a position." }, { "code": null, "e": 25759, "s": 25691, "text": "Extends deque by inserting n new element of value val in the deque." }, { "code": null, "e": 25826, "s": 25759, "text": "Extends deque by inserting new element in the range [first, last)." }, { "code": null, "e": 25834, "s": 25826, "text": "Syntax:" }, { "code": null, "e": 26087, "s": 25834, "text": "deque_name.insert (iterator position, const value_type& val)\n or\ndeque_name.insert (iterator position, size_type n, const value_type& val)\n or\ndeque_name.insert (iterator position, InputIterator first, InputIterator last)\n" }, { "code": null, "e": 26166, "s": 26087, "text": "Parameters: The function accepts four parameters which are specified as below:" }, { "code": null, "e": 26247, "s": 26166, "text": "position – Specifies the position where the element/elements are to be inserted." }, { "code": null, "e": 26315, "s": 26247, "text": "val – specifies the value to be assigned to newly inserted element." }, { "code": null, "e": 26409, "s": 26315, "text": "n – specifies the number of elements to insert. Each element is initialized to a copy of val." }, { "code": null, "e": 26635, "s": 26409, "text": "first, last – specifies the iterators specifying a range of elements which is to be inserted. The range includes all the elements between first and last, including the element pointed by first but not the one pointed by last." }, { "code": null, "e": 26739, "s": 26635, "text": "Return value: The function returns an iterator that points to the first of the newly inserted elements." }, { "code": null, "e": 26795, "s": 26739, "text": "Below programs illustrate the above function:Program 1:" }, { "code": "// CPP program to illustrate the// deque::insert() function// insert elements by iterator#include <bits/stdc++.h>using namespace std; int main(){ deque<int> dq = { 1, 2, 3, 4, 5 }; deque<int>::iterator it = dq.begin(); ++it; it = dq.insert(it, 10); // 1 10 2 3 4 5 std::cout << \"Deque contains:\"; for (it = dq.begin(); it != dq.end(); ++it) cout << ' ' << *it; cout << '\\n'; return 0;}", "e": 27221, "s": 26795, "text": null }, { "code": null, "e": 27251, "s": 27221, "text": "Deque contains: 1 10 2 3 4 5\n" }, { "code": null, "e": 27262, "s": 27251, "text": "Program 2:" }, { "code": "// CPP program to illustrate the// deque::insert() function// program for second syntax#include <bits/stdc++.h>using namespace std; int main(){ deque<int> dq = { 1, 2, 3, 4, 5 }; deque<int>::iterator it = dq.begin(); // 0 0 1 2 3 4 5 dq.insert(it, 2, 0); std::cout << \"Deque contains:\"; for (it = dq.begin(); it != dq.end(); ++it) cout << ' ' << *it; cout << '\\n'; return 0;}", "e": 27680, "s": 27262, "text": null }, { "code": null, "e": 27711, "s": 27680, "text": "Deque contains: 0 0 1 2 3 4 5\n" }, { "code": null, "e": 27722, "s": 27711, "text": "Program 3:" }, { "code": "// CPP program to illustrate the// deque::insert() function// program for third syntax#include <bits/stdc++.h>using namespace std; int main(){ deque<int> dq = { 1, 2, 3, 4, 5 }; deque<int>::iterator it = dq.begin(); ++it; vector<int> v(2, 10); // 1 10 10 2 3 4 5 dq.insert(it, v.begin(), v.end()); std::cout << \"Deque contains:\"; for (it = dq.begin(); it != dq.end(); ++it) cout << ' ' << *it; cout << '\\n'; return 0;}", "e": 28189, "s": 27722, "text": null }, { "code": null, "e": 28222, "s": 28189, "text": "Deque contains: 1 10 10 2 3 4 5\n" }, { "code": null, "e": 28236, "s": 28222, "text": "BhushanPagare" }, { "code": null, "e": 28246, "s": 28236, "text": "cpp-deque" }, { "code": null, "e": 28260, "s": 28246, "text": "CPP-Functions" }, { "code": null, "e": 28264, "s": 28260, "text": "STL" }, { "code": null, "e": 28268, "s": 28264, "text": "C++" }, { "code": null, "e": 28272, "s": 28268, "text": "STL" }, { "code": null, "e": 28276, "s": 28272, "text": "CPP" }, { "code": null, "e": 28374, "s": 28276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28402, "s": 28374, "text": "Operator Overloading in C++" }, { "code": null, "e": 28422, "s": 28402, "text": "Polymorphism in C++" }, { "code": null, "e": 28455, "s": 28422, "text": "Friend class and function in C++" }, { "code": null, "e": 28479, "s": 28455, "text": "Sorting a vector in C++" }, { "code": null, "e": 28504, "s": 28479, "text": "std::string class in C++" }, { "code": null, "e": 28528, "s": 28504, "text": "Inline Functions in C++" }, { "code": null, "e": 28572, "s": 28528, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 28625, "s": 28572, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 28661, "s": 28625, "text": "Convert string to char array in C++" } ]
GATE | GATE-CS-2015 (Set 3) | Question 56 - GeeksforGeeks
28 Jun, 2021 Consider B+ tree in which the search key is 12 bytes long, block size is 1024 bytes, record pointer is 10 bytes long and block pointer is 8 bytes long. The maximum number of keys that can be accommodated in each non-leaf node of the tree is(A) 49(B) 50(C) 51(D) 52Answer: (B)Explanation: Let m be the order of B+ tree m(8)+(m-1)12 <= 1024 [Note that record pointer is not needed in non-leaf nodes] m <= 51 Since maximum order is 51, maximum number of keys is 50. Quiz of this Question GATE-CS-2015 (Set 3) GATE-GATE-CS-2015 (Set 3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25893, "s": 25865, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26181, "s": 25893, "text": "Consider B+ tree in which the search key is 12 bytes long, block size is 1024 bytes, record pointer is 10 bytes long and block pointer is 8 bytes long. The maximum number of keys that can be accommodated in each non-leaf node of the tree is(A) 49(B) 50(C) 51(D) 52Answer: (B)Explanation:" }, { "code": null, "e": 26362, "s": 26181, "text": "Let m be the order of B+ tree\n\nm(8)+(m-1)12 <= 1024 \n[Note that record pointer is not needed in non-leaf nodes]\n\nm <= 51\n\nSince maximum order is 51, maximum number of keys is 50. " }, { "code": null, "e": 26384, "s": 26362, "text": "Quiz of this Question" }, { "code": null, "e": 26405, "s": 26384, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 26431, "s": 26405, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 26436, "s": 26431, "text": "GATE" }, { "code": null, "e": 26534, "s": 26436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26568, "s": 26534, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26602, "s": 26568, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26636, "s": 26602, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26669, "s": 26636, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26705, "s": 26669, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26739, "s": 26705, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26775, "s": 26739, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26809, "s": 26775, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26843, "s": 26809, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to Use Streamlit and Python to Build a Data Science App | Towards Data Science
Web apps are still useful tools for data scientists to present their data science projects to users. Since we may not have web development skills, we can use open-source python libraries like Streamlit to easily develop web apps in a short time. Introduction to StreamlitInstallation and Set upDevelop the Web AppTest the Web AppConclusion Introduction to Streamlit Installation and Set up Develop the Web App Test the Web App Conclusion Streamlit is an open-source python library for creating and sharing web apps for data science and machine learning projects. The library can help you create and deploy your data science solution in a few minutes with a few lines of code. Streamlit can seamlessly integrate with other popular python libraries used in Data science such as NumPy, Pandas, Matplotlib, Scikit-learn and many more. Note: Streamlit uses React as a frontend framework to render the data on the screen. Streamlit requires python >= 3.7 version in your machine. To install streamlit, you need to run the command below in the terminal. pip install streamlit You can also check the version installed on your machine with the following command. streamlit --version streamlit, version 1.1.0 After successfully installing streamlit, you can test the library by running the command below in the terminal. streamlit hello Streamlit’s Hello app will appear in a new tab in your web browser. This shows that everything is running ok, we can move on and create our first web app by using Streamlit. In this part, we are going to deploy the trained NLP model that predicts the sentiment of a movie’s review (positive or negative). You can access the source code and the dataset here. The data science web app will show a text field to add the movie’s review and a simple button to submit the review and make predictions. Import Important Packages The first step is to create a python file called app.py and then import required python packages for both streamlit and the trained NLP model. # import packagesimport streamlit as stimport osimport numpy as np from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer # text preprocessing modulesfrom string import punctuation # text preprocessing modulesfrom nltk.tokenize import word_tokenize import nltkfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerimport re # regular expressionimport joblib import warnings warnings.filterwarnings("ignore")# seedingnp.random.seed(123) # load stop wordsstop_words = stopwords.words("english") Function to Clean the Review The reviews can have unnecessary words and characters that we don’t need when making predictions. We will clean the review by removing stopwords, numbers, and punctuation. Then we will convert each word into its base form by using the lemmatization process in the NLTK package. The text_cleaning() function will handle all necessary steps to clean our review before making a prediction. # function to clean the [email protected] text_cleaning(text, remove_stop_words=True, lemmatize_words=True): # Clean the text, with the option to remove stop_words and to lemmatize word # Clean the text text = re.sub(r"[^A-Za-z0-9]", " ", text) text = re.sub(r"\'s", " ", text) text = re.sub(r"http\S+", " link ", text) text = re.sub(r"\b\d+(?:\.\d+)?\s+", "", text) # remove numbers # Remove punctuation from text text = "".join([c for c in text if c not in punctuation]) # Optionally, remove stop words if remove_stop_words: text = text.split() text = [w for w in text if not w in stop_words] text = " ".join(text) # Optionally, shorten words to their stems if lemmatize_words: text = text.split() lemmatizer = WordNetLemmatizer() lemmatized_words = [lemmatizer.lemmatize(word) for word in text] text = " ".join(lemmatized_words) # Return a list of words return text Function to Make Prediction The python function called make_prediction() will do the following tasks. Receive the review and clean it.Load the trained NLP model.Make a prediction.Estimate the probability of the prediction.Finally, it will return the predicted class and its probability. Receive the review and clean it. Load the trained NLP model. Make a prediction. Estimate the probability of the prediction. Finally, it will return the predicted class and its probability. # functon to make [email protected] make_prediction(review): # clearn the data clean_review = text_cleaning(review) # load the model and make prediction model = joblib.load("sentiment_model_pipeline.pkl") # make prection result = model.predict([clean_review]) # check probabilities probas = model.predict_proba([clean_review]) probability = "{:.2f}".format(float(probas[:, result])) return result, probability Note: if the trained NLP model predicts 1, it means Positive and if it predicts 0, it means Negative. Create App Title and Description You can create the title of your web app and its description by using the title() and write() method from streamlit. # Set the app titlest.title("Sentiment Analyisis App")st.write( "A simple machine laerning app to predict the sentiment of a movie's review") To show the web app, you need to run the following command in your terminal. streamlit run app.py Then you will see the web app automatically pop up in your web browser or you can use the local URL created http://localhost:8501. Create a Form to Receive a Movie’s Review The next step is to create a simple form by using streamlit. The form will show a text field to add your review and below the text field, it will show a simple button to submit the review added and then make a prediction. # Declare a form to receive a movie's reviewform = st.form(key="my_form")review = form.text_input(label="Enter the text of your movie review")submit = form.form_submit_button(label="Make Prediction") Now, you can see the form on the web app. Make Predictions and show Results Our last piece of code is to make predictions and show results whenever a user adds a movie’s review and clicks the “make prediction” button on the form section. After clicking the button, the web app will run the make_prediction() function and show the result on the web app in the browser. if submit: # make prediction from the input text result, probability = make_prediction(review) # Display results of the NLP task st.header("Results") if int(result) == 1: st.write("This is a positive review with a probabiliy of ", probability) else: st.write("This is a negative review with a probabiliy of ", probability) With a few lines of code, we have created a simple data science web app that can receive a movie review and predict if it is a positive review or a negative review. To test the web app, fill the text field by adding a movie review of your choice. I added the following movie review about Zack Snyder’s Justice League movie released in 2021. “I loved the movie from the beginning to the end. Just like Ray Fisher said, I was hoping that the movie doesn’t end. The begging scene was mind blowing, liked that scene very much. Unlike ‘the Justice League’ the movie show every hero is best at their own thing, make us love every character. Thanks, Zack and the whole team.” Then click the make prediction button and view the result. As you can see on the web app we have created, the trained NLP model predicts the review added is positive with a probability of 0.64. I recommend you add another movie review on the data science web app we have created and test it again. There are a lot of features and components from Streamlit that you can use to develop a data science web app the way you want. What you have learned here, are some of the common elements from streamlit. To learn more you can visit their beautiful designed documentation pages here. If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next article!. You can also find me on Twitter @Davis_McDavid. One last thing: Read more articles like this in the following links python.plainenglish.io medium.datadriveninvestor.com medium.datadriveninvestor.com This article was first published here.
[ { "code": null, "e": 418, "s": 172, "text": "Web apps are still useful tools for data scientists to present their data science projects to users. Since we may not have web development skills, we can use open-source python libraries like Streamlit to easily develop web apps in a short time." }, { "code": null, "e": 512, "s": 418, "text": "Introduction to StreamlitInstallation and Set upDevelop the Web AppTest the Web AppConclusion" }, { "code": null, "e": 538, "s": 512, "text": "Introduction to Streamlit" }, { "code": null, "e": 562, "s": 538, "text": "Installation and Set up" }, { "code": null, "e": 582, "s": 562, "text": "Develop the Web App" }, { "code": null, "e": 599, "s": 582, "text": "Test the Web App" }, { "code": null, "e": 610, "s": 599, "text": "Conclusion" }, { "code": null, "e": 848, "s": 610, "text": "Streamlit is an open-source python library for creating and sharing web apps for data science and machine learning projects. The library can help you create and deploy your data science solution in a few minutes with a few lines of code." }, { "code": null, "e": 1003, "s": 848, "text": "Streamlit can seamlessly integrate with other popular python libraries used in Data science such as NumPy, Pandas, Matplotlib, Scikit-learn and many more." }, { "code": null, "e": 1088, "s": 1003, "text": "Note: Streamlit uses React as a frontend framework to render the data on the screen." }, { "code": null, "e": 1146, "s": 1088, "text": "Streamlit requires python >= 3.7 version in your machine." }, { "code": null, "e": 1219, "s": 1146, "text": "To install streamlit, you need to run the command below in the terminal." }, { "code": null, "e": 1241, "s": 1219, "text": "pip install streamlit" }, { "code": null, "e": 1326, "s": 1241, "text": "You can also check the version installed on your machine with the following command." }, { "code": null, "e": 1346, "s": 1326, "text": "streamlit --version" }, { "code": null, "e": 1371, "s": 1346, "text": "streamlit, version 1.1.0" }, { "code": null, "e": 1483, "s": 1371, "text": "After successfully installing streamlit, you can test the library by running the command below in the terminal." }, { "code": null, "e": 1499, "s": 1483, "text": "streamlit hello" }, { "code": null, "e": 1567, "s": 1499, "text": "Streamlit’s Hello app will appear in a new tab in your web browser." }, { "code": null, "e": 1673, "s": 1567, "text": "This shows that everything is running ok, we can move on and create our first web app by using Streamlit." }, { "code": null, "e": 1857, "s": 1673, "text": "In this part, we are going to deploy the trained NLP model that predicts the sentiment of a movie’s review (positive or negative). You can access the source code and the dataset here." }, { "code": null, "e": 1994, "s": 1857, "text": "The data science web app will show a text field to add the movie’s review and a simple button to submit the review and make predictions." }, { "code": null, "e": 2020, "s": 1994, "text": "Import Important Packages" }, { "code": null, "e": 2163, "s": 2020, "text": "The first step is to create a python file called app.py and then import required python packages for both streamlit and the trained NLP model." }, { "code": null, "e": 2697, "s": 2163, "text": "# import packagesimport streamlit as stimport osimport numpy as np from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer # text preprocessing modulesfrom string import punctuation # text preprocessing modulesfrom nltk.tokenize import word_tokenize import nltkfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerimport re # regular expressionimport joblib import warnings warnings.filterwarnings(\"ignore\")# seedingnp.random.seed(123) # load stop wordsstop_words = stopwords.words(\"english\")" }, { "code": null, "e": 2726, "s": 2697, "text": "Function to Clean the Review" }, { "code": null, "e": 2824, "s": 2726, "text": "The reviews can have unnecessary words and characters that we don’t need when making predictions." }, { "code": null, "e": 3004, "s": 2824, "text": "We will clean the review by removing stopwords, numbers, and punctuation. Then we will convert each word into its base form by using the lemmatization process in the NLTK package." }, { "code": null, "e": 3113, "s": 3004, "text": "The text_cleaning() function will handle all necessary steps to clean our review before making a prediction." }, { "code": null, "e": 4078, "s": 3113, "text": "# function to clean the [email protected] text_cleaning(text, remove_stop_words=True, lemmatize_words=True): # Clean the text, with the option to remove stop_words and to lemmatize word # Clean the text text = re.sub(r\"[^A-Za-z0-9]\", \" \", text) text = re.sub(r\"\\'s\", \" \", text) text = re.sub(r\"http\\S+\", \" link \", text) text = re.sub(r\"\\b\\d+(?:\\.\\d+)?\\s+\", \"\", text) # remove numbers # Remove punctuation from text text = \"\".join([c for c in text if c not in punctuation]) # Optionally, remove stop words if remove_stop_words: text = text.split() text = [w for w in text if not w in stop_words] text = \" \".join(text) # Optionally, shorten words to their stems if lemmatize_words: text = text.split() lemmatizer = WordNetLemmatizer() lemmatized_words = [lemmatizer.lemmatize(word) for word in text] text = \" \".join(lemmatized_words) # Return a list of words return text" }, { "code": null, "e": 4106, "s": 4078, "text": "Function to Make Prediction" }, { "code": null, "e": 4180, "s": 4106, "text": "The python function called make_prediction() will do the following tasks." }, { "code": null, "e": 4365, "s": 4180, "text": "Receive the review and clean it.Load the trained NLP model.Make a prediction.Estimate the probability of the prediction.Finally, it will return the predicted class and its probability." }, { "code": null, "e": 4398, "s": 4365, "text": "Receive the review and clean it." }, { "code": null, "e": 4426, "s": 4398, "text": "Load the trained NLP model." }, { "code": null, "e": 4445, "s": 4426, "text": "Make a prediction." }, { "code": null, "e": 4489, "s": 4445, "text": "Estimate the probability of the prediction." }, { "code": null, "e": 4554, "s": 4489, "text": "Finally, it will return the predicted class and its probability." }, { "code": null, "e": 5004, "s": 4554, "text": "# functon to make [email protected] make_prediction(review): # clearn the data clean_review = text_cleaning(review) # load the model and make prediction model = joblib.load(\"sentiment_model_pipeline.pkl\") # make prection result = model.predict([clean_review]) # check probabilities probas = model.predict_proba([clean_review]) probability = \"{:.2f}\".format(float(probas[:, result])) return result, probability" }, { "code": null, "e": 5106, "s": 5004, "text": "Note: if the trained NLP model predicts 1, it means Positive and if it predicts 0, it means Negative." }, { "code": null, "e": 5139, "s": 5106, "text": "Create App Title and Description" }, { "code": null, "e": 5256, "s": 5139, "text": "You can create the title of your web app and its description by using the title() and write() method from streamlit." }, { "code": null, "e": 5401, "s": 5256, "text": "# Set the app titlest.title(\"Sentiment Analyisis App\")st.write( \"A simple machine laerning app to predict the sentiment of a movie's review\")" }, { "code": null, "e": 5478, "s": 5401, "text": "To show the web app, you need to run the following command in your terminal." }, { "code": null, "e": 5499, "s": 5478, "text": "streamlit run app.py" }, { "code": null, "e": 5630, "s": 5499, "text": "Then you will see the web app automatically pop up in your web browser or you can use the local URL created http://localhost:8501." }, { "code": null, "e": 5672, "s": 5630, "text": "Create a Form to Receive a Movie’s Review" }, { "code": null, "e": 5894, "s": 5672, "text": "The next step is to create a simple form by using streamlit. The form will show a text field to add your review and below the text field, it will show a simple button to submit the review added and then make a prediction." }, { "code": null, "e": 6094, "s": 5894, "text": "# Declare a form to receive a movie's reviewform = st.form(key=\"my_form\")review = form.text_input(label=\"Enter the text of your movie review\")submit = form.form_submit_button(label=\"Make Prediction\")" }, { "code": null, "e": 6136, "s": 6094, "text": "Now, you can see the form on the web app." }, { "code": null, "e": 6170, "s": 6136, "text": "Make Predictions and show Results" }, { "code": null, "e": 6332, "s": 6170, "text": "Our last piece of code is to make predictions and show results whenever a user adds a movie’s review and clicks the “make prediction” button on the form section." }, { "code": null, "e": 6462, "s": 6332, "text": "After clicking the button, the web app will run the make_prediction() function and show the result on the web app in the browser." }, { "code": null, "e": 6819, "s": 6462, "text": "if submit: # make prediction from the input text result, probability = make_prediction(review) # Display results of the NLP task st.header(\"Results\") if int(result) == 1: st.write(\"This is a positive review with a probabiliy of \", probability) else: st.write(\"This is a negative review with a probabiliy of \", probability)" }, { "code": null, "e": 6984, "s": 6819, "text": "With a few lines of code, we have created a simple data science web app that can receive a movie review and predict if it is a positive review or a negative review." }, { "code": null, "e": 7160, "s": 6984, "text": "To test the web app, fill the text field by adding a movie review of your choice. I added the following movie review about Zack Snyder’s Justice League movie released in 2021." }, { "code": null, "e": 7488, "s": 7160, "text": "“I loved the movie from the beginning to the end. Just like Ray Fisher said, I was hoping that the movie doesn’t end. The begging scene was mind blowing, liked that scene very much. Unlike ‘the Justice League’ the movie show every hero is best at their own thing, make us love every character. Thanks, Zack and the whole team.”" }, { "code": null, "e": 7547, "s": 7488, "text": "Then click the make prediction button and view the result." }, { "code": null, "e": 7682, "s": 7547, "text": "As you can see on the web app we have created, the trained NLP model predicts the review added is positive with a probability of 0.64." }, { "code": null, "e": 7786, "s": 7682, "text": "I recommend you add another movie review on the data science web app we have created and test it again." }, { "code": null, "e": 7989, "s": 7786, "text": "There are a lot of features and components from Streamlit that you can use to develop a data science web app the way you want. What you have learned here, are some of the common elements from streamlit." }, { "code": null, "e": 8068, "s": 7989, "text": "To learn more you can visit their beautiful designed documentation pages here." }, { "code": null, "e": 8215, "s": 8068, "text": "If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next article!." }, { "code": null, "e": 8263, "s": 8215, "text": "You can also find me on Twitter @Davis_McDavid." }, { "code": null, "e": 8331, "s": 8263, "text": "One last thing: Read more articles like this in the following links" }, { "code": null, "e": 8354, "s": 8331, "text": "python.plainenglish.io" }, { "code": null, "e": 8384, "s": 8354, "text": "medium.datadriveninvestor.com" }, { "code": null, "e": 8414, "s": 8384, "text": "medium.datadriveninvestor.com" } ]
Angular Material - Sliders
The md-slider, an Angular directive is used to show a range component. It has two modes − normal − User can slide between wide range of values. This mode exists by default. normal − User can slide between wide range of values. This mode exists by default. discrete − User can slide between selected values. To enable discrete mode use mddiscrete and step attributes. discrete − User can slide between selected values. To enable discrete mode use mddiscrete and step attributes. The following table lists out the parameters and description of the different attributes of the md-slider. md-discrete This determines whether to enable discrete mode. step The distance between values the user is allowed to pick. By default, it is 1. min The minimum value the user is allowed to pick. By default, it is 0. max The maximum value the user is allowed to pick. By default, it is 100. The following example shows the use of md-sidenav and also the uses of sidenav component. am_sliders.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('sliderController', sliderController); function sliderController ($scope, $mdSidenav) { $scope.color = { red: Math.floor(Math.random() * 255), green: Math.floor(Math.random() * 255), blue: Math.floor(Math.random() * 255) }; $scope.rating = 3; $scope.disabled = 70; } </script> </head> <body ng-app = "firstApplication"> <div id = "sliderContainer" ng-controller = "sliderController as ctrl" layout = "row" ng-cloak> <md-content style = "margin: 16px; padding:16px"> <div layout> <h4 style = "margin-top:10px">Default</h4> <md-slider flex min = "0" max = "255" ng-model = "color.red" aria-label = "red" id = "red-slider" class></md-slider> <div flex = "20" layout layout-align = "center center"> <input flex type = "number" ng-model = "color.red" aria-label = "red" aria-controls = "red-slider"> </div> </div> <div layout> <h4 style = "margin-top:10px">Warning</h4> <md-slider class = "md-warn" flex min = "0" max = "255" ng-model = "color.green" aria-label = "green" id = "green-slider"> </md-slider> <div flex = "20" layout layout-align = "center center"> <input flex type = "number" ng-model = "color.green" aria-label = "green" aria-controls = "green-slider"> </div> </div> <div layout> <h4 style = "margin-top:10px">Primary</h4> <md-slider class = "md-primary" flex min = "0" max = "255" ng-model = "color.blue" aria-label = "blue" id = "blue-slider"> </md-slider> <div flex = "20" layout layout-align = "center center"> <input flex type = "number" ng-model = "color.blue" aria-label = "blue" aria-controls = "blue-slider"> </div> </div> <div layout> <h4 style = "margin-top:10px">Discrete</h4> <md-slider flex md-discrete ng-model = "rating" step = "1" min = "1" max = "5" aria-label = "rating"></md-slider> <div flex = "20" layout layout-align = "center center"> <input flex type = "number" ng-model = "rating" aria-label = "rating" aria-controls = "rating-slider"> </div> </div> <div layout> <h4 style = "margin-top:10px">Disabled</h4> <md-slider flex min = "0" max = "255" ng-model = "disabled" ng-disabled = "true" aria-label = "Disabled"></md-slider> </div> <div layout> <h4 style = "margin-top:10px">Disabled, Discrete</h4> <md-slider flex md-discrete ng-model = "rating" step = "1" min = "1" max = "5" aria-label = "disabled" ng-disabled = "true"></md-slider> </div> </md-content> </div> </body> </html> Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2280, "s": 2190, "text": "The md-slider, an Angular directive is used to show a range component. It has two modes −" }, { "code": null, "e": 2363, "s": 2280, "text": "normal − User can slide between wide range of values. This mode exists by default." }, { "code": null, "e": 2446, "s": 2363, "text": "normal − User can slide between wide range of values. This mode exists by default." }, { "code": null, "e": 2557, "s": 2446, "text": "discrete − User can slide between selected values. To enable discrete mode use mddiscrete and step attributes." }, { "code": null, "e": 2668, "s": 2557, "text": "discrete − User can slide between selected values. To enable discrete mode use mddiscrete and step attributes." }, { "code": null, "e": 2775, "s": 2668, "text": "The following table lists out the parameters and description of the different attributes of the md-slider." }, { "code": null, "e": 2787, "s": 2775, "text": "md-discrete" }, { "code": null, "e": 2836, "s": 2787, "text": "This determines whether to enable discrete mode." }, { "code": null, "e": 2841, "s": 2836, "text": "step" }, { "code": null, "e": 2919, "s": 2841, "text": "The distance between values the user is allowed to pick. By default, it is 1." }, { "code": null, "e": 2923, "s": 2919, "text": "min" }, { "code": null, "e": 2991, "s": 2923, "text": "The minimum value the user is allowed to pick. By default, it is 0." }, { "code": null, "e": 2995, "s": 2991, "text": "max" }, { "code": null, "e": 3065, "s": 2995, "text": "The maximum value the user is allowed to pick. By default, it is 100." }, { "code": null, "e": 3155, "s": 3065, "text": "The following example shows the use of md-sidenav and also the uses of sidenav component." }, { "code": null, "e": 3170, "s": 3155, "text": "am_sliders.htm" }, { "code": null, "e": 7501, "s": 3170, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('sliderController', sliderController);\n\n function sliderController ($scope, $mdSidenav) {\n $scope.color = {\n red: Math.floor(Math.random() * 255),\n green: Math.floor(Math.random() * 255),\n blue: Math.floor(Math.random() * 255)\n };\n $scope.rating = 3; \n $scope.disabled = 70;\n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"sliderContainer\" ng-controller = \"sliderController as ctrl\"\n layout = \"row\" ng-cloak>\n <md-content style = \"margin: 16px; padding:16px\">\n <div layout>\n <h4 style = \"margin-top:10px\">Default</h4>\t\t\n <md-slider flex min = \"0\" max = \"255\" ng-model = \"color.red\"\n aria-label = \"red\" id = \"red-slider\" class></md-slider>\n <div flex = \"20\" layout layout-align = \"center center\">\n <input flex type = \"number\" ng-model = \"color.red\" aria-label = \"red\"\n aria-controls = \"red-slider\">\n </div>\n </div>\n \n <div layout>\n <h4 style = \"margin-top:10px\">Warning</h4>\t\t\n <md-slider class = \"md-warn\" flex min = \"0\" max = \"255\"\n ng-model = \"color.green\" aria-label = \"green\" id = \"green-slider\">\n </md-slider>\n <div flex = \"20\" layout layout-align = \"center center\">\n <input flex type = \"number\" ng-model = \"color.green\"\n aria-label = \"green\" aria-controls = \"green-slider\">\n </div>\n </div>\n \n <div layout>\n <h4 style = \"margin-top:10px\">Primary</h4>\t\t\n <md-slider class = \"md-primary\" flex min = \"0\" max = \"255\"\n ng-model = \"color.blue\" aria-label = \"blue\" id = \"blue-slider\">\n </md-slider>\n <div flex = \"20\" layout layout-align = \"center center\">\n <input flex type = \"number\" ng-model = \"color.blue\" aria-label = \"blue\"\n aria-controls = \"blue-slider\">\n </div>\n </div>\n \n <div layout>\n <h4 style = \"margin-top:10px\">Discrete</h4>\t\t\n <md-slider flex md-discrete ng-model = \"rating\" step = \"1\" min = \"1\"\n max = \"5\" aria-label = \"rating\"></md-slider>\n <div flex = \"20\" layout layout-align = \"center center\">\n <input flex type = \"number\" ng-model = \"rating\" aria-label = \"rating\"\n aria-controls = \"rating-slider\">\n </div>\n </div>\n \n <div layout>\n <h4 style = \"margin-top:10px\">Disabled</h4>\t\t \n <md-slider flex min = \"0\" max = \"255\" ng-model = \"disabled\"\n ng-disabled = \"true\" aria-label = \"Disabled\"></md-slider> \n </div>\n \n <div layout>\n <h4 style = \"margin-top:10px\">Disabled, Discrete</h4>\t\t \n <md-slider flex md-discrete ng-model = \"rating\" step = \"1\" min = \"1\"\n max = \"5\" aria-label = \"disabled\" ng-disabled = \"true\"></md-slider> \n </div>\n </md-content>\n \n </div>\n </body>\n</html>" }, { "code": null, "e": 7520, "s": 7501, "text": "Verify the result." }, { "code": null, "e": 7555, "s": 7520, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7569, "s": 7555, "text": " Anadi Sharma" }, { "code": null, "e": 7604, "s": 7569, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7618, "s": 7604, "text": " Anadi Sharma" }, { "code": null, "e": 7653, "s": 7618, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7673, "s": 7653, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7708, "s": 7673, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7725, "s": 7708, "text": " Frahaan Hussain" }, { "code": null, "e": 7758, "s": 7725, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7770, "s": 7758, "text": " Senol Atac" }, { "code": null, "e": 7805, "s": 7770, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7817, "s": 7805, "text": " Senol Atac" }, { "code": null, "e": 7824, "s": 7817, "text": " Print" }, { "code": null, "e": 7835, "s": 7824, "text": " Add Notes" } ]
RStudio Server in AWS EMR easy, reproducible, and fast | by Luis Henrique Zanandréa Paese | Towards Data Science
In a previous post that I’ve written (which can be found here), I shared my views on the use of Infrastructure as Code tools, such as Packer and Terraform, to create Amazon Machine Images (AMI), creating a reproducible environment for data scientists and data analysts to explore Cloud resources with many tools pre-installed in the machine (Jupyterhub and RStudio Server). I shall not extend myself in this post, since it has already been covered, but the repository associated with the other blog post uses Ansible playbooks to install the required packages and libraries to develop analysis and models using both R and Python, however, the main reason that I’ve explored the possibilities of creating custom AMIs is to use them as base images in the deployment of AWS EMR Clusters. Many people that have deployed EMR Clusters in the past, already know that the deployment of the cluster can be associated with bootstrap scripts that will provide the necessary tools that the Data Scientist, Analyst, or Engineer will use in their work, and even though this is a significant solution, it adds a time penalty to the deployment of the server (the more packages and libraries associated with the cluster initialization, the higher will be the time of deployment of the cluster). The default deployment of EMR allows the provisioning of Jupyter Notebooks or Zeppelin notebooks along with the initialization of the cluster, however, R and RStudio users are left lagging behind since both solutions are not available natively in the EMR Cluster, so I felt compelled to explore other solutions that were both scalable and fast allowing every analyst/scientist/engineer to deploy their own cluster, do their work in what language best suits their needs, and then shut down the cluster when they are done. After some digging, I found out that after the release of EMR 5.7 (and later), the cluster could be deployed using a custom Amazon Machine image, only by following a few recommendations and best practices as suggested here, like using an Amazon Linux 2 for EMR releases greater than EMR 5.30 and 6.x. This was the trigger that led me to first, create a custom Amazon Machine Image using Packer and Ansible (to ensure the installation and configuration of an RStudio Server), and later on use this image to deploy an EMR Cluster, and do a few more configurations to ensure that the RStudio user would have access to the Spark environments, Hadoop and other features available by using an EMR Cluster. As with my other blog post, this is associated with a repository that helps the user to: Deploy an EMR Cluster using Terraform and using a custom AMI Configure the default RStudio Server user to access the Hadoop File System and Spark environments Use the AWS Glue Metastore along with the Spark cluster, so that data catalogs that already exist in Glue can be accessed by the EMR Cluster Beware that this deployment is AWS-focused, and I don’t have plans to develop this same project in other clouds right now, even though I know it is possible by using tools that are available from both Google Cloud Platform and Azure. In the project repository, we have a stack to deploy the EMR cluster using Terraform scripts that are modularized, so any adaptations necessary to suit your infrastructure needs (such as the creation of keys, or permission of roles) can be implemented separately. As of today, Terraform expects the variables as described below, to allow the creation of the cluster master server and core nodes along with it. This implementation also supports the use of spot instances in the master and core nodes, however, in any production environment, it is recommended that at least the master node be deployed as an On-Demand instance, since, if it shuts down, the whole cluster would be terminated. The variables available in my Terraform configuration are as below: # EMR general configurationsname = "" # Name of the EMR Clusterregion = "us-east-1" # Region of the cluster, must be the same region that the AMI was builtkey_name = "" # The name of the key pair that can be used to SSH into the clusteringress_cidr_blocks = "" # Your IP address to connect to the clusterrelease_label = "emr-6.1.0" # The release of EMR of your choiceapplications = ["Hadoop", "Spark", "Hive"] # The applications to be available as the cluster starts up# Master node configurationsmaster_instance_type = "m5.xlarge" # EC2 instance type of the master node The underlying architecture of the machine must be compatible with the one used to build the custom AMImaster_ebs_size = "50" # Size in GiB of the EBS disk allocated to master instancemaster_ami = "" # ID of the AMI created with the custom installation of R and RStudio# If the user chooses to set a bid price, it will implicitly create a SPOT Request# If left empty, it will default to On-Demand instancesmaster_bid_price = ""# Core nodes configurationscore_instance_type = "m5.xlarge" # EC2 instance type of each core node The underlying architecture of the machine must be compatible with the one used to build the custom AMIcore_ebs_size = "50" # Size in GiB of the EBS disk allocated to each core instancecore_instance_count = 1 # Number of core instances that the cluster can scale# If the user chooses to set a bid price, it will implicitly create a SPOT Request# If left empty, it will default to On-Demand instancescore_bid_price = "0.10" These configurations should be enough to get you up and running with a custom EMR cluster. A few changes to enhance security were added since December 2020, that require the user to manually allow ports to be publically available as can be found here. If this is not your case, you can skip to the next session, but, if you desire to expose your RStudio Server instance to be publically accessible through the internet, you have to follow the steps described below: Go into the AWS Console > EMR Select Block Public Access (which should be activated) Edit the port interval to allow port 8787 to be used publically by RStudio Server If your desire is to deploy a custom server that will be available only to a few IP addresses, you can skip this step and set the ingress_cidr_blocks to your personal IP address. The steps described below are already embedded in the Terraform scripts that deploy the cluster and are here merely for informational purposes if someone wishes to tweak with it and customize it. After the deployment of the server is added a further step that configures the environment variables that make it easier for RStudio to find the necessary files to run smoothly with Spark, Hive, Hadoop, and other tools available in the cluster. Also, this step adds RStudio users to the Hadoop group and allows it to modify the HDFS. This step can be found here in the project. With the rising of off-the-shelf tools, such as AWS Glue, that allow the transformation of data and storing both the data and its metadata in an easy way, there was a need to integrate the EMR Cluster with this stack. This is also already been done in the Terraform stack, so if the user desire to use a Hive Metastore instead of a managed AWS Glue Metastore, this part of the code needs to be removed. This step is done by a configurations_json inside the EMR main Terraform, which receives multiple inputs about how the cluster should be configured, changing spark-defaults (allowing different SQL catalog implementations for example), hive-site configurations to use the AWS Glue Metastore as default hive-site, and so on. The list of possibilities to be configured can be found here. The deployment of this project aims to close the gap between the provisioning of Data Science related stacks, trying to ensure that, no matter the tool that the Data Scientists/Analyst/Engineer aims to use, they will have the opportunity to use it. By the end of the deployment, one should be able to access, in less than 10 minutes, a fully functional EMR cluster with R and RStudio server installed and configured in the master node of the EMR. Any issues related to this project, including suggestions, can be added to the Github repository.
[ { "code": null, "e": 546, "s": 172, "text": "In a previous post that I’ve written (which can be found here), I shared my views on the use of Infrastructure as Code tools, such as Packer and Terraform, to create Amazon Machine Images (AMI), creating a reproducible environment for data scientists and data analysts to explore Cloud resources with many tools pre-installed in the machine (Jupyterhub and RStudio Server)." }, { "code": null, "e": 957, "s": 546, "text": "I shall not extend myself in this post, since it has already been covered, but the repository associated with the other blog post uses Ansible playbooks to install the required packages and libraries to develop analysis and models using both R and Python, however, the main reason that I’ve explored the possibilities of creating custom AMIs is to use them as base images in the deployment of AWS EMR Clusters." }, { "code": null, "e": 1450, "s": 957, "text": "Many people that have deployed EMR Clusters in the past, already know that the deployment of the cluster can be associated with bootstrap scripts that will provide the necessary tools that the Data Scientist, Analyst, or Engineer will use in their work, and even though this is a significant solution, it adds a time penalty to the deployment of the server (the more packages and libraries associated with the cluster initialization, the higher will be the time of deployment of the cluster)." }, { "code": null, "e": 1971, "s": 1450, "text": "The default deployment of EMR allows the provisioning of Jupyter Notebooks or Zeppelin notebooks along with the initialization of the cluster, however, R and RStudio users are left lagging behind since both solutions are not available natively in the EMR Cluster, so I felt compelled to explore other solutions that were both scalable and fast allowing every analyst/scientist/engineer to deploy their own cluster, do their work in what language best suits their needs, and then shut down the cluster when they are done." }, { "code": null, "e": 2671, "s": 1971, "text": "After some digging, I found out that after the release of EMR 5.7 (and later), the cluster could be deployed using a custom Amazon Machine image, only by following a few recommendations and best practices as suggested here, like using an Amazon Linux 2 for EMR releases greater than EMR 5.30 and 6.x. This was the trigger that led me to first, create a custom Amazon Machine Image using Packer and Ansible (to ensure the installation and configuration of an RStudio Server), and later on use this image to deploy an EMR Cluster, and do a few more configurations to ensure that the RStudio user would have access to the Spark environments, Hadoop and other features available by using an EMR Cluster." }, { "code": null, "e": 2760, "s": 2671, "text": "As with my other blog post, this is associated with a repository that helps the user to:" }, { "code": null, "e": 2821, "s": 2760, "text": "Deploy an EMR Cluster using Terraform and using a custom AMI" }, { "code": null, "e": 2919, "s": 2821, "text": "Configure the default RStudio Server user to access the Hadoop File System and Spark environments" }, { "code": null, "e": 3060, "s": 2919, "text": "Use the AWS Glue Metastore along with the Spark cluster, so that data catalogs that already exist in Glue can be accessed by the EMR Cluster" }, { "code": null, "e": 3294, "s": 3060, "text": "Beware that this deployment is AWS-focused, and I don’t have plans to develop this same project in other clouds right now, even though I know it is possible by using tools that are available from both Google Cloud Platform and Azure." }, { "code": null, "e": 3704, "s": 3294, "text": "In the project repository, we have a stack to deploy the EMR cluster using Terraform scripts that are modularized, so any adaptations necessary to suit your infrastructure needs (such as the creation of keys, or permission of roles) can be implemented separately. As of today, Terraform expects the variables as described below, to allow the creation of the cluster master server and core nodes along with it." }, { "code": null, "e": 3984, "s": 3704, "text": "This implementation also supports the use of spot instances in the master and core nodes, however, in any production environment, it is recommended that at least the master node be deployed as an On-Demand instance, since, if it shuts down, the whole cluster would be terminated." }, { "code": null, "e": 4052, "s": 3984, "text": "The variables available in my Terraform configuration are as below:" }, { "code": null, "e": 5572, "s": 4052, "text": "# EMR general configurationsname = \"\" # Name of the EMR Clusterregion = \"us-east-1\" # Region of the cluster, must be the same region that the AMI was builtkey_name = \"\" # The name of the key pair that can be used to SSH into the clusteringress_cidr_blocks = \"\" # Your IP address to connect to the clusterrelease_label = \"emr-6.1.0\" # The release of EMR of your choiceapplications = [\"Hadoop\", \"Spark\", \"Hive\"] # The applications to be available as the cluster starts up# Master node configurationsmaster_instance_type = \"m5.xlarge\" # EC2 instance type of the master node The underlying architecture of the machine must be compatible with the one used to build the custom AMImaster_ebs_size = \"50\" # Size in GiB of the EBS disk allocated to master instancemaster_ami = \"\" # ID of the AMI created with the custom installation of R and RStudio# If the user chooses to set a bid price, it will implicitly create a SPOT Request# If left empty, it will default to On-Demand instancesmaster_bid_price = \"\"# Core nodes configurationscore_instance_type = \"m5.xlarge\" # EC2 instance type of each core node The underlying architecture of the machine must be compatible with the one used to build the custom AMIcore_ebs_size = \"50\" # Size in GiB of the EBS disk allocated to each core instancecore_instance_count = 1 # Number of core instances that the cluster can scale# If the user chooses to set a bid price, it will implicitly create a SPOT Request# If left empty, it will default to On-Demand instancescore_bid_price = \"0.10\"" }, { "code": null, "e": 5663, "s": 5572, "text": "These configurations should be enough to get you up and running with a custom EMR cluster." }, { "code": null, "e": 6038, "s": 5663, "text": "A few changes to enhance security were added since December 2020, that require the user to manually allow ports to be publically available as can be found here. If this is not your case, you can skip to the next session, but, if you desire to expose your RStudio Server instance to be publically accessible through the internet, you have to follow the steps described below:" }, { "code": null, "e": 6068, "s": 6038, "text": "Go into the AWS Console > EMR" }, { "code": null, "e": 6123, "s": 6068, "text": "Select Block Public Access (which should be activated)" }, { "code": null, "e": 6205, "s": 6123, "text": "Edit the port interval to allow port 8787 to be used publically by RStudio Server" }, { "code": null, "e": 6384, "s": 6205, "text": "If your desire is to deploy a custom server that will be available only to a few IP addresses, you can skip this step and set the ingress_cidr_blocks to your personal IP address." }, { "code": null, "e": 6580, "s": 6384, "text": "The steps described below are already embedded in the Terraform scripts that deploy the cluster and are here merely for informational purposes if someone wishes to tweak with it and customize it." }, { "code": null, "e": 6914, "s": 6580, "text": "After the deployment of the server is added a further step that configures the environment variables that make it easier for RStudio to find the necessary files to run smoothly with Spark, Hive, Hadoop, and other tools available in the cluster. Also, this step adds RStudio users to the Hadoop group and allows it to modify the HDFS." }, { "code": null, "e": 6958, "s": 6914, "text": "This step can be found here in the project." }, { "code": null, "e": 7361, "s": 6958, "text": "With the rising of off-the-shelf tools, such as AWS Glue, that allow the transformation of data and storing both the data and its metadata in an easy way, there was a need to integrate the EMR Cluster with this stack. This is also already been done in the Terraform stack, so if the user desire to use a Hive Metastore instead of a managed AWS Glue Metastore, this part of the code needs to be removed." }, { "code": null, "e": 7746, "s": 7361, "text": "This step is done by a configurations_json inside the EMR main Terraform, which receives multiple inputs about how the cluster should be configured, changing spark-defaults (allowing different SQL catalog implementations for example), hive-site configurations to use the AWS Glue Metastore as default hive-site, and so on. The list of possibilities to be configured can be found here." }, { "code": null, "e": 8193, "s": 7746, "text": "The deployment of this project aims to close the gap between the provisioning of Data Science related stacks, trying to ensure that, no matter the tool that the Data Scientists/Analyst/Engineer aims to use, they will have the opportunity to use it. By the end of the deployment, one should be able to access, in less than 10 minutes, a fully functional EMR cluster with R and RStudio server installed and configured in the master node of the EMR." } ]
How to Get City and State Name from Pincode in Android? - GeeksforGeeks
06 Jan, 2021 Many apps ask users to add the address in their apps. To make this task easy for the users they firstly prompt the user to add Pincode and from that Pincode, they fetch the data such as city and state name. So the user’s task is reduced to add city and state names while entering the address. Along with many apps so, many websites use this functionality that they first prompt the user to add pin code and after adding Pincode the city and state fields are entered automatically. So in this article, we will take a look at How we can incorporate that feature and get the city and state name from any Pincode of India. The Pincode is also referred to as postal code which is used to get the details of the nearby post office. These codes are generally used to get the details of the post office such as name, city, state, and many other details. We will be building a simple application in which we will be entering a pin code and after clicking on a button we will get to see the details such as city name, state, and country. Below is the GIF image in which we will get to know what we are going to build in this article. The Pincode is provided by Post Offices and postal services. Indian post is one of the most popular post service operators in India. So in this project, we will be using an API which is provided by Indian Post which will give us details such as city, state, and country name. Step 1: Create a new project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the below dependency in your build.gradle file Below is the dependency for Volley which we will be using to get the data from API of Indian Post. implementation ‘com.android.volley:volley:1.1.1’ After adding this dependency sync your project and now move toward the XML part. Step 3: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="vertical" tools:context=".MainActivity"> <!--heading text view--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Pin code validator" android:textAlignment="center" android:textColor="@color/purple_500" android:textSize="30sp" /> <!-- edit text for entering our pin code we are specifying input type as number--> <EditText android:id="@+id/idedtPinCode" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:hint="Enter pin code" android:importantForAutofill="no" android:inputType="number" android:maxLines="1" android:singleLine="true" /> <!--button to get the data from pin code--> <Button android:id="@+id/idBtnGetCityandState" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="50dp" android:text="Get city and state" android:textAllCaps="false" /> <!--text view to display the data received from pin code--> <TextView android:id="@+id/idTVPinCodeDetails" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:padding="10dp" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/purple_500" android:textSize="20sp" /> </LinearLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for edi text, // button and our text views. private EditText pinCodeEdt; private Button getDataBtn; private TextView pinCodeDetailsTV; // creating a variable for our string. String pinCode; // creating a variable for request queue. private RequestQueue mRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. pinCodeEdt = findViewById(R.id.idedtPinCode); getDataBtn = findViewById(R.id.idBtnGetCityandState); pinCodeDetailsTV = findViewById(R.id.idTVPinCodeDetails); // initializing our request que variable with request // queue and passing our context to it. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // initialing on click listener for our button. getDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting string from EditText. pinCode = pinCodeEdt.getText().toString(); // validating if the text is empty or not. if (TextUtils.isEmpty(pinCode)) { // displaying a toast message if the // text field is empty Toast.makeText(MainActivity.this, "Please enter valid pin code", Toast.LENGTH_SHORT).show(); } else { // calling a method to display // our pincode details. getDataFromPinCode(pinCode); } } }); } private void getDataFromPinCode(String pinCode) { // clearing our cache of request queue. mRequestQueue.getCache().clear(); // below is the url from where we will be getting // our response in the json format. String url = "http://www.postalpincode.in/api/pincode/" + pinCode; // below line is use to initialize our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // in below line we are creating a // object request using volley. JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // inside this method we will get two methods // such as on response method // inside on response method we are extracting // data from the json format. try { // we are getting data of post office // in the form of JSON file. JSONArray postOfficeArray = response.getJSONArray("PostOffice"); if (response.getString("Status").equals("Error")) { // validating if the response status is success or failure. // in this method the response status is having error and // we are setting text to TextView as invalid pincode. pinCodeDetailsTV.setText("Pin code is not valid."); } else { // if the status is success we are calling this method // in which we are getting data from post office object // here we are calling first object of our json array. JSONObject obj = postOfficeArray.getJSONObject(0); // inside our json array we are getting district name, // state and country from our data. String district = obj.getString("District"); String state = obj.getString("State"); String country = obj.getString("Country"); // after getting all data we are setting this data in // our text view on below line. pinCodeDetailsTV.setText("Details of pin code is : \n" + "District is : " + district + "\n" + "State : " + state + "\n" + "Country : " + country); } } catch (JSONException e) { // if we gets any error then it // will be printed in log cat. e.printStackTrace(); pinCodeDetailsTV.setText("Pin code is not valid"); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // below method is called if we get // any error while fetching data from API. // below line is use to display an error message. Toast.makeText(MainActivity.this, "Pin code is not valid.", Toast.LENGTH_SHORT).show(); pinCodeDetailsTV.setText("Pin code is not valid"); } }); // below line is use for adding object // request to our request queue. queue.add(objectRequest); }} Step 5: Add permission for the internet in the Manifest file Navigate to the app > AndroidManifest.xml file and add the below permissions to it. <uses-permission android:name=”android.permission.INTERNET”/> android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24750, "s": 24722, "text": "\n06 Jan, 2021" }, { "code": null, "e": 25597, "s": 24750, "text": "Many apps ask users to add the address in their apps. To make this task easy for the users they firstly prompt the user to add Pincode and from that Pincode, they fetch the data such as city and state name. So the user’s task is reduced to add city and state names while entering the address. Along with many apps so, many websites use this functionality that they first prompt the user to add pin code and after adding Pincode the city and state fields are entered automatically. So in this article, we will take a look at How we can incorporate that feature and get the city and state name from any Pincode of India. The Pincode is also referred to as postal code which is used to get the details of the nearby post office. These codes are generally used to get the details of the post office such as name, city, state, and many other details. " }, { "code": null, "e": 26152, "s": 25597, "text": "We will be building a simple application in which we will be entering a pin code and after clicking on a button we will get to see the details such as city name, state, and country. Below is the GIF image in which we will get to know what we are going to build in this article. The Pincode is provided by Post Offices and postal services. Indian post is one of the most popular post service operators in India. So in this project, we will be using an API which is provided by Indian Post which will give us details such as city, state, and country name. " }, { "code": null, "e": 26199, "s": 26152, "text": "Step 1: Create a new project in Android Studio" }, { "code": null, "e": 26361, "s": 26199, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 26420, "s": 26361, "text": "Step 2: Add the below dependency in your build.gradle file" }, { "code": null, "e": 26520, "s": 26420, "text": "Below is the dependency for Volley which we will be using to get the data from API of Indian Post. " }, { "code": null, "e": 26569, "s": 26520, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 26651, "s": 26569, "text": "After adding this dependency sync your project and now move toward the XML part. " }, { "code": null, "e": 26699, "s": 26651, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26815, "s": 26699, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26819, "s": 26815, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--heading text view--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:text=\"Pin code validator\" android:textAlignment=\"center\" android:textColor=\"@color/purple_500\" android:textSize=\"30sp\" /> <!-- edit text for entering our pin code we are specifying input type as number--> <EditText android:id=\"@+id/idedtPinCode\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:hint=\"Enter pin code\" android:importantForAutofill=\"no\" android:inputType=\"number\" android:maxLines=\"1\" android:singleLine=\"true\" /> <!--button to get the data from pin code--> <Button android:id=\"@+id/idBtnGetCityandState\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"50dp\" android:text=\"Get city and state\" android:textAllCaps=\"false\" /> <!--text view to display the data received from pin code--> <TextView android:id=\"@+id/idTVPinCodeDetails\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:padding=\"10dp\" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/purple_500\" android:textSize=\"20sp\" /> </LinearLayout>", "e": 28725, "s": 26819, "text": null }, { "code": null, "e": 28773, "s": 28725, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 28963, "s": 28773, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 28968, "s": 28963, "text": "Java" }, { "code": "import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for edi text, // button and our text views. private EditText pinCodeEdt; private Button getDataBtn; private TextView pinCodeDetailsTV; // creating a variable for our string. String pinCode; // creating a variable for request queue. private RequestQueue mRequestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. pinCodeEdt = findViewById(R.id.idedtPinCode); getDataBtn = findViewById(R.id.idBtnGetCityandState); pinCodeDetailsTV = findViewById(R.id.idTVPinCodeDetails); // initializing our request que variable with request // queue and passing our context to it. mRequestQueue = Volley.newRequestQueue(MainActivity.this); // initialing on click listener for our button. getDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting string from EditText. pinCode = pinCodeEdt.getText().toString(); // validating if the text is empty or not. if (TextUtils.isEmpty(pinCode)) { // displaying a toast message if the // text field is empty Toast.makeText(MainActivity.this, \"Please enter valid pin code\", Toast.LENGTH_SHORT).show(); } else { // calling a method to display // our pincode details. getDataFromPinCode(pinCode); } } }); } private void getDataFromPinCode(String pinCode) { // clearing our cache of request queue. mRequestQueue.getCache().clear(); // below is the url from where we will be getting // our response in the json format. String url = \"http://www.postalpincode.in/api/pincode/\" + pinCode; // below line is use to initialize our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // in below line we are creating a // object request using volley. JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // inside this method we will get two methods // such as on response method // inside on response method we are extracting // data from the json format. try { // we are getting data of post office // in the form of JSON file. JSONArray postOfficeArray = response.getJSONArray(\"PostOffice\"); if (response.getString(\"Status\").equals(\"Error\")) { // validating if the response status is success or failure. // in this method the response status is having error and // we are setting text to TextView as invalid pincode. pinCodeDetailsTV.setText(\"Pin code is not valid.\"); } else { // if the status is success we are calling this method // in which we are getting data from post office object // here we are calling first object of our json array. JSONObject obj = postOfficeArray.getJSONObject(0); // inside our json array we are getting district name, // state and country from our data. String district = obj.getString(\"District\"); String state = obj.getString(\"State\"); String country = obj.getString(\"Country\"); // after getting all data we are setting this data in // our text view on below line. pinCodeDetailsTV.setText(\"Details of pin code is : \\n\" + \"District is : \" + district + \"\\n\" + \"State : \" + state + \"\\n\" + \"Country : \" + country); } } catch (JSONException e) { // if we gets any error then it // will be printed in log cat. e.printStackTrace(); pinCodeDetailsTV.setText(\"Pin code is not valid\"); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // below method is called if we get // any error while fetching data from API. // below line is use to display an error message. Toast.makeText(MainActivity.this, \"Pin code is not valid.\", Toast.LENGTH_SHORT).show(); pinCodeDetailsTV.setText(\"Pin code is not valid\"); } }); // below line is use for adding object // request to our request queue. queue.add(objectRequest); }}", "e": 34914, "s": 28968, "text": null }, { "code": null, "e": 34975, "s": 34914, "text": "Step 5: Add permission for the internet in the Manifest file" }, { "code": null, "e": 35060, "s": 34975, "text": "Navigate to the app > AndroidManifest.xml file and add the below permissions to it. " }, { "code": null, "e": 35122, "s": 35060, "text": "<uses-permission android:name=”android.permission.INTERNET”/>" }, { "code": null, "e": 35130, "s": 35122, "text": "android" }, { "code": null, "e": 35154, "s": 35130, "text": "Technical Scripter 2020" }, { "code": null, "e": 35162, "s": 35154, "text": "Android" }, { "code": null, "e": 35167, "s": 35162, "text": "Java" }, { "code": null, "e": 35186, "s": 35167, "text": "Technical Scripter" }, { "code": null, "e": 35191, "s": 35186, "text": "Java" }, { "code": null, "e": 35199, "s": 35191, "text": "Android" }, { "code": null, "e": 35297, "s": 35199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35306, "s": 35297, "text": "Comments" }, { "code": null, "e": 35319, "s": 35306, "text": "Old Comments" }, { "code": null, "e": 35358, "s": 35319, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35408, "s": 35358, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 35459, "s": 35408, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 35497, "s": 35459, "text": "Android Listview in Java with Example" }, { "code": null, "e": 35539, "s": 35497, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35554, "s": 35539, "text": "Arrays in Java" }, { "code": null, "e": 35598, "s": 35554, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35620, "s": 35598, "text": "For-each loop in Java" }, { "code": null, "e": 35645, "s": 35620, "text": "Reverse a string in Java" } ]
How to apply one sample t-test on all columns of an R data frame?
When we want to apply t-test on columns of a data frame then we generally perform them one by one by accessing the appropriate columns but if we want to apply the test on all columns of the data frame then we can take the help of sapply function. For example, if we have a data frame called df that contains multiple columns then the one sample-test can be applied to all columns using the command sapply(df,t.test). Consider the below data frame − Live Demo > x1<-rnorm(20) > x2<-rnorm(20,5,2.5) > x3<-rnorm(20,5,0.31) > df1<-data.frame(x1,x2,x3) > df1 x1 x2 x3 1 -2.25470472 2.730284 5.257561 2 0.31811059 4.978190 4.799871 3 0.53974937 5.247124 4.533089 4 0.04855004 4.285427 5.187038 5 0.23913269 6.424229 5.335241 6 1.41318324 5.184035 5.638625 7 -1.19378598 0.729062 5.065400 8 0.53453582 10.548991 4.349061 9 -0.90284652 2.019270 5.479600 10 -1.85263184 5.272444 5.148048 11 0.20052589 7.367680 4.806746 12 -0.67952841 7.784398 4.908527 13 1.34338527 4.627357 5.090057 14 0.50015711 3.983630 4.370341 15 1.77264005 3.099567 4.930903 16 -0.55921578 -1.081910 5.597464 17 -0.46257623 4.273301 5.045864 18 0.97870030 6.683427 5.051728 19 -0.96029384 10.277885 4.978401 20 -1.33514505 5.534050 4.558999 Applying t-test on all columns of df1 − > sapply(df1,t.test) x1 x2 x3 statistic -0.4687486 7.892499 60.87446 parameter 19 19 19 p.value 0.6445828 2.047736e-07 3.024457e-23 conf.int Numeric,2 Numeric,2 Numeric,2 estimate -0.1156029 4.998422 5.006628 null.value 0 0 0 stderr 0.2466203 0.633313 0.08224513 alternative "two.sided" "two.sided" "two.sided" method "One Sample t-test" "One Sample t-test" "One Sample t-test" data.name "X[[i]]" "X[[i]]" "X[[i]]" Live Demo > y1<-rpois(20,5) > y2<-rpois(20,2) > y3<-rpois(20,5) > df2<-data.frame(y1,y2,y3) > df2 y1 y2 y3 1 4 2 4 2 4 1 2 3 6 1 5 4 4 3 7 5 5 4 2 6 4 4 5 7 7 3 6 8 4 0 8 9 3 0 4 10 4 4 4 11 5 2 3 12 8 2 7 13 4 4 3 14 8 1 6 15 7 3 7 16 3 2 6 17 4 0 1 18 1 3 3 19 2 3 2 20 3 4 4 Applying t-test on all columns of df2 − > sapply(df2,t.test) y1 y2 y3 statistic 10.71684 7.254174 9.888889 parameter 19 19 19 p.value 1.706058e-09 6.946248e-07 6.298981e-09 conf.int Numeric,2 Numeric,2 Numeric,2 estimate 4.5 2.3 4.45 null.value 0 0 0 stderr 0.4198997 0.3170589 0.45 alternative "two.sided" "two.sided" "two.sided" method "One Sample t-test" "One Sample t-test" "One Sample t-test" data.name "X[[i]]" "X[[i]]" "X[[i]]"
[ { "code": null, "e": 1479, "s": 1062, "text": "When we want to apply t-test on columns of a data frame then we generally perform them one by one by accessing the appropriate columns but if we want to apply the test on all columns of the data frame then we can take the help of sapply function. For example, if we have a data frame called df that contains multiple columns then the one sample-test can be applied to all columns using the command sapply(df,t.test)." }, { "code": null, "e": 1511, "s": 1479, "text": "Consider the below data frame −" }, { "code": null, "e": 1521, "s": 1511, "text": "Live Demo" }, { "code": null, "e": 1616, "s": 1521, "text": "> x1<-rnorm(20)\n> x2<-rnorm(20,5,2.5)\n> x3<-rnorm(20,5,0.31)\n> df1<-data.frame(x1,x2,x3)\n> df1" }, { "code": null, "e": 2330, "s": 1616, "text": " x1 x2 x3\n1 -2.25470472 2.730284 5.257561\n2 0.31811059 4.978190 4.799871\n3 0.53974937 5.247124 4.533089\n4 0.04855004 4.285427 5.187038\n5 0.23913269 6.424229 5.335241\n6 1.41318324 5.184035 5.638625\n7 -1.19378598 0.729062 5.065400\n8 0.53453582 10.548991 4.349061\n9 -0.90284652 2.019270 5.479600\n10 -1.85263184 5.272444 5.148048\n11 0.20052589 7.367680 4.806746\n12 -0.67952841 7.784398 4.908527\n13 1.34338527 4.627357 5.090057\n14 0.50015711 3.983630 4.370341\n15 1.77264005 3.099567 4.930903\n16 -0.55921578 -1.081910 5.597464\n17 -0.46257623 4.273301 5.045864\n18 0.97870030 6.683427 5.051728\n19 -0.96029384 10.277885 4.978401\n20 -1.33514505 5.534050 4.558999" }, { "code": null, "e": 2370, "s": 2330, "text": "Applying t-test on all columns of df1 −" }, { "code": null, "e": 2391, "s": 2370, "text": "> sapply(df1,t.test)" }, { "code": null, "e": 3168, "s": 2391, "text": " x1 x2 x3 \nstatistic -0.4687486 7.892499 60.87446 \nparameter 19 19 19 \np.value 0.6445828 2.047736e-07 3.024457e-23 \nconf.int Numeric,2 Numeric,2 Numeric,2 \nestimate -0.1156029 4.998422 5.006628 \nnull.value 0 0 0 \nstderr 0.2466203 0.633313 0.08224513 \nalternative \"two.sided\" \"two.sided\" \"two.sided\" \nmethod \"One Sample t-test\" \"One Sample t-test\" \"One Sample t-test\"\ndata.name \"X[[i]]\" \"X[[i]]\" \"X[[i]]\" " }, { "code": null, "e": 3178, "s": 3168, "text": "Live Demo" }, { "code": null, "e": 3266, "s": 3178, "text": "> y1<-rpois(20,5)\n> y2<-rpois(20,2)\n> y3<-rpois(20,5)\n> df2<-data.frame(y1,y2,y3)\n> df2" }, { "code": null, "e": 3518, "s": 3266, "text": " y1 y2 y3\n1 4 2 4\n2 4 1 2\n3 6 1 5\n4 4 3 7\n5 5 4 2\n6 4 4 5\n7 7 3 6\n8 4 0 8\n9 3 0 4\n10 4 4 4\n11 5 2 3\n12 8 2 7\n13 4 4 3\n14 8 1 6\n15 7 3 7\n16 3 2 6\n17 4 0 1\n18 1 3 3\n19 2 3 2\n20 3 4 4" }, { "code": null, "e": 3558, "s": 3518, "text": "Applying t-test on all columns of df2 −" }, { "code": null, "e": 3579, "s": 3558, "text": "> sapply(df2,t.test)" }, { "code": null, "e": 4356, "s": 3579, "text": " y1 y2 y3 \nstatistic 10.71684 7.254174 9.888889 \nparameter 19 19 19 \np.value 1.706058e-09 6.946248e-07 6.298981e-09 \nconf.int Numeric,2 Numeric,2 Numeric,2 \nestimate 4.5 2.3 4.45 \nnull.value 0 0 0 \nstderr 0.4198997 0.3170589 0.45 \nalternative \"two.sided\" \"two.sided\" \"two.sided\" \nmethod \"One Sample t-test\" \"One Sample t-test\" \"One Sample t-test\"\ndata.name \"X[[i]]\" \"X[[i]]\" \"X[[i]]\" " } ]
Pascal - Environment Set Up
There are several Pascal compilers and interpreters available for general use. Among these are − Turbo Pascal − provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86, DOS, Windows and Macintosh. Turbo Pascal − provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86, DOS, Windows and Macintosh. Delphi − provides compilers for running Object Pascal and generates native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to build support for the Linux and Android operating system. Delphi − provides compilers for running Object Pascal and generates native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to build support for the Linux and Android operating system. Free Pascal − it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms. Free Pascal − it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms. Turbo51 − It is a free Pascal compiler for the 8051 family of microcontrollers, with Turbo Pascal 7 syntax. Turbo51 − It is a free Pascal compiler for the 8051 family of microcontrollers, with Turbo Pascal 7 syntax. Oxygene − It is an Object Pascal compiler for the .NET and Mono platforms. Oxygene − It is an Object Pascal compiler for the .NET and Mono platforms. GNU Pascal (GPC) − It is a Pascal compiler composed of a front end to GNU Compiler Collection. GNU Pascal (GPC) − It is a Pascal compiler composed of a front end to GNU Compiler Collection. We will be using Free Pascal in these tutorials. You can download Free Pascal for your operating system from the link: Download Free Pascal The Linux distribution of Free Pascal comes in three forms − a tar.gz version, also available as separate files. a tar.gz version, also available as separate files. a .rpm (Red Hat Package Manager) version. a .rpm (Red Hat Package Manager) version. a .deb (Debian) version. a .deb (Debian) version. Installation code for the .rpm version:: rpm -i fpc-X.Y.Z-N.ARCH.rpm Where X.Y.Z is the version number of the .rpm file, and ARCH is one of the supported architectures (i386, x86_64, etc.). Installation code for the Debian version (like Ubuntu): dpkg -i fpc-XXX.deb Where XXX is the version number of the .deb file. For details read: Free Pascal Installation Guide If you use Mac OS X, the easiest way to use Free Pascal is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use the Free Pascal compiler. For Windows, you will download the Windows installer, setup.exe. This is a usual installation program. You need to take the following steps for installation − Select a directory. Select a directory. Select parts of the package you want to install. Select parts of the package you want to install. Optionally choose to associate the .pp or .pas extensions with the Free Pascal IDE. Optionally choose to associate the .pp or .pas extensions with the Free Pascal IDE. For details read: Free Pascal Installation Guide This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux or UNIX. The files you create with your editor are called source files and contain program source code. The source files for Pascal programs are typically named with the extension .pas. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2180, "s": 2083, "text": "There are several Pascal compilers and interpreters available for general use. Among these are −" }, { "code": null, "e": 2298, "s": 2180, "text": "Turbo Pascal − provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86, DOS, Windows and Macintosh." }, { "code": null, "e": 2416, "s": 2298, "text": "Turbo Pascal − provides an IDE and compiler for running Pascal programs on CP/M, CP/M-86, DOS, Windows and Macintosh." }, { "code": null, "e": 2663, "s": 2416, "text": "Delphi − provides compilers for running Object Pascal and generates native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to build support for the Linux and Android operating system." }, { "code": null, "e": 2910, "s": 2663, "text": "Delphi − provides compilers for running Object Pascal and generates native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS. Embarcadero is planning to build support for the Linux and Android operating system." }, { "code": null, "e": 3163, "s": 2910, "text": "Free Pascal − it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms." }, { "code": null, "e": 3416, "s": 3163, "text": "Free Pascal − it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms." }, { "code": null, "e": 3524, "s": 3416, "text": "Turbo51 − It is a free Pascal compiler for the 8051 family of microcontrollers, with Turbo Pascal 7 syntax." }, { "code": null, "e": 3632, "s": 3524, "text": "Turbo51 − It is a free Pascal compiler for the 8051 family of microcontrollers, with Turbo Pascal 7 syntax." }, { "code": null, "e": 3707, "s": 3632, "text": "Oxygene − It is an Object Pascal compiler for the .NET and Mono platforms." }, { "code": null, "e": 3782, "s": 3707, "text": "Oxygene − It is an Object Pascal compiler for the .NET and Mono platforms." }, { "code": null, "e": 3877, "s": 3782, "text": "GNU Pascal (GPC) − It is a Pascal compiler composed of a front end to GNU Compiler Collection." }, { "code": null, "e": 3972, "s": 3877, "text": "GNU Pascal (GPC) − It is a Pascal compiler composed of a front end to GNU Compiler Collection." }, { "code": null, "e": 4112, "s": 3972, "text": "We will be using Free Pascal in these tutorials. You can download Free Pascal for your operating system from the link: Download Free Pascal" }, { "code": null, "e": 4173, "s": 4112, "text": "The Linux distribution of Free Pascal comes in three forms −" }, { "code": null, "e": 4225, "s": 4173, "text": "a tar.gz version, also available as separate files." }, { "code": null, "e": 4277, "s": 4225, "text": "a tar.gz version, also available as separate files." }, { "code": null, "e": 4319, "s": 4277, "text": "a .rpm (Red Hat Package Manager) version." }, { "code": null, "e": 4361, "s": 4319, "text": "a .rpm (Red Hat Package Manager) version." }, { "code": null, "e": 4386, "s": 4361, "text": "a .deb (Debian) version." }, { "code": null, "e": 4411, "s": 4386, "text": "a .deb (Debian) version." }, { "code": null, "e": 4453, "s": 4411, "text": "Installation code for the .rpm version:: " }, { "code": null, "e": 4481, "s": 4453, "text": "rpm -i fpc-X.Y.Z-N.ARCH.rpm" }, { "code": null, "e": 4602, "s": 4481, "text": "Where X.Y.Z is the version number of the .rpm file, and ARCH is one of the supported architectures (i386, x86_64, etc.)." }, { "code": null, "e": 4659, "s": 4602, "text": "Installation code for the Debian version (like Ubuntu): " }, { "code": null, "e": 4679, "s": 4659, "text": "dpkg -i fpc-XXX.deb" }, { "code": null, "e": 4730, "s": 4679, "text": "Where XXX is the version number of the .deb file." }, { "code": null, "e": 4779, "s": 4730, "text": "For details read: Free Pascal Installation Guide" }, { "code": null, "e": 5032, "s": 4779, "text": "If you use Mac OS X, the easiest way to use Free Pascal is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use the Free Pascal compiler." }, { "code": null, "e": 5191, "s": 5032, "text": "For Windows, you will download the Windows installer, setup.exe. This is a usual installation program. You need to take the following steps for installation −" }, { "code": null, "e": 5211, "s": 5191, "text": "Select a directory." }, { "code": null, "e": 5231, "s": 5211, "text": "Select a directory." }, { "code": null, "e": 5280, "s": 5231, "text": "Select parts of the package you want to install." }, { "code": null, "e": 5329, "s": 5280, "text": "Select parts of the package you want to install." }, { "code": null, "e": 5413, "s": 5329, "text": "Optionally choose to associate the .pp or .pas extensions with the Free Pascal IDE." }, { "code": null, "e": 5497, "s": 5413, "text": "Optionally choose to associate the .pp or .pas extensions with the Free Pascal IDE." }, { "code": null, "e": 5546, "s": 5497, "text": "For details read: Free Pascal Installation Guide" }, { "code": null, "e": 5690, "s": 5546, "text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 5871, "s": 5690, "text": "Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux or UNIX." }, { "code": null, "e": 6048, "s": 5871, "text": "The files you create with your editor are called source files and contain program source code. The source files for Pascal programs are typically named with the extension .pas." }, { "code": null, "e": 6240, "s": 6048, "text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it." }, { "code": null, "e": 6275, "s": 6240, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6298, "s": 6275, "text": " Stone River ELearning" }, { "code": null, "e": 6305, "s": 6298, "text": " Print" }, { "code": null, "e": 6316, "s": 6305, "text": " Add Notes" } ]
How to display Hexadecimal Values in NumericUpDown in C#? - GeeksforGeeks
29 Jul, 2019 In Windows Forms, NumericUpDown control is used to provide a Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can display values in hexadecimal format in the up-down control using Hexadecimal Property.If the value of this property is set to true, then the up-down control displays the values in hexadecimal format. And if the value of this property is set to false, then the up-down control does not display the values in hexadecimal format. The default value of this property is false. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the hexadecimal values in the NumericUpDown as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the hexadecimal values in the NumericUpDown as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set in the hexadecimal format in the NumericUpDown control programmatically with the help of given syntax: public bool Hexadecimal { get; set; } The value of this property is of System.Boolean type, either true or false. The following steps show how to set the hexadecimal values in the NumericUpDown dynamically: Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown NumericUpDown n = new NumericUpDown(); // Creating a NumericUpDown NumericUpDown n = new NumericUpDown(); Step 2: After creating NumericUpDown, set the Hexadecimal property of the NumericUpDown provided by the NumericUpDown class.// Setting the Hexadecimal values n.Hexadecimal = true; // Setting the Hexadecimal values n.Hexadecimal = true; Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown control on the form this.Controls.Add(n); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp44 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 25); l1.Text = "Example"; l1.Font = new Font("Bodoni MT", 16); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Select value:"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.Increment = 1; n.Hexadecimal = true; // Adding this control // to the form this.Controls.Add(n); }}}Output: // Adding NumericUpDown control on the form this.Controls.Add(n); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp44 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 25); l1.Text = "Example"; l1.Font = new Font("Bodoni MT", 16); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Select value:"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.Increment = 1; n.Hexadecimal = true; // Adding this control // to the form this.Controls.Add(n); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# Top 50 C# Interview Questions & Answers Partial Classes in C# HashSet in C# with Examples C# | Inheritance C# | How to insert an element in an Array? C# | List Class Lambda Expressions in C# C# | Generics - Introduction What is Regular Expression in C#?
[ { "code": null, "e": 24222, "s": 24194, "text": "\n29 Jul, 2019" }, { "code": null, "e": 24954, "s": 24222, "text": "In Windows Forms, NumericUpDown control is used to provide a Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can display values in hexadecimal format in the up-down control using Hexadecimal Property.If the value of this property is set to true, then the up-down control displays the values in hexadecimal format. And if the value of this property is set to false, then the up-down control does not display the values in hexadecimal format. The default value of this property is false. You can set this property in two different ways:" }, { "code": null, "e": 25076, "s": 24954, "text": "1. Design-Time: It is the easiest way to set the hexadecimal values in the NumericUpDown as shown in the following steps:" }, { "code": null, "e": 25192, "s": 25076, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 25304, "s": 25192, "text": "Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 25471, "s": 25304, "text": "Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the hexadecimal values in the NumericUpDown as shown in the below image:Output:" }, { "code": null, "e": 25479, "s": 25471, "text": "Output:" }, { "code": null, "e": 25674, "s": 25479, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set in the hexadecimal format in the NumericUpDown control programmatically with the help of given syntax:" }, { "code": null, "e": 25712, "s": 25674, "text": "public bool Hexadecimal { get; set; }" }, { "code": null, "e": 25881, "s": 25712, "text": "The value of this property is of System.Boolean type, either true or false. The following steps show how to set the hexadecimal values in the NumericUpDown dynamically:" }, { "code": null, "e": 26057, "s": 25881, "text": "Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n" }, { "code": null, "e": 26125, "s": 26057, "text": "// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n" }, { "code": null, "e": 26307, "s": 26125, "text": "Step 2: After creating NumericUpDown, set the Hexadecimal property of the NumericUpDown provided by the NumericUpDown class.// Setting the Hexadecimal values\nn.Hexadecimal = true; \n" }, { "code": null, "e": 26365, "s": 26307, "text": "// Setting the Hexadecimal values\nn.Hexadecimal = true; \n" }, { "code": null, "e": 27883, "s": 26365, "text": "Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown control on the form\nthis.Controls.Add(n);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp44 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 25); l1.Text = \"Example\"; l1.Font = new Font(\"Bodoni MT\", 16); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Select value:\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.Increment = 1; n.Hexadecimal = true; // Adding this control // to the form this.Controls.Add(n); }}}Output:" }, { "code": null, "e": 27950, "s": 27883, "text": "// Adding NumericUpDown control on the form\nthis.Controls.Add(n);\n" }, { "code": null, "e": 27959, "s": 27950, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp44 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 25); l1.Text = \"Example\"; l1.Font = new Font(\"Bodoni MT\", 16); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Select value:\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.Increment = 1; n.Hexadecimal = true; // Adding this control // to the form this.Controls.Add(n); }}}", "e": 29306, "s": 27959, "text": null }, { "code": null, "e": 29314, "s": 29306, "text": "Output:" }, { "code": null, "e": 29345, "s": 29314, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 29348, "s": 29345, "text": "C#" }, { "code": null, "e": 29446, "s": 29348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29455, "s": 29446, "text": "Comments" }, { "code": null, "e": 29468, "s": 29455, "text": "Old Comments" }, { "code": null, "e": 29491, "s": 29468, "text": "Extension Method in C#" }, { "code": null, "e": 29531, "s": 29491, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29553, "s": 29531, "text": "Partial Classes in C#" }, { "code": null, "e": 29581, "s": 29553, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29598, "s": 29581, "text": "C# | Inheritance" }, { "code": null, "e": 29641, "s": 29598, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 29657, "s": 29641, "text": "C# | List Class" }, { "code": null, "e": 29682, "s": 29657, "text": "Lambda Expressions in C#" }, { "code": null, "e": 29711, "s": 29682, "text": "C# | Generics - Introduction" } ]
Get current time and date on Android
As per Oracle documentation, SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. In this example, we have imported simple date format class from java as shown below - import java.text.SimpleDateFormat; import java.util.Date; Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns: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"> <TextView android:id="@+id/date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:textSize="30sp" android:layout_marginBottom="36dp" /> </RelativeLayout> In the above code, we have given text view, it going to print the current date on the window manager. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView=findViewById(R.id.date); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"); String currentDateandTime = sdf.format(new Date()); textView.setText(currentDateandTime); } } In the above code we are calling SimpleDateFormat and from the simpledateformat, we are accessing the current date in the string. There are so many date format are available. For more reference Click here. Step 4 − No need to change manifest.xml. 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 an android studio, open one of your project's activity files and click Run from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above example, it contains a current date and time. Click here to download the project code
[ { "code": null, "e": 1277, "s": 1062, "text": "As per Oracle documentation, SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. In this example, we have imported simple date format class from java as shown below -" }, { "code": null, "e": 1335, "s": 1277, "text": "import java.text.SimpleDateFormat;\nimport java.util.Date;" }, { "code": null, "e": 1464, "s": 1335, "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": 1529, "s": 1464, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2120, "s": 1529, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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 <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30sp\"\n android:layout_marginBottom=\"36dp\" />\n</RelativeLayout>" }, { "code": null, "e": 2222, "s": 2120, "text": "In the above code, we have given text view, it going to print the current date on the window manager." }, { "code": null, "e": 2279, "s": 2222, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3035, "s": 2279, "text": "package com.example.andy.myapplication;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class MainActivity extends AppCompatActivity {\n @TargetApi(Build.VERSION_CODES.O)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView=findViewById(R.id.date);\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy.MM.dd G 'at' HH:mm:ss z\");\n String currentDateandTime = sdf.format(new Date());\n textView.setText(currentDateandTime);\n }\n}" }, { "code": null, "e": 3241, "s": 3035, "text": "In the above code we are calling SimpleDateFormat and from the simpledateformat, we are accessing the current date in the string. There are so many date format are available. For more reference Click here." }, { "code": null, "e": 3282, "s": 3241, "text": "Step 4 − No need to change manifest.xml." }, { "code": null, "e": 3626, "s": 3282, "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 an android studio, open one of your project's activity files and click Run 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": 3685, "s": 3626, "text": "In the above example, it contains a current date and time." }, { "code": null, "e": 3725, "s": 3685, "text": "Click here to download the project code" } ]
Loading Ridiculously Large Excel Files in Python | by Yaakov Bressler | Towards Data Science
Sometimes you need to work with .xls or .xlx files. In the event that they’re larger than 1M rows, excel will either load the first 1M rows or crash. This article will demonstrate how to load such files in python. Before we dive in, here’s some background information on how spreadsheets work on the backend. Spreadsheets store data as row-wise arrays consisting of column keys with cell values.1 The functionality of spreadsheets deride from their behavior as a directed acyclic graph (DAG) which allow cyclical (arbitrary) relational functionality.2 This is best demonstrated with the illustration below which shows how some cell values are derived from their relationships to others. Current size limits for excel are 1,048,576 rows by 16,384 columns — owing to memory resources. To be clear, data can be stored in an excel file which breaks these rules — but will not function in the excel program. If you were to open an excel file of 1.25M rows, the program will drop all data below row 1M. The easiest answer is that the file itself is easily shareable and provides better encryption than csv, txt, or json structure. Also, excel’s UI is incredibly user friendly and makes inspecting data really easy. Some specific situations where I’ve received massive excel files: External access not-allowed to database — existing user exports data to encrypted excel format and shares. Data is being collected/generated by non-technical team. (Ex. agile marketing project.) Data needs to be inspected by legal / compliance team before being shared. Programmatic analysis or data manipulation has the advantage of: reproducibility automation efficiency reduction of spreadsheet risks To prove this challenge and solution, let’s first create a massive excel file. Assuming you have python installed on your computer, run the following command on your terminal: pip install pandas openpyxl namegenerator I included several data types (string, float, datetime) to make loading non-trivial. Note: This will crash your machine if you have less than 8GB system memory. My file is 210,714,241 bites (210 MB). Inspect your file with the code below to get the actual size. f_path = "my_ridiculous_excel_file.xlsx"os.path.getsize(f_path) Interestingly, csv format takes up significantly larger space — 324,425,683 bites (324 MB). Larger data size — but is serialized. (If you have any clue why / how this is happening, please leave as a comment.) Loading excel files is a memory intensive action. The entire file is loaded into memory >> then each row is loaded into memory >> row is structured into a numpy array of key value pairs>> row is converted to a pandas Series >> rows are concatenated to a dataframe object. data_path = "data/my_excel_file.xls"df = pd.read_excel(data_path, index_col=0, engine="openpyxl") The above command took my computer 14 minutes to load. That’s way too long... Is supposed to be faster than openpxyl but doesn’t work for > 1M rows of data... The file is loaded to memory but data is loaded through a generator which allows mapped-retrieval of values. Still slow but a tiny drop faster than Pandas. Openpyxl Documentation: Memory use is fairly high in comparison with other libraries and applications and is approximately 50 times the original file size. wb = openpyxl.load_workbook(filename=data_path, read_only=True)ws = wb.active# Convert to a dfdf = pd.DataFrame(ws) The above command took my computer 11 minutes 44 seconds to load. wb = openpyxl.load_workbook(filename=data_path, read_only=True)ws = wb.active# Load the rowsrows = ws.rowsfirst_row = [cell.value for cell in next(rows)]# Load the datadata = []for row in rows: record = {} for key, cell in zip(first_row, row): record[key] = cell.value data.append(record)# Convert to a dfdf = pd.DataFrame(data) The above command took my computer 11 minutes 8 seconds to load. Slightly better than the read_excel method, but still slow. Unfortunately, couldn’t load. Received the following assertion error: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xlrd/xlsx.py in do_row(self, row_elem) 635 self.rowx = int(row_number) - 1 636 explicit_row_number = 1--> 637 assert 0 <= self.rowx < X12_MAX_ROWS 638 rowx = self.rowx 639 colx = -1 Of what I was able to surmise from StackOverflow, this error is likely arising from exceeding allowed dimensions of the data or a non-allowed character — the latter of which is not likely. If you’re working with massive excel files, try not to. They’re very difficult data structures to process — especially when your data is large. Consider serialized formats such as parquet, csv, json, or pickle (python’s binary stream). If the data you’re working with is regularly larger than 1M rows, consider using a map-reduce tool — such as Dask, Apache Spark, or Apache Hadoop. Answer to What Are The Data Structures Behind A Spreadsheet?. Software Engineering Stack Exchange. [Accessed 10 June 2020].Ack! Cell, Tree, DAG. Cs.gmu.edu. [Accessed 10 June 2020]. Answer to What Are The Data Structures Behind A Spreadsheet?. Software Engineering Stack Exchange. [Accessed 10 June 2020]. Ack! Cell, Tree, DAG. Cs.gmu.edu. [Accessed 10 June 2020]. Special thanks to: Aaron Hall, Hervé Yav, Ephraim Klestzick, Martin Durant
[ { "code": null, "e": 386, "s": 172, "text": "Sometimes you need to work with .xls or .xlx files. In the event that they’re larger than 1M rows, excel will either load the first 1M rows or crash. This article will demonstrate how to load such files in python." }, { "code": null, "e": 481, "s": 386, "text": "Before we dive in, here’s some background information on how spreadsheets work on the backend." }, { "code": null, "e": 569, "s": 481, "text": "Spreadsheets store data as row-wise arrays consisting of column keys with cell values.1" }, { "code": null, "e": 859, "s": 569, "text": "The functionality of spreadsheets deride from their behavior as a directed acyclic graph (DAG) which allow cyclical (arbitrary) relational functionality.2 This is best demonstrated with the illustration below which shows how some cell values are derived from their relationships to others." }, { "code": null, "e": 1075, "s": 859, "text": "Current size limits for excel are 1,048,576 rows by 16,384 columns — owing to memory resources. To be clear, data can be stored in an excel file which breaks these rules — but will not function in the excel program." }, { "code": null, "e": 1169, "s": 1075, "text": "If you were to open an excel file of 1.25M rows, the program will drop all data below row 1M." }, { "code": null, "e": 1381, "s": 1169, "text": "The easiest answer is that the file itself is easily shareable and provides better encryption than csv, txt, or json structure. Also, excel’s UI is incredibly user friendly and makes inspecting data really easy." }, { "code": null, "e": 1447, "s": 1381, "text": "Some specific situations where I’ve received massive excel files:" }, { "code": null, "e": 1554, "s": 1447, "text": "External access not-allowed to database — existing user exports data to encrypted excel format and shares." }, { "code": null, "e": 1642, "s": 1554, "text": "Data is being collected/generated by non-technical team. (Ex. agile marketing project.)" }, { "code": null, "e": 1717, "s": 1642, "text": "Data needs to be inspected by legal / compliance team before being shared." }, { "code": null, "e": 1782, "s": 1717, "text": "Programmatic analysis or data manipulation has the advantage of:" }, { "code": null, "e": 1798, "s": 1782, "text": "reproducibility" }, { "code": null, "e": 1809, "s": 1798, "text": "automation" }, { "code": null, "e": 1820, "s": 1809, "text": "efficiency" }, { "code": null, "e": 1851, "s": 1820, "text": "reduction of spreadsheet risks" }, { "code": null, "e": 1930, "s": 1851, "text": "To prove this challenge and solution, let’s first create a massive excel file." }, { "code": null, "e": 2027, "s": 1930, "text": "Assuming you have python installed on your computer, run the following command on your terminal:" }, { "code": null, "e": 2069, "s": 2027, "text": "pip install pandas openpyxl namegenerator" }, { "code": null, "e": 2154, "s": 2069, "text": "I included several data types (string, float, datetime) to make loading non-trivial." }, { "code": null, "e": 2230, "s": 2154, "text": "Note: This will crash your machine if you have less than 8GB system memory." }, { "code": null, "e": 2331, "s": 2230, "text": "My file is 210,714,241 bites (210 MB). Inspect your file with the code below to get the actual size." }, { "code": null, "e": 2395, "s": 2331, "text": "f_path = \"my_ridiculous_excel_file.xlsx\"os.path.getsize(f_path)" }, { "code": null, "e": 2604, "s": 2395, "text": "Interestingly, csv format takes up significantly larger space — 324,425,683 bites (324 MB). Larger data size — but is serialized. (If you have any clue why / how this is happening, please leave as a comment.)" }, { "code": null, "e": 2876, "s": 2604, "text": "Loading excel files is a memory intensive action. The entire file is loaded into memory >> then each row is loaded into memory >> row is structured into a numpy array of key value pairs>> row is converted to a pandas Series >> rows are concatenated to a dataframe object." }, { "code": null, "e": 2974, "s": 2876, "text": "data_path = \"data/my_excel_file.xls\"df = pd.read_excel(data_path, index_col=0, engine=\"openpyxl\")" }, { "code": null, "e": 3052, "s": 2974, "text": "The above command took my computer 14 minutes to load. That’s way too long..." }, { "code": null, "e": 3133, "s": 3052, "text": "Is supposed to be faster than openpxyl but doesn’t work for > 1M rows of data..." }, { "code": null, "e": 3289, "s": 3133, "text": "The file is loaded to memory but data is loaded through a generator which allows mapped-retrieval of values. Still slow but a tiny drop faster than Pandas." }, { "code": null, "e": 3445, "s": 3289, "text": "Openpyxl Documentation: Memory use is fairly high in comparison with other libraries and applications and is approximately 50 times the original file size." }, { "code": null, "e": 3561, "s": 3445, "text": "wb = openpyxl.load_workbook(filename=data_path, read_only=True)ws = wb.active# Convert to a dfdf = pd.DataFrame(ws)" }, { "code": null, "e": 3627, "s": 3561, "text": "The above command took my computer 11 minutes 44 seconds to load." }, { "code": null, "e": 3972, "s": 3627, "text": "wb = openpyxl.load_workbook(filename=data_path, read_only=True)ws = wb.active# Load the rowsrows = ws.rowsfirst_row = [cell.value for cell in next(rows)]# Load the datadata = []for row in rows: record = {} for key, cell in zip(first_row, row): record[key] = cell.value data.append(record)# Convert to a dfdf = pd.DataFrame(data)" }, { "code": null, "e": 4097, "s": 3972, "text": "The above command took my computer 11 minutes 8 seconds to load. Slightly better than the read_excel method, but still slow." }, { "code": null, "e": 4127, "s": 4097, "text": "Unfortunately, couldn’t load." }, { "code": null, "e": 4167, "s": 4127, "text": "Received the following assertion error:" }, { "code": null, "e": 4488, "s": 4167, "text": "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xlrd/xlsx.py in do_row(self, row_elem) 635 self.rowx = int(row_number) - 1 636 explicit_row_number = 1--> 637 assert 0 <= self.rowx < X12_MAX_ROWS 638 rowx = self.rowx 639 colx = -1" }, { "code": null, "e": 4677, "s": 4488, "text": "Of what I was able to surmise from StackOverflow, this error is likely arising from exceeding allowed dimensions of the data or a non-allowed character — the latter of which is not likely." }, { "code": null, "e": 4913, "s": 4677, "text": "If you’re working with massive excel files, try not to. They’re very difficult data structures to process — especially when your data is large. Consider serialized formats such as parquet, csv, json, or pickle (python’s binary stream)." }, { "code": null, "e": 5060, "s": 4913, "text": "If the data you’re working with is regularly larger than 1M rows, consider using a map-reduce tool — such as Dask, Apache Spark, or Apache Hadoop." }, { "code": null, "e": 5242, "s": 5060, "text": "Answer to What Are The Data Structures Behind A Spreadsheet?. Software Engineering Stack Exchange. [Accessed 10 June 2020].Ack! Cell, Tree, DAG. Cs.gmu.edu. [Accessed 10 June 2020]." }, { "code": null, "e": 5366, "s": 5242, "text": "Answer to What Are The Data Structures Behind A Spreadsheet?. Software Engineering Stack Exchange. [Accessed 10 June 2020]." }, { "code": null, "e": 5425, "s": 5366, "text": "Ack! Cell, Tree, DAG. Cs.gmu.edu. [Accessed 10 June 2020]." } ]
How to Get Random Elements from Java HashSet?
07 Jan, 2021 Unlike List classes, the HashSet class does not provide any methods using which we can get the elements using their index. It makes it difficult to get random elements from it using the index. We need to get random elements from HashSet, which can be done by either of the two ways: By converting it to an arrayUsing an Iterator or a for loop By converting it to an array Using an Iterator or a for loop Example: Input: hs.add(11); hs.add(24); hs.add(34); hs.add(43); hs.add(55); hs.add(66); hs.add(72); hs.add(80); hs.add(99); Output: Random element: 99 Method 1: By converting to an array. Firstly convert HashSet into an array and then access the random element from it. Then we will create an object of Random class and will call the nextInt() method of that class which will give us any random number less than or equal to the size of the HashSet. And then using an array we will simply print the element present at that index. Java // Java program to get random elements from HashSet// using an array import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // creating the HashSet Set<Integer> hs = new HashSet<Integer>(); hs.add(11); hs.add(24); hs.add(34); hs.add(43); hs.add(55); hs.add(66); hs.add(72); hs.add(80); hs.add(99); // convert HashSet to an array Integer[] arrayNumbers = hs.toArray(new Integer[hs.size()]); // generate a random number Random rndm = new Random(); // this will generate a random number between 0 and // HashSet.size - 1 int rndmNumber = rndm.nextInt(hs.size()); // get the element at random number index System.out.println("Random element: " + arrayNumbers[rndmNumber]); }} Random element: 11 Method 2: Using an Iterator or a for loop In order to get random elements from the HashSet object, we need to generate a random number between 0 (inclusive) and the size of the HashSet (exclusive). And then iterate through the set till we reach the element located at the random number position as given below. In this approach, we will get the element at a random index using an Iterator. Java // Java program to get random elements from HashSet// using an Iterator import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Set<Integer> hs = new HashSet<Integer>(); hs.add(11); hs.add(24); hs.add(34); hs.add(43); hs.add(55); hs.add(66); hs.add(72); hs.add(80); hs.add(99); System.out.println("Random element: " + getRandomElement(hs)); } private static <E> E getRandomElement(Set<? extends E> set) { Random random = new Random(); // Generate a random number using nextInt // method of the Random class. int randomNumber = random.nextInt(set.size()); Iterator<? extends E> iterator = set.iterator(); int currentIndex = 0; E randomElement = null; // iterate the HashSet while (iterator.hasNext()) { randomElement = iterator.next(); // if current index is equal to random number if (currentIndex == randomNumber) return randomElement; // increase the current index currentIndex++; } return randomElement; }} Random element: 99 Java-Collections java-hashset Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2021" }, { "code": null, "e": 221, "s": 28, "text": "Unlike List classes, the HashSet class does not provide any methods using which we can get the elements using their index. It makes it difficult to get random elements from it using the index." }, { "code": null, "e": 311, "s": 221, "text": "We need to get random elements from HashSet, which can be done by either of the two ways:" }, { "code": null, "e": 371, "s": 311, "text": "By converting it to an arrayUsing an Iterator or a for loop" }, { "code": null, "e": 400, "s": 371, "text": "By converting it to an array" }, { "code": null, "e": 432, "s": 400, "text": "Using an Iterator or a for loop" }, { "code": null, "e": 441, "s": 432, "text": "Example:" }, { "code": null, "e": 588, "s": 441, "text": "Input:\n\n\nhs.add(11);\nhs.add(24);\nhs.add(34);\nhs.add(43);\nhs.add(55);\nhs.add(66);\nhs.add(72);\nhs.add(80);\nhs.add(99);\n\n\nOutput:\n\nRandom element: 99" }, { "code": null, "e": 625, "s": 588, "text": "Method 1: By converting to an array." }, { "code": null, "e": 707, "s": 625, "text": "Firstly convert HashSet into an array and then access the random element from it." }, { "code": null, "e": 886, "s": 707, "text": "Then we will create an object of Random class and will call the nextInt() method of that class which will give us any random number less than or equal to the size of the HashSet." }, { "code": null, "e": 966, "s": 886, "text": "And then using an array we will simply print the element present at that index." }, { "code": null, "e": 971, "s": 966, "text": "Java" }, { "code": "// Java program to get random elements from HashSet// using an array import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // creating the HashSet Set<Integer> hs = new HashSet<Integer>(); hs.add(11); hs.add(24); hs.add(34); hs.add(43); hs.add(55); hs.add(66); hs.add(72); hs.add(80); hs.add(99); // convert HashSet to an array Integer[] arrayNumbers = hs.toArray(new Integer[hs.size()]); // generate a random number Random rndm = new Random(); // this will generate a random number between 0 and // HashSet.size - 1 int rndmNumber = rndm.nextInt(hs.size()); // get the element at random number index System.out.println(\"Random element: \" + arrayNumbers[rndmNumber]); }}", "e": 1865, "s": 971, "text": null }, { "code": null, "e": 1884, "s": 1865, "text": "Random element: 11" }, { "code": null, "e": 1926, "s": 1884, "text": "Method 2: Using an Iterator or a for loop" }, { "code": null, "e": 2082, "s": 1926, "text": "In order to get random elements from the HashSet object, we need to generate a random number between 0 (inclusive) and the size of the HashSet (exclusive)." }, { "code": null, "e": 2195, "s": 2082, "text": "And then iterate through the set till we reach the element located at the random number position as given below." }, { "code": null, "e": 2274, "s": 2195, "text": "In this approach, we will get the element at a random index using an Iterator." }, { "code": null, "e": 2279, "s": 2274, "text": "Java" }, { "code": "// Java program to get random elements from HashSet// using an Iterator import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { Set<Integer> hs = new HashSet<Integer>(); hs.add(11); hs.add(24); hs.add(34); hs.add(43); hs.add(55); hs.add(66); hs.add(72); hs.add(80); hs.add(99); System.out.println(\"Random element: \" + getRandomElement(hs)); } private static <E> E getRandomElement(Set<? extends E> set) { Random random = new Random(); // Generate a random number using nextInt // method of the Random class. int randomNumber = random.nextInt(set.size()); Iterator<? extends E> iterator = set.iterator(); int currentIndex = 0; E randomElement = null; // iterate the HashSet while (iterator.hasNext()) { randomElement = iterator.next(); // if current index is equal to random number if (currentIndex == randomNumber) return randomElement; // increase the current index currentIndex++; } return randomElement; }}", "e": 3524, "s": 2279, "text": null }, { "code": null, "e": 3543, "s": 3524, "text": "Random element: 99" }, { "code": null, "e": 3560, "s": 3543, "text": "Java-Collections" }, { "code": null, "e": 3573, "s": 3560, "text": "java-hashset" }, { "code": null, "e": 3580, "s": 3573, "text": "Picked" }, { "code": null, "e": 3604, "s": 3580, "text": "Technical Scripter 2020" }, { "code": null, "e": 3609, "s": 3604, "text": "Java" }, { "code": null, "e": 3623, "s": 3609, "text": "Java Programs" }, { "code": null, "e": 3642, "s": 3623, "text": "Technical Scripter" }, { "code": null, "e": 3647, "s": 3642, "text": "Java" }, { "code": null, "e": 3664, "s": 3647, "text": "Java-Collections" }, { "code": null, "e": 3762, "s": 3664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3777, "s": 3762, "text": "Stream In Java" }, { "code": null, "e": 3798, "s": 3777, "text": "Introduction to Java" }, { "code": null, "e": 3819, "s": 3798, "text": "Constructors in Java" }, { "code": null, "e": 3838, "s": 3819, "text": "Exceptions in Java" }, { "code": null, "e": 3855, "s": 3838, "text": "Generics in Java" }, { "code": null, "e": 3881, "s": 3855, "text": "Java Programming Examples" }, { "code": null, "e": 3915, "s": 3881, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3962, "s": 3915, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 4000, "s": 3962, "text": "Factory method design pattern in Java" } ]
CSS | fit-content() Property
06 Jun, 2022 The CSS fit-content property is an inbuilt property in CSS. This property is used to adjust the size according to this formula min(maximum size, max(minimum size, argument)). The fit-content() property use to defined function to put a limit on the maximum size of the division. This formula is very helpful while dealing with CSS grids. However, it must be kept in mind that fit-content() is not compatible with Internet Explorer on PC. Different CSS units can be used in this formula. The fit-content() function accepts length and percentage as arguments.Syntax: fit-content: length | percentage Property values: length: This property value contains the fixed length. Units: Absolute Lengths fit-content(8cm)fit-content(12mm)fit-content(8pc)fit-content(15px)fit-content(5pt) fit-content(8cm) fit-content(12mm) fit-content(8pc) fit-content(15px) fit-content(5pt) percentage: This property value contains the relative length depends on available space in the given axis. Units: Relative Length fit-content(100%)fit-content(10em)fit-content(5rem)fit-content(2ch) fit-content(100%) fit-content(10em) fit-content(5rem) fit-content(2ch) Below example illustrate the CSS fit-content property:Example: It can be seen that the webpage is divided into four grid columns. The maximum permissible width of the first, second and third division is 150px, 250px, and 350px respectively, whereas the fourth division’s width has been set to 1.5fr. This means that it will adjust itself according to the device width and the width occupied by the other three divisions. html <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <title>CSS | fit-content Property</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <style> #container { display: grid; grid-template-columns: fit-content(150px) fit-content(250px) fit-content(350px) 1.5fr; grid-gap: 5px; box-sizing: border-box; height: 100%; width: 100%; background-color: #563d7c; padding: 8px; }</style> <body> <h1 style="color:green;">GeeksforGeeks</h1> <div id="container"> <div style="background-color: whitesmoke; padding: 5px"> The smallest division of the grid. Maximum width is clamped to 150px. </div> <div style="background-color: whitesmoke; padding: 5px"> This division's width will depend on the content inside it. However, the maximum width will be 250px. </div> <div style="background-color: whitesmoke; padding: 5px"> <strong> Division with some more data, however, the maximum permissible width will be 350px. </strong> <br> <br> Web design encompasses many different skills and disciplines in the production and maintenance of websites. The different areas of web design include web graphic design; interface design; authoring, including standardized code and proprietary software; user experience design; and search engine optimization. </div> <div style="background-color: whitesmoke; padding: 5px"> Flexible division, the width will change in accordance with the screen size and the width of the other three divisions. </div> </div> </body> </html> Output: Explanation: Let’s have a look at the example stepwise. Step 01: Normal Layout, the normal webpage layout. CSS Grid is used for the demonstration purpose. CSS Grid helps in creating responsive webpages, as the grid divisions adjust according to the screen width. Step 02: Screen width starts to decrease. The fourth division has started to shrink, however, the first, second and third division remains unaffected. Step 03: Minimum Width, the third division has shrunk the most. The content inside the first and the second division have adjusted themselves in such a way that they do not get overflow. The grid is responding well to the screen width change. Step 04: Screen width starts to increase. Now the screen width has been increased, and the width of all the divisions has increased accordingly. However, an upper limit on the width of the first, second and third divisions was set, and thus after limiting that threshold limit, they will get fixed. The fourth division, however, will keep on expanding. Step 05: Back to normal layout the grid has been reinstated to the normal layout. From steps 02, 03, and 04, it can be observed that once the screen width started to reduce, the fourth division was the first to shrink. Once the width started to increase, all the divisions started to expand, however, the first division stopped expanding after the width became equal to 150px, while the second and the third one expanded until they reached the width of 250px and 350px respectively. The fourth division kept on expanding. This is because its width was set to 1.5fr, which means that its own width will depend on the width of the screen and the other divisions. Supported Browser: Google Chrome Firefox Opera Safari ysachin2314 vinayedula CSS-Properties Picked CSS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2022" }, { "code": null, "e": 618, "s": 52, "text": "The CSS fit-content property is an inbuilt property in CSS. This property is used to adjust the size according to this formula min(maximum size, max(minimum size, argument)). The fit-content() property use to defined function to put a limit on the maximum size of the division. This formula is very helpful while dealing with CSS grids. However, it must be kept in mind that fit-content() is not compatible with Internet Explorer on PC. Different CSS units can be used in this formula. The fit-content() function accepts length and percentage as arguments.Syntax: " }, { "code": null, "e": 651, "s": 618, "text": "fit-content: length | percentage" }, { "code": null, "e": 670, "s": 651, "text": "Property values: " }, { "code": null, "e": 832, "s": 670, "text": "length: This property value contains the fixed length. Units: Absolute Lengths fit-content(8cm)fit-content(12mm)fit-content(8pc)fit-content(15px)fit-content(5pt)" }, { "code": null, "e": 849, "s": 832, "text": "fit-content(8cm)" }, { "code": null, "e": 867, "s": 849, "text": "fit-content(12mm)" }, { "code": null, "e": 884, "s": 867, "text": "fit-content(8pc)" }, { "code": null, "e": 902, "s": 884, "text": "fit-content(15px)" }, { "code": null, "e": 919, "s": 902, "text": "fit-content(5pt)" }, { "code": null, "e": 1117, "s": 919, "text": "percentage: This property value contains the relative length depends on available space in the given axis. Units: Relative Length fit-content(100%)fit-content(10em)fit-content(5rem)fit-content(2ch)" }, { "code": null, "e": 1135, "s": 1117, "text": "fit-content(100%)" }, { "code": null, "e": 1153, "s": 1135, "text": "fit-content(10em)" }, { "code": null, "e": 1171, "s": 1153, "text": "fit-content(5rem)" }, { "code": null, "e": 1188, "s": 1171, "text": "fit-content(2ch)" }, { "code": null, "e": 1610, "s": 1188, "text": "Below example illustrate the CSS fit-content property:Example: It can be seen that the webpage is divided into four grid columns. The maximum permissible width of the first, second and third division is 150px, 250px, and 350px respectively, whereas the fourth division’s width has been set to 1.5fr. This means that it will adjust itself according to the device width and the width occupied by the other three divisions. " }, { "code": null, "e": 1615, "s": 1610, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <title>CSS | fit-content Property</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\"> </head> <style> #container { display: grid; grid-template-columns: fit-content(150px) fit-content(250px) fit-content(350px) 1.5fr; grid-gap: 5px; box-sizing: border-box; height: 100%; width: 100%; background-color: #563d7c; padding: 8px; }</style> <body> <h1 style=\"color:green;\">GeeksforGeeks</h1> <div id=\"container\"> <div style=\"background-color: whitesmoke; padding: 5px\"> The smallest division of the grid. Maximum width is clamped to 150px. </div> <div style=\"background-color: whitesmoke; padding: 5px\"> This division's width will depend on the content inside it. However, the maximum width will be 250px. </div> <div style=\"background-color: whitesmoke; padding: 5px\"> <strong> Division with some more data, however, the maximum permissible width will be 350px. </strong> <br> <br> Web design encompasses many different skills and disciplines in the production and maintenance of websites. The different areas of web design include web graphic design; interface design; authoring, including standardized code and proprietary software; user experience design; and search engine optimization. </div> <div style=\"background-color: whitesmoke; padding: 5px\"> Flexible division, the width will change in accordance with the screen size and the width of the other three divisions. </div> </div> </body> </html>", "e": 3933, "s": 1615, "text": null }, { "code": null, "e": 3943, "s": 3933, "text": "Output: " }, { "code": null, "e": 4000, "s": 3943, "text": "Explanation: Let’s have a look at the example stepwise. " }, { "code": null, "e": 4208, "s": 4000, "text": "Step 01: Normal Layout, the normal webpage layout. CSS Grid is used for the demonstration purpose. CSS Grid helps in creating responsive webpages, as the grid divisions adjust according to the screen width. " }, { "code": null, "e": 4360, "s": 4208, "text": "Step 02: Screen width starts to decrease. The fourth division has started to shrink, however, the first, second and third division remains unaffected. " }, { "code": null, "e": 4604, "s": 4360, "text": "Step 03: Minimum Width, the third division has shrunk the most. The content inside the first and the second division have adjusted themselves in such a way that they do not get overflow. The grid is responding well to the screen width change. " }, { "code": null, "e": 4958, "s": 4604, "text": "Step 04: Screen width starts to increase. Now the screen width has been increased, and the width of all the divisions has increased accordingly. However, an upper limit on the width of the first, second and third divisions was set, and thus after limiting that threshold limit, they will get fixed. The fourth division, however, will keep on expanding. " }, { "code": null, "e": 5041, "s": 4958, "text": "Step 05: Back to normal layout the grid has been reinstated to the normal layout. " }, { "code": null, "e": 5620, "s": 5041, "text": "From steps 02, 03, and 04, it can be observed that once the screen width started to reduce, the fourth division was the first to shrink. Once the width started to increase, all the divisions started to expand, however, the first division stopped expanding after the width became equal to 150px, while the second and the third one expanded until they reached the width of 250px and 350px respectively. The fourth division kept on expanding. This is because its width was set to 1.5fr, which means that its own width will depend on the width of the screen and the other divisions." }, { "code": null, "e": 5639, "s": 5620, "text": "Supported Browser:" }, { "code": null, "e": 5653, "s": 5639, "text": "Google Chrome" }, { "code": null, "e": 5661, "s": 5653, "text": "Firefox" }, { "code": null, "e": 5667, "s": 5661, "text": "Opera" }, { "code": null, "e": 5674, "s": 5667, "text": "Safari" }, { "code": null, "e": 5686, "s": 5674, "text": "ysachin2314" }, { "code": null, "e": 5697, "s": 5686, "text": "vinayedula" }, { "code": null, "e": 5712, "s": 5697, "text": "CSS-Properties" }, { "code": null, "e": 5719, "s": 5712, "text": "Picked" }, { "code": null, "e": 5723, "s": 5719, "text": "CSS" }, { "code": null, "e": 5742, "s": 5723, "text": "Technical Scripter" }, { "code": null, "e": 5759, "s": 5742, "text": "Web Technologies" } ]
Groovy - Traits
Traits are a structural construct of the language which allow − Composition of behaviors. Runtime implementation of interfaces. Compatibility with static type checking/compilation They can be seen as interfaces carrying both default implementations and state. A trait is defined using the trait keyword. An example of a trait is given below − trait Marks { void DisplayMarks() { println("Display Marks"); } } One can then use the implement keyword to implement the trait in the similar way as interfaces. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); } } trait Marks { void DisplayMarks() { println("Display Marks"); } } class Student implements Marks { int StudentID int Marks1; } Traits may implement interfaces, in which case the interfaces are declared using the implements keyword. An example of a trait implementing an interface is given below. In the following example the following key points can be noted. An interface Total is defined with the method DisplayTotal. An interface Total is defined with the method DisplayTotal. The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method. The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); println(st.DisplayTotal()); } } interface Total { void DisplayTotal() } trait Marks implements Total { void DisplayMarks() { println("Display Marks"); } void DisplayTotal() { println("Display Total"); } } class Student implements Marks { int StudentID int Marks1; } The output of the above program would be − Display Marks Display Total A trait may define properties. An example of a trait with a property is given below. In the following example, the Marks1 of type integer is a property. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); println(st.DisplayTotal()); } interface Total { void DisplayTotal() } trait Marks implements Total { int Marks1; void DisplayMarks() { this.Marks1 = 10; println(this.Marks1); } void DisplayTotal() { println("Display Total"); } } class Student implements Marks { int StudentID } } The output of the above program would be − 10 Display Total Traits can be used to implement multiple inheritance in a controlled way, avoiding the diamond issue. In the following code example, we have defined two traits – Marks and Total. Our Student class implements both traits. Since the student class extends both traits, it is able to access the both of the methods – DisplayMarks and DisplayTotal. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); println(st.DisplayTotal()); } } trait Marks { void DisplayMarks() { println("Marks1"); } } trait Total { void DisplayTotal() { println("Total"); } } class Student implements Marks,Total { int StudentID } The output of the above program would be − Total Marks1 Traits may extend another trait, in which case you must use the extends keyword. In the following code example, we are extending the Total trait with the Marks trait. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); } } trait Marks { void DisplayMarks() { println("Marks1"); } } trait Total extends Marks { void DisplayMarks() { println("Total"); } } class Student implements Total { int StudentID } The output of the above program would be −
[ { "code": null, "e": 2436, "s": 2372, "text": "Traits are a structural construct of the language which allow −" }, { "code": null, "e": 2462, "s": 2436, "text": "Composition of behaviors." }, { "code": null, "e": 2500, "s": 2462, "text": "Runtime implementation of interfaces." }, { "code": null, "e": 2552, "s": 2500, "text": "Compatibility with static type checking/compilation" }, { "code": null, "e": 2676, "s": 2552, "text": "They can be seen as interfaces carrying both default implementations and state. A trait is defined using the trait keyword." }, { "code": null, "e": 2715, "s": 2676, "text": "An example of a trait is given below −" }, { "code": null, "e": 2794, "s": 2715, "text": "trait Marks {\n void DisplayMarks() {\n println(\"Display Marks\");\n } \n}" }, { "code": null, "e": 2890, "s": 2794, "text": "One can then use the implement keyword to implement the trait in the similar way as interfaces." }, { "code": null, "e": 3218, "s": 2890, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.Marks1 = 10; \n println(st.DisplayMarks());\n } \n} \n\ntrait Marks { \n void DisplayMarks() {\n println(\"Display Marks\");\n } \n} \n\nclass Student implements Marks { \n int StudentID\n int Marks1;\n}" }, { "code": null, "e": 3323, "s": 3218, "text": "Traits may implement interfaces, in which case the interfaces are declared using the implements keyword." }, { "code": null, "e": 3451, "s": 3323, "text": "An example of a trait implementing an interface is given below. In the following example the following key points can be noted." }, { "code": null, "e": 3511, "s": 3451, "text": "An interface Total is defined with the method DisplayTotal." }, { "code": null, "e": 3571, "s": 3511, "text": "An interface Total is defined with the method DisplayTotal." }, { "code": null, "e": 3692, "s": 3571, "text": "The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method." }, { "code": null, "e": 3813, "s": 3692, "text": "The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method." }, { "code": null, "e": 4307, "s": 3813, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.Marks1 = 10;\n\t\t\n println(st.DisplayMarks());\n println(st.DisplayTotal());\n } \n} \n\ninterface Total {\n void DisplayTotal() \n} \n\ntrait Marks implements Total {\n void DisplayMarks() {\n println(\"Display Marks\");\n }\n\t\n void DisplayTotal() {\n println(\"Display Total\"); \n } \n} \n\nclass Student implements Marks { \n int StudentID\n int Marks1; \n} " }, { "code": null, "e": 4350, "s": 4307, "text": "The output of the above program would be −" }, { "code": null, "e": 4380, "s": 4350, "text": "Display Marks \nDisplay Total\n" }, { "code": null, "e": 4465, "s": 4380, "text": "A trait may define properties. An example of a trait with a property is given below." }, { "code": null, "e": 4533, "s": 4465, "text": "In the following example, the Marks1 of type integer is a property." }, { "code": null, "e": 5076, "s": 4533, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n\t\t\n println(st.DisplayMarks());\n println(st.DisplayTotal());\n } \n\t\n interface Total {\n void DisplayTotal() \n } \n\t\n trait Marks implements Total {\n int Marks1;\n\t\t\n void DisplayMarks() {\n this.Marks1 = 10;\n println(this.Marks1);\n }\n\t\t\n void DisplayTotal() {\n println(\"Display Total\");\n } \n } \n\t\n class Student implements Marks {\n int StudentID \n }\n} " }, { "code": null, "e": 5119, "s": 5076, "text": "The output of the above program would be −" }, { "code": null, "e": 5138, "s": 5119, "text": "10 \nDisplay Total\n" }, { "code": null, "e": 5482, "s": 5138, "text": "Traits can be used to implement multiple inheritance in a controlled way, avoiding the diamond issue. In the following code example, we have defined two traits – Marks and Total. Our Student class implements both traits. Since the student class extends both traits, it is able to access the both of the methods – DisplayMarks and DisplayTotal." }, { "code": null, "e": 5886, "s": 5482, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n\t\t\n println(st.DisplayMarks());\n println(st.DisplayTotal()); \n } \n} \n\ntrait Marks {\n void DisplayMarks() {\n println(\"Marks1\");\n } \n} \n\ntrait Total {\n void DisplayTotal() { \n println(\"Total\");\n } \n} \n\nclass Student implements Marks,Total {\n int StudentID \n} " }, { "code": null, "e": 5929, "s": 5886, "text": "The output of the above program would be −" }, { "code": null, "e": 5944, "s": 5929, "text": "Total \nMarks1\n" }, { "code": null, "e": 6111, "s": 5944, "text": "Traits may extend another trait, in which case you must use the extends keyword. In the following code example, we are extending the Total trait with the Marks trait." }, { "code": null, "e": 6481, "s": 6111, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n println(st.DisplayMarks());\n } \n} \n\ntrait Marks {\n void DisplayMarks() {\n println(\"Marks1\");\n } \n} \n\ntrait Total extends Marks {\n void DisplayMarks() {\n println(\"Total\");\n } \n} \n\nclass Student implements Total {\n int StudentID \n}" } ]
Excel – Descriptive Statistics
08 Feb, 2022 Descriptive statistics is all about describing the given data. To describe about the data, we use Measures of central tendency and measures of dispersion. Measures of central tendency [Mean, Median, and Mode] – a single number about the center of the data points. Measures of dispersion [Range, Variance and Standard Deviation] – how the data is distributed In this article, we explain how to use “Data Analysis” in excel for descriptive statistics in detail. Sample data: For eg. We have given shirt size of 20 men in the below table. Follow the below steps to implement descriptive statistics on sample data: Step 1: Go to “Data” >> Click “Data Analysis” (Image 1) – to popup the “Data Analysis” Dialog box. If you cannot find “Data analysis” in excel ribbon. The end of this article finds the steps [To provide “Data Analysis”]. Image 1 Step 2: In Data Analysis, Select “Descriptive Statistics” and Press “OK” – To popup “Descriptive statistics” Dialog box for further input Step 3: Make sure the below options are selected in “Descriptive statistics” and Press “OK”. Input Range: “$B$1:$B$21” Grouped By: Columns Labels in first row: Checked Output Range: $D$5 Summary statistics: Checked Output: Descriptive statistics Output in Table “D5:E19” To provide the “Data Analysis” button in the “Analysis Group” Step 1: Go to File >> Click “Options” – to popup “Excel options”. Step 2: Select “Add-ins” and Press “Go”. Step 3: Select “Analysis ToolPak” and press “OK”. avtarkumar719 Excel-Charts Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Get Length of Array in Excel VBA? How to Normalize Data in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? Introduction to Excel Spreadsheet How to make a 3 Axis Graph using Excel? Macros in Excel How to Show Percentages in Stacked Column Chart in Excel? How to Extract the Last Word From a Cell in Excel?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Feb, 2022" }, { "code": null, "e": 183, "s": 28, "text": "Descriptive statistics is all about describing the given data. To describe about the data, we use Measures of central tendency and measures of dispersion." }, { "code": null, "e": 292, "s": 183, "text": "Measures of central tendency [Mean, Median, and Mode] – a single number about the center of the data points." }, { "code": null, "e": 386, "s": 292, "text": "Measures of dispersion [Range, Variance and Standard Deviation] – how the data is distributed" }, { "code": null, "e": 488, "s": 386, "text": "In this article, we explain how to use “Data Analysis” in excel for descriptive statistics in detail." }, { "code": null, "e": 501, "s": 488, "text": "Sample data:" }, { "code": null, "e": 564, "s": 501, "text": "For eg. We have given shirt size of 20 men in the below table." }, { "code": null, "e": 639, "s": 564, "text": "Follow the below steps to implement descriptive statistics on sample data:" }, { "code": null, "e": 861, "s": 639, "text": "Step 1: Go to “Data” >> Click “Data Analysis” (Image 1) – to popup the “Data Analysis” Dialog box. If you cannot find “Data analysis” in excel ribbon. The end of this article finds the steps [To provide “Data Analysis”]." }, { "code": null, "e": 869, "s": 861, "text": "Image 1" }, { "code": null, "e": 1007, "s": 869, "text": "Step 2: In Data Analysis, Select “Descriptive Statistics” and Press “OK” – To popup “Descriptive statistics” Dialog box for further input" }, { "code": null, "e": 1100, "s": 1007, "text": "Step 3: Make sure the below options are selected in “Descriptive statistics” and Press “OK”." }, { "code": null, "e": 1226, "s": 1100, "text": "Input Range: “$B$1:$B$21”\n\nGrouped By: Columns\n\nLabels in first row: Checked\n\nOutput Range: $D$5\n\nSummary statistics: Checked" }, { "code": null, "e": 1234, "s": 1226, "text": "Output:" }, { "code": null, "e": 1283, "s": 1234, "text": "Descriptive statistics Output in Table “D5:E19”" }, { "code": null, "e": 1347, "s": 1283, "text": "To provide the “Data Analysis” button in the “Analysis Group” " }, { "code": null, "e": 1414, "s": 1347, "text": "Step 1: Go to File >> Click “Options” – to popup “Excel options”." }, { "code": null, "e": 1455, "s": 1414, "text": "Step 2: Select “Add-ins” and Press “Go”." }, { "code": null, "e": 1506, "s": 1455, "text": "Step 3: Select “Analysis ToolPak” and press “OK”." }, { "code": null, "e": 1520, "s": 1506, "text": "avtarkumar719" }, { "code": null, "e": 1533, "s": 1520, "text": "Excel-Charts" }, { "code": null, "e": 1540, "s": 1533, "text": "Picked" }, { "code": null, "e": 1546, "s": 1540, "text": "Excel" }, { "code": null, "e": 1644, "s": 1546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1682, "s": 1644, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 1723, "s": 1682, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 1755, "s": 1723, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 1810, "s": 1755, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 1838, "s": 1810, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 1872, "s": 1838, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 1912, "s": 1872, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 1928, "s": 1912, "text": "Macros in Excel" }, { "code": null, "e": 1986, "s": 1928, "text": "How to Show Percentages in Stacked Column Chart in Excel?" } ]
Python Program To Merge Two Sorted Lists (In-Place)
11 Jan, 2022 Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: The output list is in sorted order. There are different discussed different solutions in post below. Merge two sorted linked lists Method 1 (Recursive): Approach: The recursive solution can be formed, given the linked lists are sorted. Compare the head of both linked lists.Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.The rest elements of both lists will appear after that.Now run a recursive function with parameters, the next node of the smaller element, and the other head.The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()Handle some corner cases. If both the heads are NULL return null.If one head is null return the other. Compare the head of both linked lists. Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes. The rest elements of both lists will appear after that. Now run a recursive function with parameters, the next node of the smaller element, and the other head. The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction() Handle some corner cases. If both the heads are NULL return null.If one head is null return the other. If both the heads are NULL return null. If one head is null return the other. Python3 # Python3 program to merge two # sorted linked lists in-place.import mathclass Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in # a linkedlistdef newNode(key): temp = Node(key) temp.data = key temp.next = None return temp # A utility function to print # linked listdef printList(node): while (node != None): print(node.data, end = " ") node = node.next # Merges two given lists in-place. # This function mainly compares # head nodes and calls mergeUtil()def merge(h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # start with the linked list # whose head data is the least if (h1.data < h2.data): h1.next = merge(h1.next, h2) return h1 else: h2.next = merge(h1, h2.next) return h2 # Driver Codeif __name__=='__main__': head1 = newNode(1) head1.next = newNode(3) head1.next.next = newNode(5) # 1.3.5 LinkedList created head2 = newNode(0) head2.next = newNode(2) head2.next.next = newNode(4) # 0.2.4 LinkedList created mergedhead = merge(head1, head2) printList(mergedhead) # This code is contributed by Srathore Output: 0 1 2 3 4 5 Complexity Analysis: Time complexity:O(n). Only one traversal of the linked lists are needed. Auxiliary Space:O(n). If the recursive stack space is taken into consideration. Method 2 (Iterative): Approach: This approach is very similar to the above recursive approach. Traverse the list from start to end.If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed.If the first list has reached end while traversing, point the next node to the head of second list. Traverse the list from start to end. If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed. If the first list has reached end while traversing, point the next node to the head of second list. Note: Compare both the lists where the list with a smaller head value is the first list. Python # Python program to merge two # sorted linked lists in-place.# Linked List node class Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in # a linkedlistdef newNode(key): temp = Node(0) temp.data = key temp.next = None return temp # A utility function to print # linked listdef printList(node): while (node != None) : print( node.data, end =" ") node = node.next # Merges two lists with headers as h1 and h2.# It assumes that h1's data is smaller than# or equal to h2's data.def mergeUtil(h1, h2): # if only one node in first list # simply point its head to second # list if (h1.next == None) : h1.next = h2 return h1 # Initialize current and next # pointers of both lists curr1 = h1 next1 = h1.next curr2 = h2 next2 = h2.next while (next1 != None and curr2 != None): # if curr2 lies in between curr1 # and next1 then do curr1.curr2.next1 if ((curr2.data) >= (curr1.data) and (curr2.data) <= (next1.data)): next2 = curr2.next curr1.next = curr2 curr2.next = next1 # now let curr1 and curr2 to point # to their immediate next pointers curr1 = curr2 curr2 = next2 else: # if more nodes in first list if (next1.next) : next1 = next1.next curr1 = curr1.next # else point the last node of first list # to the remaining nodes of second list else: next1.next = curr2 return h1 return h1 # Merges two given lists in-place. # This function mainly compares head # nodes and calls mergeUtil()def merge(h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # Start with the linked list # whose head data is the least if (h1.data < h2.data): return mergeUtil(h1, h2) else: return mergeUtil(h2, h1) # Driver codehead1 = newNode(1)head1.next = newNode(3)head1.next.next = newNode(5) # 1.3.5 LinkedList createdhead2 = newNode(0)head2.next = newNode(2)head2.next.next = newNode(4) # 0.2.4 LinkedList createdmergedhead = merge(head1, head2) printList(mergedhead)# This code is contributed by Arnab Kundu Output: 0 1 2 3 4 5 Complexity Analysis: Time complexity:O(n). As only one traversal of the linked lists is needed. Auxiliary Space:O(1). As there is no space required. Please refer complete article on Merge two sorted lists (in-place) for more details! Accolite Amazon Belzabar Brocade FactSet Flipkart MakeMyTrip Microsoft OATS Systems Oracle Samsung Synopsys Linked List Python Programs Flipkart Accolite Amazon Microsoft Samsung FactSet MakeMyTrip Oracle Brocade Synopsys OATS Systems Belzabar Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Find first node of loop in a linked list Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jan, 2022" }, { "code": null, "e": 141, "s": 28, "text": "Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples:" }, { "code": null, "e": 381, "s": 141, "text": "Input: head1: 5->7->9\n head2: 4->6->8 \nOutput: 4->5->6->7->8->9\nExplanation: The output list is in sorted order.\n\nInput: head1: 1->3->5->7\n head2: 2->4\nOutput: 1->2->3->4->5->7\nExplanation: The output list is in sorted order." }, { "code": null, "e": 476, "s": 381, "text": "There are different discussed different solutions in post below. Merge two sorted linked lists" }, { "code": null, "e": 498, "s": 476, "text": "Method 1 (Recursive):" }, { "code": null, "e": 581, "s": 498, "text": "Approach: The recursive solution can be formed, given the linked lists are sorted." }, { "code": null, "e": 1179, "s": 581, "text": "Compare the head of both linked lists.Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.The rest elements of both lists will appear after that.Now run a recursive function with parameters, the next node of the smaller element, and the other head.The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()Handle some corner cases. If both the heads are NULL return null.If one head is null return the other." }, { "code": null, "e": 1218, "s": 1179, "text": "Compare the head of both linked lists." }, { "code": null, "e": 1333, "s": 1218, "text": "Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes." }, { "code": null, "e": 1389, "s": 1333, "text": "The rest elements of both lists will appear after that." }, { "code": null, "e": 1493, "s": 1389, "text": "Now run a recursive function with parameters, the next node of the smaller element, and the other head." }, { "code": null, "e": 1679, "s": 1493, "text": "The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()" }, { "code": null, "e": 1782, "s": 1679, "text": "Handle some corner cases. If both the heads are NULL return null.If one head is null return the other." }, { "code": null, "e": 1822, "s": 1782, "text": "If both the heads are NULL return null." }, { "code": null, "e": 1860, "s": 1822, "text": "If one head is null return the other." }, { "code": null, "e": 1868, "s": 1860, "text": "Python3" }, { "code": "# Python3 program to merge two # sorted linked lists in-place.import mathclass Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in # a linkedlistdef newNode(key): temp = Node(key) temp.data = key temp.next = None return temp # A utility function to print # linked listdef printList(node): while (node != None): print(node.data, end = \" \") node = node.next # Merges two given lists in-place. # This function mainly compares # head nodes and calls mergeUtil()def merge(h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # start with the linked list # whose head data is the least if (h1.data < h2.data): h1.next = merge(h1.next, h2) return h1 else: h2.next = merge(h1, h2.next) return h2 # Driver Codeif __name__=='__main__': head1 = newNode(1) head1.next = newNode(3) head1.next.next = newNode(5) # 1.3.5 LinkedList created head2 = newNode(0) head2.next = newNode(2) head2.next.next = newNode(4) # 0.2.4 LinkedList created mergedhead = merge(head1, head2) printList(mergedhead) # This code is contributed by Srathore", "e": 3119, "s": 1868, "text": null }, { "code": null, "e": 3129, "s": 3119, "text": "Output: " }, { "code": null, "e": 3142, "s": 3129, "text": "0 1 2 3 4 5 " }, { "code": null, "e": 3163, "s": 3142, "text": "Complexity Analysis:" }, { "code": null, "e": 3236, "s": 3163, "text": "Time complexity:O(n). Only one traversal of the linked lists are needed." }, { "code": null, "e": 3316, "s": 3236, "text": "Auxiliary Space:O(n). If the recursive stack space is taken into consideration." }, { "code": null, "e": 3338, "s": 3316, "text": "Method 2 (Iterative):" }, { "code": null, "e": 3411, "s": 3338, "text": "Approach: This approach is very similar to the above recursive approach." }, { "code": null, "e": 3779, "s": 3411, "text": "Traverse the list from start to end.If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed.If the first list has reached end while traversing, point the next node to the head of second list." }, { "code": null, "e": 3816, "s": 3779, "text": "Traverse the list from start to end." }, { "code": null, "e": 4049, "s": 3816, "text": "If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed." }, { "code": null, "e": 4149, "s": 4049, "text": "If the first list has reached end while traversing, point the next node to the head of second list." }, { "code": null, "e": 4238, "s": 4149, "text": "Note: Compare both the lists where the list with a smaller head value is the first list." }, { "code": null, "e": 4245, "s": 4238, "text": "Python" }, { "code": "# Python program to merge two # sorted linked lists in-place.# Linked List node class Node: def __init__(self, data): self.data = data self.next = None # Function to create newNode in # a linkedlistdef newNode(key): temp = Node(0) temp.data = key temp.next = None return temp # A utility function to print # linked listdef printList(node): while (node != None) : print( node.data, end =\" \") node = node.next # Merges two lists with headers as h1 and h2.# It assumes that h1's data is smaller than# or equal to h2's data.def mergeUtil(h1, h2): # if only one node in first list # simply point its head to second # list if (h1.next == None) : h1.next = h2 return h1 # Initialize current and next # pointers of both lists curr1 = h1 next1 = h1.next curr2 = h2 next2 = h2.next while (next1 != None and curr2 != None): # if curr2 lies in between curr1 # and next1 then do curr1.curr2.next1 if ((curr2.data) >= (curr1.data) and (curr2.data) <= (next1.data)): next2 = curr2.next curr1.next = curr2 curr2.next = next1 # now let curr1 and curr2 to point # to their immediate next pointers curr1 = curr2 curr2 = next2 else: # if more nodes in first list if (next1.next) : next1 = next1.next curr1 = curr1.next # else point the last node of first list # to the remaining nodes of second list else: next1.next = curr2 return h1 return h1 # Merges two given lists in-place. # This function mainly compares head # nodes and calls mergeUtil()def merge(h1, h2): if (h1 == None): return h2 if (h2 == None): return h1 # Start with the linked list # whose head data is the least if (h1.data < h2.data): return mergeUtil(h1, h2) else: return mergeUtil(h2, h1) # Driver codehead1 = newNode(1)head1.next = newNode(3)head1.next.next = newNode(5) # 1.3.5 LinkedList createdhead2 = newNode(0)head2.next = newNode(2)head2.next.next = newNode(4) # 0.2.4 LinkedList createdmergedhead = merge(head1, head2) printList(mergedhead)# This code is contributed by Arnab Kundu", "e": 6638, "s": 4245, "text": null }, { "code": null, "e": 6648, "s": 6638, "text": "Output: " }, { "code": null, "e": 6661, "s": 6648, "text": "0 1 2 3 4 5 " }, { "code": null, "e": 6682, "s": 6661, "text": "Complexity Analysis:" }, { "code": null, "e": 6757, "s": 6682, "text": "Time complexity:O(n). As only one traversal of the linked lists is needed." }, { "code": null, "e": 6810, "s": 6757, "text": "Auxiliary Space:O(1). As there is no space required." }, { "code": null, "e": 6895, "s": 6810, "text": "Please refer complete article on Merge two sorted lists (in-place) for more details!" }, { "code": null, "e": 6904, "s": 6895, "text": "Accolite" }, { "code": null, "e": 6911, "s": 6904, "text": "Amazon" }, { "code": null, "e": 6920, "s": 6911, "text": "Belzabar" }, { "code": null, "e": 6928, "s": 6920, "text": "Brocade" }, { "code": null, "e": 6936, "s": 6928, "text": "FactSet" }, { "code": null, "e": 6945, "s": 6936, "text": "Flipkart" }, { "code": null, "e": 6956, "s": 6945, "text": "MakeMyTrip" }, { "code": null, "e": 6966, "s": 6956, "text": "Microsoft" }, { "code": null, "e": 6979, "s": 6966, "text": "OATS Systems" }, { "code": null, "e": 6986, "s": 6979, "text": "Oracle" }, { "code": null, "e": 6994, "s": 6986, "text": "Samsung" }, { "code": null, "e": 7003, "s": 6994, "text": "Synopsys" }, { "code": null, "e": 7015, "s": 7003, "text": "Linked List" }, { "code": null, "e": 7031, "s": 7015, "text": "Python Programs" }, { "code": null, "e": 7040, "s": 7031, "text": "Flipkart" }, { "code": null, "e": 7049, "s": 7040, "text": "Accolite" }, { "code": null, "e": 7056, "s": 7049, "text": "Amazon" }, { "code": null, "e": 7066, "s": 7056, "text": "Microsoft" }, { "code": null, "e": 7074, "s": 7066, "text": "Samsung" }, { "code": null, "e": 7082, "s": 7074, "text": "FactSet" }, { "code": null, "e": 7093, "s": 7082, "text": "MakeMyTrip" }, { "code": null, "e": 7100, "s": 7093, "text": "Oracle" }, { "code": null, "e": 7108, "s": 7100, "text": "Brocade" }, { "code": null, "e": 7117, "s": 7108, "text": "Synopsys" }, { "code": null, "e": 7130, "s": 7117, "text": "OATS Systems" }, { "code": null, "e": 7139, "s": 7130, "text": "Belzabar" }, { "code": null, "e": 7151, "s": 7139, "text": "Linked List" }, { "code": null, "e": 7249, "s": 7151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7281, "s": 7249, "text": "Introduction to Data Structures" }, { "code": null, "e": 7345, "s": 7281, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7366, "s": 7345, "text": "Types of Linked List" }, { "code": null, "e": 7406, "s": 7366, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 7447, "s": 7406, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 7490, "s": 7447, "text": "Python program to convert a list to string" }, { "code": null, "e": 7512, "s": 7490, "text": "Defaultdict in Python" }, { "code": null, "e": 7551, "s": 7512, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 7589, "s": 7551, "text": "Python | Convert a list to dictionary" } ]
Python program to find the String in a List
12 Apr, 2022 Given a list, the task is to write a Python program to check whether a list contains a particular string or not. Examples: Input: l=[1, 1.0, ‘have’, ‘a’, ‘geeky’, ‘day’]; s=’geeky’ Output: geeky is present in the list Input: l=[‘hello’,’ geek’, ‘have’, ‘a’, ‘geeky’, ‘day’]; s=’nice’ Output: nice is not present in the list Method #1: Using in operator The in operator comes handy for checking if a particular string/element exists in the list or not. Example: Python3 # assign listl = [1, 2.0, 'have', 'a', 'geeky', 'day'] # assign strings = 'geeky' # check if string is present in the listif s in l: print(f'{s} is present in the list')else: print(f'{s} is not present in the list') Output: geeky is present in the list Method #2: Using count() function The count() function is used to count the occurrence of a particular string in the list. If the count of a string is more than 0, it means that particular string exists in the list, else that string doesn’t exist in the list. Example: Python3 # assign listl = ['1', 1.0, 32, 'a', 'geeky', 'day'] # assign strings = 'prime' # check if string is present in listif l.count(s) > 0: print(f'{s} is present in the list')else: print(f'{s} is not present in the list') Output: prime is not present in the list Method #3: Using List Comprehension List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. It is used to transform iterative statements into formulas. Example: Python3 # assign listl = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] # assign strings = 'geek' # list comprehensioncompare = [i for i in l if s in l] # check if string is present in listif len(compare) > 0: print(f'{s} is present in the list')else: print(f'{s} is not present in the list') Output: geeky is present in the list Method #4: Using any() function The any() function is used to check the existence of an element in the list. it’s like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list. Example: Python3 # assign listl = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] # assign strings = 'prime' # check if string is present in listif any(s in i for i in l): print(f'{s} is present in the list')else: print(f'{s} is not present in the list') Output: prime is not present in the list sweetyty singghakshay Python list-programs Python string-programs Technical Scripter 2020 Python Python Programs Technical Scripter 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 Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2022" }, { "code": null, "e": 141, "s": 28, "text": "Given a list, the task is to write a Python program to check whether a list contains a particular string or not." }, { "code": null, "e": 151, "s": 141, "text": "Examples:" }, { "code": null, "e": 209, "s": 151, "text": "Input: l=[1, 1.0, ‘have’, ‘a’, ‘geeky’, ‘day’]; s=’geeky’" }, { "code": null, "e": 246, "s": 209, "text": "Output: geeky is present in the list" }, { "code": null, "e": 312, "s": 246, "text": "Input: l=[‘hello’,’ geek’, ‘have’, ‘a’, ‘geeky’, ‘day’]; s=’nice’" }, { "code": null, "e": 352, "s": 312, "text": "Output: nice is not present in the list" }, { "code": null, "e": 381, "s": 352, "text": "Method #1: Using in operator" }, { "code": null, "e": 480, "s": 381, "text": "The in operator comes handy for checking if a particular string/element exists in the list or not." }, { "code": null, "e": 489, "s": 480, "text": "Example:" }, { "code": null, "e": 497, "s": 489, "text": "Python3" }, { "code": "# assign listl = [1, 2.0, 'have', 'a', 'geeky', 'day'] # assign strings = 'geeky' # check if string is present in the listif s in l: print(f'{s} is present in the list')else: print(f'{s} is not present in the list')", "e": 720, "s": 497, "text": null }, { "code": null, "e": 728, "s": 720, "text": "Output:" }, { "code": null, "e": 757, "s": 728, "text": "geeky is present in the list" }, { "code": null, "e": 791, "s": 757, "text": "Method #2: Using count() function" }, { "code": null, "e": 1017, "s": 791, "text": "The count() function is used to count the occurrence of a particular string in the list. If the count of a string is more than 0, it means that particular string exists in the list, else that string doesn’t exist in the list." }, { "code": null, "e": 1026, "s": 1017, "text": "Example:" }, { "code": null, "e": 1034, "s": 1026, "text": "Python3" }, { "code": "# assign listl = ['1', 1.0, 32, 'a', 'geeky', 'day'] # assign strings = 'prime' # check if string is present in listif l.count(s) > 0: print(f'{s} is present in the list')else: print(f'{s} is not present in the list')", "e": 1258, "s": 1034, "text": null }, { "code": null, "e": 1266, "s": 1258, "text": "Output:" }, { "code": null, "e": 1299, "s": 1266, "text": "prime is not present in the list" }, { "code": null, "e": 1335, "s": 1299, "text": "Method #3: Using List Comprehension" }, { "code": null, "e": 1510, "s": 1335, "text": "List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. It is used to transform iterative statements into formulas." }, { "code": null, "e": 1519, "s": 1510, "text": "Example:" }, { "code": null, "e": 1527, "s": 1519, "text": "Python3" }, { "code": "# assign listl = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] # assign strings = 'geek' # list comprehensioncompare = [i for i in l if s in l] # check if string is present in listif len(compare) > 0: print(f'{s} is present in the list')else: print(f'{s} is not present in the list')", "e": 1818, "s": 1527, "text": null }, { "code": null, "e": 1826, "s": 1818, "text": "Output:" }, { "code": null, "e": 1855, "s": 1826, "text": "geeky is present in the list" }, { "code": null, "e": 1887, "s": 1855, "text": "Method #4: Using any() function" }, { "code": null, "e": 2135, "s": 1887, "text": "The any() function is used to check the existence of an element in the list. it’s like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list." }, { "code": null, "e": 2144, "s": 2135, "text": "Example:" }, { "code": null, "e": 2152, "s": 2144, "text": "Python3" }, { "code": "# assign listl = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] # assign strings = 'prime' # check if string is present in listif any(s in i for i in l): print(f'{s} is present in the list')else: print(f'{s} is not present in the list')", "e": 2395, "s": 2152, "text": null }, { "code": null, "e": 2403, "s": 2395, "text": "Output:" }, { "code": null, "e": 2436, "s": 2403, "text": "prime is not present in the list" }, { "code": null, "e": 2445, "s": 2436, "text": "sweetyty" }, { "code": null, "e": 2458, "s": 2445, "text": "singghakshay" }, { "code": null, "e": 2479, "s": 2458, "text": "Python list-programs" }, { "code": null, "e": 2502, "s": 2479, "text": "Python string-programs" }, { "code": null, "e": 2526, "s": 2502, "text": "Technical Scripter 2020" }, { "code": null, "e": 2533, "s": 2526, "text": "Python" }, { "code": null, "e": 2549, "s": 2533, "text": "Python Programs" }, { "code": null, "e": 2568, "s": 2549, "text": "Technical Scripter" }, { "code": null, "e": 2666, "s": 2568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2698, "s": 2666, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2725, "s": 2698, "text": "Python Classes and Objects" }, { "code": null, "e": 2746, "s": 2725, "text": "Python OOPs Concepts" }, { "code": null, "e": 2769, "s": 2746, "text": "Introduction To PYTHON" }, { "code": null, "e": 2825, "s": 2769, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2847, "s": 2825, "text": "Defaultdict in Python" }, { "code": null, "e": 2886, "s": 2847, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2924, "s": 2886, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2961, "s": 2924, "text": "Python Program for Fibonacci numbers" } ]
Which Book Should I Read Next?. Building a book recommendation system... | by Jordan Bean | Towards Data Science
I love to read but each time I finish a book I run into the same problem: What do I read next? The platforms I use should have plenty of data to help me solve this problem. However, Libby — through the Boston Public Library — doesn’t provide any recommendations and the ones from Goodreads, an Amazon company where I store my reading history, aren’t very good. I want an algorithm that presents me with targeted and relevant options and, as I’m not getting it through my current book providers, I figured I’d try to build it myself. For the full project code in Python, please click here. Data The best data set that I was able to find contains the top 10,000 books from Goodreads along with ratings by user, the books that a user wants to read, and any tags associated with the book by the reader. The data has its limitations. We only have access to the 10,000 most popular books and can’t layer in additional information like genre or book description. The data is as of 2017, so we miss out on new published books. That said, there’s certainly enough to build the framework for the algorithm. I was also able to export my own Goodreads data and while not every book that I read was in the top 10,000, ~60 matched after accounting for only the books that I wanted to be considered in the algorithm. Approach and Critical Thinking Based on the information available to us, I felt the best approach was to find the “most similar” users to me, then look for the most popular books (by average rating or number of times read) that they’ve read and I haven’t. This method — looking for patterns among users and applying those patterns to make recommendations — is called collaborative filtering. It’s essentially a simplified version of what Amazon would use when you see the “Customers who bought this item also bought” set of recommendations under a product. I initially framed out the article to focus on the steps of collaborative filtering, but after I finished the first set of code and looked at the results, I realized there was so much beyond the simple filtering and coding to take into consideration. Instead, the below will focus on how to use intuition and critical thinking to improve on initial results. Weighting and Standardization of the Inputs I realized that there needs to be a way to standardize the popularity of a book overall and within the relevant sample of similar readers. Otherwise, the most read book by similar users could be unduly influenced by the popularity of the book overall. This isn’t necessarily bad, but I wanted a way to adjust for sample vs. population. To overcome this, I chose to use a method of standardizing the results by dividing the number of times a book was rated (read) and marked as “to read” by the total number of reviews for the book. This ratio isn’t necessarily significant in any capacity other than helping us order the results and offset total popularity of a book. Then, when choosing which book to read, do I want the most popular book (by this ratio) or the one with the highest rating? Should I weight higher books from authors that I’ve already read and enjoyed? Or, should the one with the most 5-star ratings be preferred? The short answer is I chose to create a weighting of variables that matched my preferences. These could be changed in the call of the function if my preferences change: rec_weight_avg_rating = 0.5, rec_weight_read_ratio = 0.4, rec_weight_perc_4_5 = 0.1, rec_weight_perc_1_2 = -0.1, rec_weight_author_previous = 0.1 Series, New Authors, and My Ratings I noticed as I ran the algorithm that books that were part of a Series dominated the results even as I played around with the inputs. It’s logical — when someone reads and enjoys book 1 in a series, they’re likely to read book 2. If I’ve read book 1 too, those users are more likely to match with me. I noticed a pattern for books in a series where the format is typically: Title, (Series Name, #[1, 2, 3, etc.]). Therefore, a book in a series is easily identifiable by searching within the title for the “#” signal. It’s not perfect, but it captures most. Therefore, in the call to the function, I added a “Series” option that filters out all series if toggle is set to “No”. Likewise, the early recommendations were largely from the same authors as I’ve already read — again, understandable given the weighting. But, what if I want to read a new author? This is an easy fix — a “new_author_only” toggle was put into the function call so that I can control whether I only see new authors. Finally, after applying some of these factors, I noticed that my top recommendation was a series that I already read but didn’t necessarily enjoy — I had rated most books a 3/5. So, to offset this, I took the data that was used for the recommendation, searched each series within my own books, and if the average rating was less than a 4, I removed all instances from the data set. Books that I Want to Read I read a variety of types of books — fiction, non-fiction, business, etc. — but it doesn’t mean that everything I rated highly I want to be recommended to me. If we had genre information available, I could specify the genre type of the recommendation that I want, but we don’t have that, so I had to make a workaround. For the purposes of this exercise, I decided to create a new column and tag the books that I wanted to be considered within the scope of recommendation. Only these books are used for matching and then the results are adjusted for the other books that I’ve read but don’t want to recommend. Defining “Similar” How many books do I have to have in common with a user to be considered similar? Five? Ten? 20? How many readers should be included? The results of the algorithm change depending on how we define similar. I chose to use the 99th percentile of similar readers, which given the data set was 600+ people that collectively rated nearly 75,000 books. Again, this percentile can be changed in the function call. Recommendation Outputs Having layered in the above and more, what were the results? Let’s try a couple calls to the function: # Default call to the functionbook_recommendation_system(my_books = my_books, all_books = all_books, ratings = ratings, to_read = to_read, series = 'Yes', new_author_only = 'No', number_of_similar_quantile = 0.99, english_only = 'Yes', rec_weight_avg_rating = 0.5, rec_weight_read_ratio = 0.4, rec_weight_perc_4_5 = 0.1, rec_weight_perc_1_2 = -0.1, rec_weight_author_previous = 0.1, return_dataset = 'No', num_similar_ratings = 50) Conclusion My biggest takeaway from the project was: Collaborative filtering — or any recommendation system — can’t be viewed in a box. Layered on top must be the thinking and intuition that a computer can’t understand. Flexibility of the system and algorithm are far more valuable than the ability to simply execute on the code to make a program function. I thought that the project would start and end with the collaborative filtering code. Instead, I spent far more time on the follow up to refine the system rather than create it in the first place. Recommendations can be a powerful way to drive sales and satisfaction in a business. That said, the topic has to be approached carefully and thoughtfully as bad recommendations can be frustrating and deter future sales. Ultimately, helping someone discover a product or service that they were looking for — or didn’t even know they might want — can be a win for everyone involved and a fun challenge to solve as a data enthusiast.
[ { "code": null, "e": 220, "s": 47, "text": "I love to read but each time I finish a book I run into the same problem: What do I read next? The platforms I use should have plenty of data to help me solve this problem." }, { "code": null, "e": 408, "s": 220, "text": "However, Libby — through the Boston Public Library — doesn’t provide any recommendations and the ones from Goodreads, an Amazon company where I store my reading history, aren’t very good." }, { "code": null, "e": 580, "s": 408, "text": "I want an algorithm that presents me with targeted and relevant options and, as I’m not getting it through my current book providers, I figured I’d try to build it myself." }, { "code": null, "e": 636, "s": 580, "text": "For the full project code in Python, please click here." }, { "code": null, "e": 641, "s": 636, "text": "Data" }, { "code": null, "e": 846, "s": 641, "text": "The best data set that I was able to find contains the top 10,000 books from Goodreads along with ratings by user, the books that a user wants to read, and any tags associated with the book by the reader." }, { "code": null, "e": 1144, "s": 846, "text": "The data has its limitations. We only have access to the 10,000 most popular books and can’t layer in additional information like genre or book description. The data is as of 2017, so we miss out on new published books. That said, there’s certainly enough to build the framework for the algorithm." }, { "code": null, "e": 1349, "s": 1144, "text": "I was also able to export my own Goodreads data and while not every book that I read was in the top 10,000, ~60 matched after accounting for only the books that I wanted to be considered in the algorithm." }, { "code": null, "e": 1380, "s": 1349, "text": "Approach and Critical Thinking" }, { "code": null, "e": 1741, "s": 1380, "text": "Based on the information available to us, I felt the best approach was to find the “most similar” users to me, then look for the most popular books (by average rating or number of times read) that they’ve read and I haven’t. This method — looking for patterns among users and applying those patterns to make recommendations — is called collaborative filtering." }, { "code": null, "e": 1906, "s": 1741, "text": "It’s essentially a simplified version of what Amazon would use when you see the “Customers who bought this item also bought” set of recommendations under a product." }, { "code": null, "e": 2264, "s": 1906, "text": "I initially framed out the article to focus on the steps of collaborative filtering, but after I finished the first set of code and looked at the results, I realized there was so much beyond the simple filtering and coding to take into consideration. Instead, the below will focus on how to use intuition and critical thinking to improve on initial results." }, { "code": null, "e": 2308, "s": 2264, "text": "Weighting and Standardization of the Inputs" }, { "code": null, "e": 2644, "s": 2308, "text": "I realized that there needs to be a way to standardize the popularity of a book overall and within the relevant sample of similar readers. Otherwise, the most read book by similar users could be unduly influenced by the popularity of the book overall. This isn’t necessarily bad, but I wanted a way to adjust for sample vs. population." }, { "code": null, "e": 2976, "s": 2644, "text": "To overcome this, I chose to use a method of standardizing the results by dividing the number of times a book was rated (read) and marked as “to read” by the total number of reviews for the book. This ratio isn’t necessarily significant in any capacity other than helping us order the results and offset total popularity of a book." }, { "code": null, "e": 3409, "s": 2976, "text": "Then, when choosing which book to read, do I want the most popular book (by this ratio) or the one with the highest rating? Should I weight higher books from authors that I’ve already read and enjoyed? Or, should the one with the most 5-star ratings be preferred? The short answer is I chose to create a weighting of variables that matched my preferences. These could be changed in the call of the function if my preferences change:" }, { "code": null, "e": 3555, "s": 3409, "text": "rec_weight_avg_rating = 0.5, rec_weight_read_ratio = 0.4, rec_weight_perc_4_5 = 0.1, rec_weight_perc_1_2 = -0.1, rec_weight_author_previous = 0.1" }, { "code": null, "e": 3591, "s": 3555, "text": "Series, New Authors, and My Ratings" }, { "code": null, "e": 3892, "s": 3591, "text": "I noticed as I ran the algorithm that books that were part of a Series dominated the results even as I played around with the inputs. It’s logical — when someone reads and enjoys book 1 in a series, they’re likely to read book 2. If I’ve read book 1 too, those users are more likely to match with me." }, { "code": null, "e": 4268, "s": 3892, "text": "I noticed a pattern for books in a series where the format is typically: Title, (Series Name, #[1, 2, 3, etc.]). Therefore, a book in a series is easily identifiable by searching within the title for the “#” signal. It’s not perfect, but it captures most. Therefore, in the call to the function, I added a “Series” option that filters out all series if toggle is set to “No”." }, { "code": null, "e": 4581, "s": 4268, "text": "Likewise, the early recommendations were largely from the same authors as I’ve already read — again, understandable given the weighting. But, what if I want to read a new author? This is an easy fix — a “new_author_only” toggle was put into the function call so that I can control whether I only see new authors." }, { "code": null, "e": 4963, "s": 4581, "text": "Finally, after applying some of these factors, I noticed that my top recommendation was a series that I already read but didn’t necessarily enjoy — I had rated most books a 3/5. So, to offset this, I took the data that was used for the recommendation, searched each series within my own books, and if the average rating was less than a 4, I removed all instances from the data set." }, { "code": null, "e": 4989, "s": 4963, "text": "Books that I Want to Read" }, { "code": null, "e": 5308, "s": 4989, "text": "I read a variety of types of books — fiction, non-fiction, business, etc. — but it doesn’t mean that everything I rated highly I want to be recommended to me. If we had genre information available, I could specify the genre type of the recommendation that I want, but we don’t have that, so I had to make a workaround." }, { "code": null, "e": 5598, "s": 5308, "text": "For the purposes of this exercise, I decided to create a new column and tag the books that I wanted to be considered within the scope of recommendation. Only these books are used for matching and then the results are adjusted for the other books that I’ve read but don’t want to recommend." }, { "code": null, "e": 5617, "s": 5598, "text": "Defining “Similar”" }, { "code": null, "e": 6023, "s": 5617, "text": "How many books do I have to have in common with a user to be considered similar? Five? Ten? 20? How many readers should be included? The results of the algorithm change depending on how we define similar. I chose to use the 99th percentile of similar readers, which given the data set was 600+ people that collectively rated nearly 75,000 books. Again, this percentile can be changed in the function call." }, { "code": null, "e": 6046, "s": 6023, "text": "Recommendation Outputs" }, { "code": null, "e": 6149, "s": 6046, "text": "Having layered in the above and more, what were the results? Let’s try a couple calls to the function:" }, { "code": null, "e": 6760, "s": 6149, "text": "# Default call to the functionbook_recommendation_system(my_books = my_books, all_books = all_books, ratings = ratings, to_read = to_read, series = 'Yes', new_author_only = 'No', number_of_similar_quantile = 0.99, english_only = 'Yes', rec_weight_avg_rating = 0.5, rec_weight_read_ratio = 0.4, rec_weight_perc_4_5 = 0.1, rec_weight_perc_1_2 = -0.1, rec_weight_author_previous = 0.1, return_dataset = 'No', num_similar_ratings = 50)" }, { "code": null, "e": 6771, "s": 6760, "text": "Conclusion" }, { "code": null, "e": 6813, "s": 6771, "text": "My biggest takeaway from the project was:" }, { "code": null, "e": 7314, "s": 6813, "text": "Collaborative filtering — or any recommendation system — can’t be viewed in a box. Layered on top must be the thinking and intuition that a computer can’t understand. Flexibility of the system and algorithm are far more valuable than the ability to simply execute on the code to make a program function. I thought that the project would start and end with the collaborative filtering code. Instead, I spent far more time on the follow up to refine the system rather than create it in the first place." } ]
How to upload file with selenium (Python)?
We can upload files with Selenium using Python. This can be done with the help of the send_keys method. First, we shall identify the element which does the task of selecting the file path that has to be uploaded. This feature is only applied to elements having the type attribute set to file. Also, the tagname of the element should be input. Let us investigate the html code of an element having the above properties. Code Implementation. from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) driver.maximize_window() driver.get("https://www.tutorialspoint.com/selenium/selenium_automat ion_practice.htm") #to identify element s = driver.find_element_by_xpath("//input[@type='file']") #file path specified with send_keys s.send_keys("C:\\Users\\Pictures\\Logo.jpg")
[ { "code": null, "e": 1275, "s": 1062, "text": "We can upload files with Selenium using Python. This can be done with the help of the send_keys method. First, we shall identify the element which does the task of selecting the file path that has to be uploaded." }, { "code": null, "e": 1481, "s": 1275, "text": "This feature is only applied to elements having the type attribute set to file. Also, the tagname of the element should be input. Let us investigate the html code of an element having the above properties." }, { "code": null, "e": 1502, "s": 1481, "text": "Code Implementation." }, { "code": null, "e": 1901, "s": 1502, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.maximize_window()\n\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automat\nion_practice.htm\")\n#to identify element\ns = driver.find_element_by_xpath(\"//input[@type='file']\")\n#file path specified with send_keys\ns.send_keys(\"C:\\\\Users\\\\Pictures\\\\Logo.jpg\")" } ]
AngularJS | Application - GeeksforGeeks
31 Jul, 2020 Applications in AngularJS enable the creation of real-time Applications. There are four primary steps involved in creation of Applications in AngularJS: Creation of List for an Application. Adding elements in the List. Removing elements from the List. Error Handling Below are the steps for creations a Subject List Application: Step 1: To start with, choose the list which you want to create. Then using, controller and ng-repeat directive display the elements of the array as a list. <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script><h1 style="color: green">GeeksforGeeks</h1><body> <script>var app = angular.module("Subjects", []); app.controller("my_Ctrl", function($scope) { $scope.name = [ "English", "Maths", "Economics"];});</script> <div ng-app="Subjects" ng-controller="my_Ctrl"> <ul> <li ng-repeat="var in name">{{var}}</li> </ul></div> </body></html> Output: Step 2: Use the text field, in your application with the help of the ng-model directive. In the controller, make a function named addNewSubject, and use the value of the addSubject input field to add a subject to the ‘name’ array. Add a button, to add a new subject using an ng-click directive. <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><h1 style="color: green">GeeksforGeeks</h1><body> <script>var app = angular.module("Subjects", []); app.controller("my_Ctrl", function($scope) { $scope.name = ["English", "Maths", "Economics"]; $scope.addingNewSubject = function () { $scope.name.push($scope.addSubject); } });</script> <div ng-app="Subjects" ng-controller="my_Ctrl"> <ul> <li ng-repeat="x in name">{{x}}</li> </ul> <input ng-model="addSubject"> <button ng-click="addingNewSubject()">Add</button></div><p>Use input field for adding new subjects.</p></body></html> Output: Step 3: To remove a subject, make a remove function with the index as it’s a parameter. For each subject, make a span item and give them an ng-click directive to call the remove function. <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><h1 style="color: green">GeeksforGeeks</h1><body> <script>var app = angular.module("Subjects", []); app.controller("my_Ctrl", function($scope) { $scope.name = ["English", "Maths", "Economics"]; $scope.addingNewSubject = function () { $scope.name.push($scope.addSubject); } $scope.remove = function (x) { $scope.name.splice(x, 1); }});</script> <div ng-app="Subjects" ng-controller="my_Ctrl"> <ul> <li ng-repeat="x in name"> {{x}}<span ng-click="remove($index)">×</span></li> </ul> <input ng-model="addSubject"> <button ng-click="addingNewSubject()">Add</button></div><p>Use cross icon for removing subjects.</p></body></html> Output: Step 4: Errors need to be carefully handled.For example: If the same subject is added twice in the list, it displays an error message. <!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script><h1 style="color: green"> GeeksforGeeks</h1><body> <script>var app = angular.module("Subjects", []); app.controller("my_Ctrl", function($scope) { $scope.name = ["English", "Maths", "Economics"]; $scope.addingNewSubject = function () { $scope.errortext = ""; if (!$scope.addSubject) {return;} if ($scope.name.indexOf($scope.addSubject) == -1) { $scope.name.push($scope.addSubject); } else { $scope.errortext = "This subject is already in the list."; } } $scope.remove = function (x) { $scope.errortext = ""; $scope.name.splice(x, 1); }});</script> <div ng-app="Subjects" ng-controller="my_Ctrl"> <ul> <li ng-repeat="x in name"> {{x}}<span ng-click="remove($index)">×</span> </li> </ul> <input ng-model="addSubject"> <button ng-click="addingNewSubject()">Add</button> <p>{{errortext}}</p></div><p>Use cross icon for removing subjects.</p></body></html> Output: AngularJS-Basics Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Top 10 Angular Libraries For Web Developers Angular | keyup event Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 28271, "s": 28243, "text": "\n31 Jul, 2020" }, { "code": null, "e": 28424, "s": 28271, "text": "Applications in AngularJS enable the creation of real-time Applications. There are four primary steps involved in creation of Applications in AngularJS:" }, { "code": null, "e": 28461, "s": 28424, "text": "Creation of List for an Application." }, { "code": null, "e": 28490, "s": 28461, "text": "Adding elements in the List." }, { "code": null, "e": 28523, "s": 28490, "text": "Removing elements from the List." }, { "code": null, "e": 28538, "s": 28523, "text": "Error Handling" }, { "code": null, "e": 28600, "s": 28538, "text": "Below are the steps for creations a Subject List Application:" }, { "code": null, "e": 28757, "s": 28600, "text": "Step 1: To start with, choose the list which you want to create. Then using, controller and ng-repeat directive display the elements of the array as a list." }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script><h1 style=\"color: green\">GeeksforGeeks</h1><body> <script>var app = angular.module(\"Subjects\", []); app.controller(\"my_Ctrl\", function($scope) { $scope.name = [ \"English\", \"Maths\", \"Economics\"];});</script> <div ng-app=\"Subjects\" ng-controller=\"my_Ctrl\"> <ul> <li ng-repeat=\"var in name\">{{var}}</li> </ul></div> </body></html>", "e": 29224, "s": 28757, "text": null }, { "code": null, "e": 29232, "s": 29224, "text": "Output:" }, { "code": null, "e": 29527, "s": 29232, "text": "Step 2: Use the text field, in your application with the help of the ng-model directive. In the controller, make a function named addNewSubject, and use the value of the addSubject input field to add a subject to the ‘name’ array. Add a button, to add a new subject using an ng-click directive." }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><h1 style=\"color: green\">GeeksforGeeks</h1><body> <script>var app = angular.module(\"Subjects\", []); app.controller(\"my_Ctrl\", function($scope) { $scope.name = [\"English\", \"Maths\", \"Economics\"]; $scope.addingNewSubject = function () { $scope.name.push($scope.addSubject); } });</script> <div ng-app=\"Subjects\" ng-controller=\"my_Ctrl\"> <ul> <li ng-repeat=\"x in name\">{{x}}</li> </ul> <input ng-model=\"addSubject\"> <button ng-click=\"addingNewSubject()\">Add</button></div><p>Use input field for adding new subjects.</p></body></html>", "e": 30199, "s": 29527, "text": null }, { "code": null, "e": 30207, "s": 30199, "text": "Output:" }, { "code": null, "e": 30395, "s": 30207, "text": "Step 3: To remove a subject, make a remove function with the index as it’s a parameter. For each subject, make a span item and give them an ng-click directive to call the remove function." }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><h1 style=\"color: green\">GeeksforGeeks</h1><body> <script>var app = angular.module(\"Subjects\", []); app.controller(\"my_Ctrl\", function($scope) { $scope.name = [\"English\", \"Maths\", \"Economics\"]; $scope.addingNewSubject = function () { $scope.name.push($scope.addSubject); } $scope.remove = function (x) { $scope.name.splice(x, 1); }});</script> <div ng-app=\"Subjects\" ng-controller=\"my_Ctrl\"> <ul> <li ng-repeat=\"x in name\"> {{x}}<span ng-click=\"remove($index)\">×</span></li> </ul> <input ng-model=\"addSubject\"> <button ng-click=\"addingNewSubject()\">Add</button></div><p>Use cross icon for removing subjects.</p></body></html>", "e": 31184, "s": 30395, "text": null }, { "code": null, "e": 31192, "s": 31184, "text": "Output:" }, { "code": null, "e": 31327, "s": 31192, "text": "Step 4: Errors need to be carefully handled.For example: If the same subject is added twice in the list, it displays an error message." }, { "code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script><h1 style=\"color: green\"> GeeksforGeeks</h1><body> <script>var app = angular.module(\"Subjects\", []); app.controller(\"my_Ctrl\", function($scope) { $scope.name = [\"English\", \"Maths\", \"Economics\"]; $scope.addingNewSubject = function () { $scope.errortext = \"\"; if (!$scope.addSubject) {return;} if ($scope.name.indexOf($scope.addSubject) == -1) { $scope.name.push($scope.addSubject); } else { $scope.errortext = \"This subject is already in the list.\"; } } $scope.remove = function (x) { $scope.errortext = \"\"; $scope.name.splice(x, 1); }});</script> <div ng-app=\"Subjects\" ng-controller=\"my_Ctrl\"> <ul> <li ng-repeat=\"x in name\"> {{x}}<span ng-click=\"remove($index)\">×</span> </li> </ul> <input ng-model=\"addSubject\"> <button ng-click=\"addingNewSubject()\">Add</button> <p>{{errortext}}</p></div><p>Use cross icon for removing subjects.</p></body></html>", "e": 32440, "s": 31327, "text": null }, { "code": null, "e": 32448, "s": 32440, "text": "Output:" }, { "code": null, "e": 32465, "s": 32448, "text": "AngularJS-Basics" }, { "code": null, "e": 32472, "s": 32465, "text": "Picked" }, { "code": null, "e": 32482, "s": 32472, "text": "AngularJS" }, { "code": null, "e": 32499, "s": 32482, "text": "Web Technologies" }, { "code": null, "e": 32597, "s": 32499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32617, "s": 32597, "text": "Angular File Upload" }, { "code": null, "e": 32661, "s": 32617, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 32683, "s": 32661, "text": "Angular | keyup event" }, { "code": null, "e": 32714, "s": 32683, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 32756, "s": 32714, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 32798, "s": 32756, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32860, "s": 32798, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32903, "s": 32860, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32936, "s": 32903, "text": "Installation of Node.js on Linux" } ]
How to implement a constructor reference with one or more arguments in Java?
A method reference can also be applicable to constructors in Java 8. A constructor reference can be created using the class name and a new keyword. The constructor reference can be assigned to any functional interface reference that defines a method compatible with the constructor. <Class-Name>::new import java.util.function.*; @FunctionalInterface interface MyFunctionalInterface { Student getStudent(String name); } public class ConstructorReferenceTest1 { public static void main(String[] args) { MyFunctionalInterface mf = Student::new; Function<Sttring, Student> f1 = Student::new; // Constructor Reference Function<String, Student> f2 = (name) -> new Student(name); System.out.println(mf.getStudent("Adithya").getName()); System.out.println(f1.apply("Jai").getName()); System.out.println(f2.apply("Jai").getName()); } } // Student class class Student { private String name; public Student(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Adithya Jai Jai import java.util.function.*; @FunctionalInterface interface MyFunctionalInterface { Student getStudent(int id, String name); } public class ConstructorReferenceTest2 { public static void main(String[] args) { MyFunctionalInterface mf = Student::new; // Constructor Reference BiFunction<Integer, String, Student> f1 = Student::new; BiFunction<Integer, String, Student> f2 = (id, name) -> new Student(id,name); System.out.println(mf.getStudent(101, "Adithya").getId()); System.out.println(f1.apply(111, "Jai").getId()); System.out.println(f2.apply(121, "Jai").getId()); } } // Student class class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 101 111 121
[ { "code": null, "e": 1345, "s": 1062, "text": "A method reference can also be applicable to constructors in Java 8. A constructor reference can be created using the class name and a new keyword. The constructor reference can be assigned to any functional interface reference that defines a method compatible with the constructor." }, { "code": null, "e": 1363, "s": 1345, "text": "<Class-Name>::new" }, { "code": null, "e": 2183, "s": 1363, "text": "import java.util.function.*;\n\n@FunctionalInterface\ninterface MyFunctionalInterface {\n Student getStudent(String name);\n}\npublic class ConstructorReferenceTest1 {\n public static void main(String[] args) {\n MyFunctionalInterface mf = Student::new;\n\n Function<Sttring, Student> f1 = Student::new; // Constructor Reference\n Function<String, Student> f2 = (name) -> new Student(name);\n\n System.out.println(mf.getStudent(\"Adithya\").getName());\n System.out.println(f1.apply(\"Jai\").getName());\n System.out.println(f2.apply(\"Jai\").getName());\n }\n}\n\n// Student class\nclass Student {\n private String name;\n public Student(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 2199, "s": 2183, "text": "Adithya\nJai\nJai" }, { "code": null, "e": 3214, "s": 2199, "text": "import java.util.function.*;\n\n@FunctionalInterface\ninterface MyFunctionalInterface {\n Student getStudent(int id, String name);\n}\npublic class ConstructorReferenceTest2 {\n public static void main(String[] args) {\n MyFunctionalInterface mf = Student::new; // Constructor Reference\n\n BiFunction<Integer, String, Student> f1 = Student::new;\n BiFunction<Integer, String, Student> f2 = (id, name) -> new Student(id,name);\n\n System.out.println(mf.getStudent(101, \"Adithya\").getId());\n System.out.println(f1.apply(111, \"Jai\").getId());\n System.out.println(f2.apply(121, \"Jai\").getId());\n }\n}\n\n// Student class\nclass Student {\n private int id;\n private String name;\n public Student(int id, String name) {\n this.id = id;\n this.name = name;\n }\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 3226, "s": 3214, "text": "101\n111\n121" } ]
Spring MVC - Simple Url Handler Mapping Example
The following example shows how to use Simple URL Handler Mapping using the Spring Web MVC framework. The SimpleUrlHandlerMapping class helps to explicitly-map URLs with their controllers respectively. <beans> <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/WEB-INF/jsp/"/> <property name = "suffix" value = ".jsp"/> </bean> <bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name = "mappings"> <props> <prop key = "/welcome.htm">welcomeController</prop> <prop key = "/helloWorld.htm">helloController</prop> </props> </property> </bean> <bean id = "helloController" class = "com.tutorialspoint.HelloController" /> <bean id = "welcomeController" class = "com.tutorialspoint.WelcomeController"/> </beans> For example, using above configuration, if URI /helloWorld.htm is requested, DispatcherServlet will forward the request to the HelloController. /helloWorld.htm is requested, DispatcherServlet will forward the request to the HelloController. /welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController. /welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("hello"); model.addObject("message", "Hello World!"); return model; } } package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class WelcomeController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("welcome"); model.addObject("message", "Welcome!"); return model; } } <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/WEB-INF/jsp/"/> <property name = "suffix" value = ".jsp"/> </bean> <bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name = "mappings"> <props> <prop key = "/welcome.htm">welcomeController</prop> <prop key = "/helloWorld.htm">helloController</prop> </props> </property> </bean> <bean id = "helloController" class = "com.tutorialspoint.HelloController" /> <bean id = "welcomeController" class = "com.tutorialspoint.WelcomeController"/> </beans> <%@ page contentType = "text/html; charset = UTF-8" %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> <%@ page contentType = "text/html; charset = UTF-8" %> <html> <head> <title>Welcome</title> </head> <body> <h2>${message}</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use the Export → WAR File option and save your TestWeb.war file in Tomcat's webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder by using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL http://localhost:8080/TestWeb/welcome.htm and you should see the following result if everything is fine with your Spring Web Application. Print Add Notes Bookmark this page
[ { "code": null, "e": 2993, "s": 2791, "text": "The following example shows how to use Simple URL Handler Mapping using the Spring Web MVC framework. The SimpleUrlHandlerMapping class helps to explicitly-map URLs with their controllers respectively." }, { "code": null, "e": 3699, "s": 2993, "text": "<beans>\n <bean class = \"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name = \"prefix\" value = \"/WEB-INF/jsp/\"/>\n <property name = \"suffix\" value = \".jsp\"/>\n </bean>\n\n <bean class = \"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping\">\n <property name = \"mappings\">\n <props>\n <prop key = \"/welcome.htm\">welcomeController</prop>\t\t \n <prop key = \"/helloWorld.htm\">helloController</prop>\n </props>\n </property>\n </bean>\n\n <bean id = \"helloController\" class = \"com.tutorialspoint.HelloController\" />\n\n <bean id = \"welcomeController\" class = \"com.tutorialspoint.WelcomeController\"/> \n</beans>" }, { "code": null, "e": 3746, "s": 3699, "text": "For example, using above configuration, if URI" }, { "code": null, "e": 3843, "s": 3746, "text": "/helloWorld.htm is requested, DispatcherServlet will forward the request to the HelloController." }, { "code": null, "e": 3940, "s": 3843, "text": "/helloWorld.htm is requested, DispatcherServlet will forward the request to the HelloController." }, { "code": null, "e": 4036, "s": 3940, "text": "/welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController." }, { "code": null, "e": 4132, "s": 4036, "text": "/welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController." }, { "code": null, "e": 4303, "s": 4132, "text": "To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework." }, { "code": null, "e": 4878, "s": 4303, "text": "package com.tutorialspoint;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.mvc.AbstractController;\n\npublic class HelloController extends AbstractController{\n \n @Override\n protected ModelAndView handleRequestInternal(HttpServletRequest request,\n HttpServletResponse response) throws Exception {\n ModelAndView model = new ModelAndView(\"hello\");\n model.addObject(\"message\", \"Hello World!\");\n return model;\n }\n}" }, { "code": null, "e": 5453, "s": 4878, "text": "package com.tutorialspoint;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.web.servlet.mvc.AbstractController;\n\npublic class WelcomeController extends AbstractController{\n \n @Override\n protected ModelAndView handleRequestInternal(HttpServletRequest request,\n HttpServletResponse response) throws Exception {\n ModelAndView model = new ModelAndView(\"welcome\");\n model.addObject(\"message\", \"Welcome!\");\n return model;\n }\n}" }, { "code": null, "e": 6610, "s": 5453, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <bean class = \"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name = \"prefix\" value = \"/WEB-INF/jsp/\"/>\n <property name = \"suffix\" value = \".jsp\"/>\n </bean>\n\n <bean class = \"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping\">\n <property name = \"mappings\">\n <props>\n <prop key = \"/welcome.htm\">welcomeController</prop>\t\t \n <prop key = \"/helloWorld.htm\">helloController</prop>\n </props>\n </property>\n </bean>\n\n <bean id = \"helloController\" class = \"com.tutorialspoint.HelloController\" />\n\n <bean id = \"welcomeController\" class = \"com.tutorialspoint.WelcomeController\"/> \n</beans>" }, { "code": null, "e": 6781, "s": 6610, "text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<html>\n <head>\n <title>Hello World</title>\n </head>\n <body>\n <h2>${message}</h2>\n </body>\n</html>" }, { "code": null, "e": 6948, "s": 6781, "text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<html>\n <head>\n <title>Welcome</title>\n </head>\n <body>\n <h2>${message}</h2>\n </body>\n</html>" }, { "code": null, "e": 7162, "s": 6948, "text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use the Export → WAR File option and save your TestWeb.war file in Tomcat's webapps folder." }, { "code": null, "e": 7447, "s": 7162, "text": "Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder by using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application." }, { "code": null, "e": 7595, "s": 7447, "text": "Try a URL http://localhost:8080/TestWeb/welcome.htm and you should see the following result if everything is fine with your Spring Web Application." }, { "code": null, "e": 7602, "s": 7595, "text": " Print" }, { "code": null, "e": 7613, "s": 7602, "text": " Add Notes" } ]
How to change the mode of a file using Python?
To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use: >>> import os >>> os.chmod('my_file', 0o777) You can also use flags from the stat module. You can read more about these flags here: http://docs.python.org/2/library/stat.html Another way to acheive it is using a subprocess call: >>> import subprocess >>> subprocess.call(['chmod', '0444', 'my_file'])
[ { "code": null, "e": 1328, "s": 1062, "text": "To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use:" }, { "code": null, "e": 1373, "s": 1328, "text": ">>> import os\n>>> os.chmod('my_file', 0o777)" }, { "code": null, "e": 1503, "s": 1373, "text": "You can also use flags from the stat module. You can read more about these flags here: http://docs.python.org/2/library/stat.html" }, { "code": null, "e": 1557, "s": 1503, "text": "Another way to acheive it is using a subprocess call:" }, { "code": null, "e": 1629, "s": 1557, "text": ">>> import subprocess\n>>> subprocess.call(['chmod', '0444', 'my_file'])" } ]
PHP Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. A cookie is created with the setcookie() function. Only the name parameter is required. All other parameters are optional. The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer). We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set: Note: The setcookie() function must appear BEFORE the <html> tag. Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead). To modify a cookie, just set (again) the cookie using the setcookie() function: To delete a cookie, use the setcookie() function with an expiration date in the past: The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable: For a complete reference of Network functions, go to our complete PHP Network Reference. Create a cookie named "username". ("username", "John", time() + (86400 * 30), "/"); We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 265, "s": 0, "text": "A cookie is often used to identify a user. A cookie is a small file that the \nserver embeds on the user's computer. Each time the same computer requests a \npage with a browser, it will send the cookie too. With PHP, you can both create \nand retrieve cookie values." }, { "code": null, "e": 316, "s": 265, "text": "A cookie is created with the setcookie() function." }, { "code": null, "e": 389, "s": 316, "text": "Only the name parameter is required. All other parameters are \noptional." }, { "code": null, "e": 629, "s": 389, "text": "The following example creates a cookie named \"user\" with the value \"John \nDoe\". The cookie will expire after 30 days (86400 * 30). The \"/\" means that the \ncookie is available in entire website (otherwise, select the directory you \nprefer)." }, { "code": null, "e": 783, "s": 629, "text": "We then retrieve the value of the cookie \"user\" (using the global variable \n$_COOKIE). We also use the isset() function to find out if the cookie is set:" }, { "code": null, "e": 851, "s": 785, "text": "Note: The setcookie() function must appear BEFORE the <html> tag." }, { "code": null, "e": 1030, "s": 851, "text": "Note: The value of the cookie is automatically URLencoded when \nsending the cookie, and automatically decoded when received (to prevent \nURLencoding, use setrawcookie() instead)." }, { "code": null, "e": 1110, "s": 1030, "text": "To modify a cookie, just set (again) the cookie using the setcookie() function:" }, { "code": null, "e": 1197, "s": 1110, "text": "To delete a cookie, use the setcookie() function with an expiration date in \nthe past:" }, { "code": null, "e": 1391, "s": 1197, "text": "The following example creates a small script that checks whether cookies are \nenabled. First, try to create a test cookie with the setcookie() function, then \ncount the $_COOKIE array variable:" }, { "code": null, "e": 1480, "s": 1391, "text": "For a complete reference of Network functions, go to our complete\nPHP Network Reference." }, { "code": null, "e": 1514, "s": 1480, "text": "Create a cookie named \"username\"." }, { "code": null, "e": 1565, "s": 1514, "text": "(\"username\", \"John\", time() + (86400 * 30), \"/\");\n" }, { "code": null, "e": 1598, "s": 1565, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1640, "s": 1598, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1747, "s": 1640, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1766, "s": 1747, "text": "[email protected]" } ]
How to call Python file from within PHP?
To call a Python file from within a PHP file, you need to call it using the shell_exec function. <?php $command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; ?> This will call the script. But in your script at the top, you'll need to specify the interpreter as well. So in your py file, add the following line at the top: #!/usr/bin/env python Alternatively you can also provide the interpreter when executing the command. <?php $command = escapeshellcmd('python3 /usr/custom/test.py'); $output = shell_exec($command); echo $output; ?>
[ { "code": null, "e": 1159, "s": 1062, "text": "To call a Python file from within a PHP file, you need to call it using the shell_exec function." }, { "code": null, "e": 1276, "s": 1159, "text": "<?php\n $command = escapeshellcmd('/usr/custom/test.py');\n $output = shell_exec($command);\n echo $output;\n?>" }, { "code": null, "e": 1437, "s": 1276, "text": "This will call the script. But in your script at the top, you'll need to specify the interpreter as well. So in your py file, add the following line at the top:" }, { "code": null, "e": 1459, "s": 1437, "text": "#!/usr/bin/env python" }, { "code": null, "e": 1538, "s": 1459, "text": "Alternatively you can also provide the interpreter when executing the command." }, { "code": null, "e": 1663, "s": 1538, "text": "<?php\n $command = escapeshellcmd('python3 /usr/custom/test.py');\n $output = shell_exec($command);\n echo $output;\n?>" } ]
Python - String concatenation in Heterogeneous list - GeeksforGeeks
04 Oct, 2021 Sometimes, while working with Python, we can come across a problem in which we require to find the concatenation of strings. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + conditions We can employ a brute force method to type caste check each element, if its a string we concatenate it. This can ensure that only strings are concatenated and hence can solve the problem. Python3 # Python3 code to demonstrate working of# String concatenation in Heterogeneous list# using loop + conditions # initializing listtest_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best'] # printing original listprint("The original list is : " + str(test_list)) # String concatenation in Heterogeneous list# using loop + conditionsres = ''for ele in test_list: if type(ele) == str: res += ele # printing result print("Concatenation of strings in list : " + str(res)) The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best'] Concatenation of strings in list : gfg is best Method #2 : Using join() + isinstance() This problem can also be solved using the inbuilt function of join() and it also supports the instance filter using isinstance() which can be feeded with strings and hence solve the problem. Python3 # Python3 code to demonstrate working of# String concatenation in Heterogeneous list# using join() + isinstance() # initializing listtest_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best'] # printing original listprint("The original list is : " + str(test_list)) # String concatenation in Heterogeneous list# using join() + isinstance()res = "".join(filter(lambda i: isinstance(i, str), test_list)) # printing result print("Concatenation of strings in list : " + str(res)) The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best'] Concatenation of strings in list : gfg is best anikaseth98 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 23901, "s": 23873, "text": "\n04 Oct, 2021" }, { "code": null, "e": 24207, "s": 23901, "text": "Sometimes, while working with Python, we can come across a problem in which we require to find the concatenation of strings. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24431, "s": 24207, "text": "Method #1 : Using loop + conditions We can employ a brute force method to type caste check each element, if its a string we concatenate it. This can ensure that only strings are concatenated and hence can solve the problem." }, { "code": null, "e": 24439, "s": 24431, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# String concatenation in Heterogeneous list# using loop + conditions # initializing listtest_list = [5, 6, \"gfg \", 8, (5, 7), ' is', 9, ' best'] # printing original listprint(\"The original list is : \" + str(test_list)) # String concatenation in Heterogeneous list# using loop + conditionsres = ''for ele in test_list: if type(ele) == str: res += ele # printing result print(\"Concatenation of strings in list : \" + str(res))", "e": 24927, "s": 24439, "text": null }, { "code": null, "e": 25043, "s": 24927, "text": "The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best']\nConcatenation of strings in list : gfg is best" }, { "code": null, "e": 25276, "s": 25045, "text": "Method #2 : Using join() + isinstance() This problem can also be solved using the inbuilt function of join() and it also supports the instance filter using isinstance() which can be feeded with strings and hence solve the problem." }, { "code": null, "e": 25284, "s": 25276, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# String concatenation in Heterogeneous list# using join() + isinstance() # initializing listtest_list = [5, 6, \"gfg \", 8, (5, 7), ' is', 9, ' best'] # printing original listprint(\"The original list is : \" + str(test_list)) # String concatenation in Heterogeneous list# using join() + isinstance()res = \"\".join(filter(lambda i: isinstance(i, str), test_list)) # printing result print(\"Concatenation of strings in list : \" + str(res))", "e": 25762, "s": 25284, "text": null }, { "code": null, "e": 25878, "s": 25762, "text": "The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best']\nConcatenation of strings in list : gfg is best" }, { "code": null, "e": 25892, "s": 25880, "text": "anikaseth98" }, { "code": null, "e": 25913, "s": 25892, "text": "Python list-programs" }, { "code": null, "e": 25920, "s": 25913, "text": "Python" }, { "code": null, "e": 25936, "s": 25920, "text": "Python Programs" }, { "code": null, "e": 26034, "s": 25936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26043, "s": 26034, "text": "Comments" }, { "code": null, "e": 26056, "s": 26043, "text": "Old Comments" }, { "code": null, "e": 26088, "s": 26056, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26144, "s": 26088, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26186, "s": 26144, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26228, "s": 26186, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26264, "s": 26228, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26286, "s": 26264, "text": "Defaultdict in Python" }, { "code": null, "e": 26325, "s": 26286, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26371, "s": 26325, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26409, "s": 26371, "text": "Python | Convert a list to dictionary" } ]
Python program to split a string and join with comma
Suppose we have few words that are separated by spaces. We have to split these words to form a list, then join them into a string by placing comma in-between. So, if the input is like s = "Programming Python Language Easy Funny", then the output will be Programming, Python, Language, Easy, Funny To solve this, we will follow these steps − words := a list of words by applying split function on s with delimiter " " blank space. words := a list of words by applying split function on s with delimiter " " blank space. ret := join each items present in words and place ", " in between each pair of words ret := join each items present in words and place ", " in between each pair of words return ret return ret Let us see the following implementation to get better understanding def solve(s): words = s.split(' ') ret = ', '.join(words) return ret s = "Programming Python Language Easy Funny" print(solve(s)) "Programming Python Language Easy Funny" Programming, Python, Language, Easy, Funny
[ { "code": null, "e": 1221, "s": 1062, "text": "Suppose we have few words that are separated by spaces. We have to split these words to form a list, then join them into a string by placing comma in-between." }, { "code": null, "e": 1359, "s": 1221, "text": "So, if the input is like s = \"Programming Python Language Easy Funny\", then the output will be Programming, Python, Language, Easy, Funny" }, { "code": null, "e": 1403, "s": 1359, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1492, "s": 1403, "text": "words := a list of words by applying split function on s with delimiter \" \" blank space." }, { "code": null, "e": 1581, "s": 1492, "text": "words := a list of words by applying split function on s with delimiter \" \" blank space." }, { "code": null, "e": 1666, "s": 1581, "text": "ret := join each items present in words and place \", \" in between each pair of words" }, { "code": null, "e": 1751, "s": 1666, "text": "ret := join each items present in words and place \", \" in between each pair of words" }, { "code": null, "e": 1762, "s": 1751, "text": "return ret" }, { "code": null, "e": 1773, "s": 1762, "text": "return ret" }, { "code": null, "e": 1841, "s": 1773, "text": "Let us see the following implementation to get better understanding" }, { "code": null, "e": 1981, "s": 1841, "text": "def solve(s):\n words = s.split(' ')\n ret = ', '.join(words)\n return ret\n\ns = \"Programming Python Language Easy Funny\"\nprint(solve(s))" }, { "code": null, "e": 2022, "s": 1981, "text": "\"Programming Python Language Easy Funny\"" }, { "code": null, "e": 2065, "s": 2022, "text": "Programming, Python, Language, Easy, Funny" } ]
Ridiculously Powerful Functions in Python | Towards Data Science
Python offers a bunch of built-in functions! Python programmers use them to write code quickly, clearly, and in a more Pythonic way. Here, I am discussing the 5 most powerful, speedy built-in functions which I mastered (and certainly you can) in 1 minute or less. ⏳ I use them a lot in my projects to make the code faster, and more understandable way. These built-in functions will keep your program clean, clear, short, and simple to understand. Let’s jump in! The map() function applies a specified function on each item in an iterable. Its syntax itself is self-explanatory. map(function,iterable) For example, let's make a function to return an input word in the upper case. And then map this function to each item in the list. That's it! The function makeupper() is applied to each item in the list colors. In my last project, the function map() was 1.5X faster ⚡ than a for loop to apply a complex function on each item in the list. Here is an execution time comparison for a simple function ⏳. Along with faster execution, map() function improves the readability of the code. Sometimes, while working with iterators, we also need to have a count of iterations. ♻️ enumerate() is the solution!! The enumerate() function adds a counter to an iterable and returns it in a form of an enumerated object. This object can be used directly in for loops and even can be converted into a list of tuples. Here is its syntax: enumerate(iterable, start=0) An iterable must be a sequence or some object which supports iteration. As Python is a 0-indexed language, the iteration counter starts at 0 by default. Certainly, you can change the starting number of the iteration counter. Let’s continue with the colors example from the previous function. colors = ['red', 'yellow', 'green', 'black']result = enumerate(colors) In this example, the result is an enumerated object, which can be directly used in a for loop and even can be converted into a list. The zip() function is used to use the similar index of multiple containers so that they can be used as a single entity. The syntax is as simple as the definition: zip(iterables) It produces a tuple with one item from each container or iterable. Let’s have an example of two lists. colors = ['red', 'yellow', 'green', 'black']fruits = ['apple', 'pineapple', 'grapes', 'cherry'] Using zip() function in a for loop, zip() is often used in cases where the containers are assumed to be of equal length. However, if the containers have different lengths, the function zip() stops when the smallest container is exhausted. An example is below 👇 Using zip() function when containers have different sizes or lengths, You can pass lists, tuples, sets, or dictionaries through the zip() function. Often, we need to process an iterable and extract those items that satisfy a given condition. filter() can save your time and efforts!! The filter() extracts elements from an iterable such as list, tuples where the extracted elements are are the ones where the function returns true. Here is a syntax:filter(function, iterable) For easier digestion, let’s take an example. Let’s create a function to check if the word is in upper case or not. And then use the filter() to extract all the words from the iterable which are in uppercase. Here is official documentation about filter(). 🚩 Learn how to define a function in a single line using Ternary conditional. Lambda functions are used to create anonymous functions i.e. functions without a name. They are useful when we need to create a function to do a single operation and can be written in one line. Its syntax is: lambda parameters: expression 🎯 Lambda functions can have any number of parameters but can only have one expression. For example, lambda x: x+2 That’s it!! Just now I created a function that takes a single input parameter x and adds 2 to it. However, as you can see this is an anonymous function, it can not be called at a later stage. Hence, to call it any time in the program, lambda function can be assigned to a function object like this, add2 = lambda x: x+2 Calling this function is exactly the same as calling a function that was defined with the def keyword. For example, add2(10) # It will return 12 as output Lambda function can be a good one-liner in some situations such as List comprehensions. As shown in the above picture, newlist is generated with a single line of code by using the lambda function. Summing up, I found these built-in functions quite handy while using Python for Data Analysis as well as complex automation tasks. Some of them such as zip() , map() are useful in many cases while others such as Lambda function serve as the best one-liner in some situations. 🚩 5 Most Powerful One-Liners can even further boost your coding. towardsdatascience.com Now you can become a Medium member by signing up here to read all the stories published by me and other writers. If you do so, I will get a small portion of your fees. Feel free to join my email list to stay updated about my writing. Thank you for reading and investing your time!!
[ { "code": null, "e": 216, "s": 171, "text": "Python offers a bunch of built-in functions!" }, { "code": null, "e": 304, "s": 216, "text": "Python programmers use them to write code quickly, clearly, and in a more Pythonic way." }, { "code": null, "e": 437, "s": 304, "text": "Here, I am discussing the 5 most powerful, speedy built-in functions which I mastered (and certainly you can) in 1 minute or less. ⏳" }, { "code": null, "e": 523, "s": 437, "text": "I use them a lot in my projects to make the code faster, and more understandable way." }, { "code": null, "e": 618, "s": 523, "text": "These built-in functions will keep your program clean, clear, short, and simple to understand." }, { "code": null, "e": 633, "s": 618, "text": "Let’s jump in!" }, { "code": null, "e": 749, "s": 633, "text": "The map() function applies a specified function on each item in an iterable. Its syntax itself is self-explanatory." }, { "code": null, "e": 772, "s": 749, "text": "map(function,iterable)" }, { "code": null, "e": 903, "s": 772, "text": "For example, let's make a function to return an input word in the upper case. And then map this function to each item in the list." }, { "code": null, "e": 983, "s": 903, "text": "That's it! The function makeupper() is applied to each item in the list colors." }, { "code": null, "e": 1110, "s": 983, "text": "In my last project, the function map() was 1.5X faster ⚡ than a for loop to apply a complex function on each item in the list." }, { "code": null, "e": 1172, "s": 1110, "text": "Here is an execution time comparison for a simple function ⏳." }, { "code": null, "e": 1254, "s": 1172, "text": "Along with faster execution, map() function improves the readability of the code." }, { "code": null, "e": 1342, "s": 1254, "text": "Sometimes, while working with iterators, we also need to have a count of iterations. ♻️" }, { "code": null, "e": 1372, "s": 1342, "text": "enumerate() is the solution!!" }, { "code": null, "e": 1572, "s": 1372, "text": "The enumerate() function adds a counter to an iterable and returns it in a form of an enumerated object. This object can be used directly in for loops and even can be converted into a list of tuples." }, { "code": null, "e": 1621, "s": 1572, "text": "Here is its syntax: enumerate(iterable, start=0)" }, { "code": null, "e": 1846, "s": 1621, "text": "An iterable must be a sequence or some object which supports iteration. As Python is a 0-indexed language, the iteration counter starts at 0 by default. Certainly, you can change the starting number of the iteration counter." }, { "code": null, "e": 1913, "s": 1846, "text": "Let’s continue with the colors example from the previous function." }, { "code": null, "e": 1984, "s": 1913, "text": "colors = ['red', 'yellow', 'green', 'black']result = enumerate(colors)" }, { "code": null, "e": 2117, "s": 1984, "text": "In this example, the result is an enumerated object, which can be directly used in a for loop and even can be converted into a list." }, { "code": null, "e": 2237, "s": 2117, "text": "The zip() function is used to use the similar index of multiple containers so that they can be used as a single entity." }, { "code": null, "e": 2295, "s": 2237, "text": "The syntax is as simple as the definition: zip(iterables)" }, { "code": null, "e": 2362, "s": 2295, "text": "It produces a tuple with one item from each container or iterable." }, { "code": null, "e": 2398, "s": 2362, "text": "Let’s have an example of two lists." }, { "code": null, "e": 2494, "s": 2398, "text": "colors = ['red', 'yellow', 'green', 'black']fruits = ['apple', 'pineapple', 'grapes', 'cherry']" }, { "code": null, "e": 2530, "s": 2494, "text": "Using zip() function in a for loop," }, { "code": null, "e": 2755, "s": 2530, "text": "zip() is often used in cases where the containers are assumed to be of equal length. However, if the containers have different lengths, the function zip() stops when the smallest container is exhausted. An example is below 👇" }, { "code": null, "e": 2825, "s": 2755, "text": "Using zip() function when containers have different sizes or lengths," }, { "code": null, "e": 2903, "s": 2825, "text": "You can pass lists, tuples, sets, or dictionaries through the zip() function." }, { "code": null, "e": 2997, "s": 2903, "text": "Often, we need to process an iterable and extract those items that satisfy a given condition." }, { "code": null, "e": 3039, "s": 2997, "text": "filter() can save your time and efforts!!" }, { "code": null, "e": 3187, "s": 3039, "text": "The filter() extracts elements from an iterable such as list, tuples where the extracted elements are are the ones where the function returns true." }, { "code": null, "e": 3231, "s": 3187, "text": "Here is a syntax:filter(function, iterable)" }, { "code": null, "e": 3439, "s": 3231, "text": "For easier digestion, let’s take an example. Let’s create a function to check if the word is in upper case or not. And then use the filter() to extract all the words from the iterable which are in uppercase." }, { "code": null, "e": 3486, "s": 3439, "text": "Here is official documentation about filter()." }, { "code": null, "e": 3563, "s": 3486, "text": "🚩 Learn how to define a function in a single line using Ternary conditional." }, { "code": null, "e": 3772, "s": 3563, "text": "Lambda functions are used to create anonymous functions i.e. functions without a name. They are useful when we need to create a function to do a single operation and can be written in one line. Its syntax is:" }, { "code": null, "e": 3802, "s": 3772, "text": "lambda parameters: expression" }, { "code": null, "e": 3889, "s": 3802, "text": "🎯 Lambda functions can have any number of parameters but can only have one expression." }, { "code": null, "e": 3916, "s": 3889, "text": "For example, lambda x: x+2" }, { "code": null, "e": 4014, "s": 3916, "text": "That’s it!! Just now I created a function that takes a single input parameter x and adds 2 to it." }, { "code": null, "e": 4215, "s": 4014, "text": "However, as you can see this is an anonymous function, it can not be called at a later stage. Hence, to call it any time in the program, lambda function can be assigned to a function object like this," }, { "code": null, "e": 4236, "s": 4215, "text": "add2 = lambda x: x+2" }, { "code": null, "e": 4352, "s": 4236, "text": "Calling this function is exactly the same as calling a function that was defined with the def keyword. For example," }, { "code": null, "e": 4391, "s": 4352, "text": "add2(10) # It will return 12 as output" }, { "code": null, "e": 4479, "s": 4391, "text": "Lambda function can be a good one-liner in some situations such as List comprehensions." }, { "code": null, "e": 4588, "s": 4479, "text": "As shown in the above picture, newlist is generated with a single line of code by using the lambda function." }, { "code": null, "e": 4600, "s": 4588, "text": "Summing up," }, { "code": null, "e": 4864, "s": 4600, "text": "I found these built-in functions quite handy while using Python for Data Analysis as well as complex automation tasks. Some of them such as zip() , map() are useful in many cases while others such as Lambda function serve as the best one-liner in some situations." }, { "code": null, "e": 4929, "s": 4864, "text": "🚩 5 Most Powerful One-Liners can even further boost your coding." }, { "code": null, "e": 4952, "s": 4929, "text": "towardsdatascience.com" }, { "code": null, "e": 5186, "s": 4952, "text": "Now you can become a Medium member by signing up here to read all the stories published by me and other writers. If you do so, I will get a small portion of your fees. Feel free to join my email list to stay updated about my writing." } ]
Introduction to Survival Analysis: the Kaplan-Meier estimator | by Eryk Lewinson | Towards Data Science
In my previous article, I described the potential use-cases of survival analysis and introduced all the building blocks required to understand the techniques used for analyzing the time-to-event data. I continue the series by explaining perhaps the simplest, yet very insightful approach to survival analysis — the Kaplan-Meier estimator. After a theoretical introduction, I will show you how to carry out the analysis in Python using the popular lifetimes library. The Kaplan-Meier estimator (also known as the product-limit estimator, you will see why later on) is a non-parametric technique of estimating and plotting the survival probability as a function of time. It is often the first step in carrying out the survival analysis, as it is the simplest approach and requires the least assumptions. To carry out the analysis using the Kaplan-Meier approach, we assume the following: The event of interest is unambiguous and happens at a clearly specified time. The survival probability of all observations is the same, it does not matter exactly when they have entered the study. Censored observations have the same survival prospects as observations that continue to be followed. In real-life cases, we never know the true survival function. That is why with the Kaplan-Meier estimator, we approximate the true survival function from the collected data. The estimator is defined as the fraction of observations who survived for a certain amount of time under the same circumstances and is given by the following formula: where: t_i is a time when at least one event happened, d_i is the number of events that happened at time t_i, n_i represents the number of individuals known to have survived up to time t_i (they have not yet had the death event or have been censored). Or to put it differently, the number of observations at risk at time t_i. From the product symbol in the formula, we can see the connection to the other name of the method, the product-limit estimator. The survival probability at time t is equal to the product of the percentage chance of surviving at time t and each prior time. What we most often associate with this approach to survival analysis and what we generally see in practice are the Kaplan-Meier curves — a plot of the Kaplan-Meier estimator over time. We can use those curves as an exploratory tool — to compare the survival function between cohorts, groups that received some kind of treatment or not, behavioral clusters, etc. The survival line is actually a series of decreasing horizontal steps, which approach the shape of the population’s true survival function given a large enough sample size. In practice, the plot is often accompanied by confidence intervals, to show how uncertain we are about the point estimates — wide confidence intervals indicate high uncertainty, probably due to the study containing only a few participants — caused by both observations dying and being censored. For more details on the calculation of the confidence intervals using the Greenwood method, please see [2]. The interpretation of the survival curve is quite simple, the y-axis represents the probability that the subject still has not experienced the event of interest after surviving up to time t, represented on the x-axis. Each drop in the survival function (approximated by the Kaplan-Meier estimator) is caused by the event of interest happening for at least one observation. The actual length of the vertical line represents the fraction of observations at risk that experienced the event at time t. This means that a single observation (not actually the same one, but simply singular) experiencing the event at two different times can result in a drop of difference size — depending on the number of observations at risk. This way, the height of the drop can also inform us about the number of observations at risk (even when unreported and/or there are no confidence intervals). When no observations experienced the event of interest or some observations were censored, there is no drop in the survival curve. We have learned how to use the Kaplan-Meier estimator to approximate the true survival function of a population. And we know we can plot multiple curves to compare their shapes, for example, by the OS the users of our mobile app use. However, we still do not have a tool that will actually allow for comparison. Well, at least a more rigorous one than eyeballing the curves. That is when the log-rank test comes into play. It is a statistical test that compares the survival probabilities between two groups (or more, for that please see the Python implementation). The null hypothesis of the test states that there is no difference between the survival functions of the considered groups. The log-rank test uses the same assumptions as of the Kaplan-Meier estimator. Additionally, there is the proportional hazards assumption — the hazard ratio (please see the previous article for a reminder about the hazard rate) should be constant throughout the study period. In practice, this means that the log-rank test might not be an appropriate test if the survival curves cross. However, this is still a topic of active debate, please see [4] and [5]. For brevity, we do not cover the maths behind the test. If you are interested, please see this article or [3]. In this part, I wanted to mention some of the common mistakes that can occur while working with the Kaplan-Meier estimator. It might be tempting to remove censored data as it can significantly alter the shape of the Kaplan-Meier curve, however, this can lead to severe biases so we should always include it while fitting the model. Pay special attention when interpreting the end of the survival curves, as any big drops close to the end of the study can be explained by only a few observations reaching this point of time (this should also be indicated by wider confidence intervals) By dichotomizing I mean using the median or “optimal” cut-off point to create groups such as “low” and “high” regarding any continuous metric. This approach can create multiple problems: Finding an “optimal“ cut-off point can be very dataset-dependent and impossible to replicate in different studies. Also, by doing multiple comparisons, we risk increasing the chances of false positives (finding a difference in the survival functions, when actually there is none). Dichotomizing decreases the power of the statistical test by forcing all measurements to a binary value, which in turn can lead to the need for a much larger sample size required to detect an effect. It is also worth mentioning that with survival analysis, the required sample size refers to the number of observations with the event of interest. When dichotomizing, we make poor assumptions about the distribution of risk among observations. Let’s assume we use the age of 50 as the split between young and old patients. If we do so, we assume that an 18-year-old is in the same risk group as a 49-year-old, which is not true in most of the cases. The Kaplan-Meier estimator is a univariable method, as it approximates the survival function using at most one variable/predictor. As a result, the results can be easily biased — either exaggerating or missing the signal. That is caused by the so-called omitted-variable bias, which causes the analysis to assume that the potential effects of multiple predictors should be attributed only to the single one, which we take into account. Because of that, multivariable methods such as the Cox regression should be used instead. It is time to implement what we have learned in practice. We start by importing all the required libraries. Then, we load the dataset and do some small wrangling to make it work nicely with the lifelines library. For the analysis, we use the popular Telco Customer Churn dataset (available here or on my GitHub). The dataset contains client information of a telephone/internet provider, including their tenure, what kind of services they use, some demographical data, and ultimately the flag indicating churn. For this analysis, we use the following columns: tenure — the number of months the customer has stayed with the company, churn — information whether the customer churned (binary encoded: 1 if the event happened, 0 otherwise), PaymentMethod— what kind of payment method the customers used. For the most basic scenario, we actually only need the time-to-event and the flag indicating if the event of interest happened. The KaplanMeierFitter works similarly to the classes known from scikit-learn: we first instantiate the object of the class and then use the fit method to fit the model to our data. While plotting, we specify at_risk_counts=True to additionally display information about the number of observations at risk at certain points of time. Normally, we would be interested in the median survival time, that is, the point in time in which on average 50% of the population has already died, or in this case, churned. We can access it using the following line: kmf.median_survival_time_ However, in this case, the command returns inf, as we can see from the survival curve that we actually do not observe that point in our data. We have seen the basic use-case, now let’s complicate the analysis and plot the survival curves for each variant of the payment method. We can do so by running the following code: Running the block of code generates the following plot: We can see that the probability of survival is definitely the lowest for the electronic check, while the curves for automatic bank transfer/credit card are very similar. This is a perfect time to use the log-rank test to see if they are actually different. The following table presents the results. By looking at the p-value of 0.35, we can see that there are no reasons to reject the null hypothesis stating that the survival functions are identical. For this example, we only compared two methods of payment. However, there are definitely more combinations we could test. There is a handy function called pairwise_logrank_test, which makes the comparison very easy. In the table, we see the previous comparison we did, as well as all the other combinations. The bank transfer vs. credit card is the only case in which we should not reject the null hypothesis. Also, we should be cautious about interpreting the results of the log-rank test, as we can see in the plot above that the curves for the bank transfer and credit card payments actually cross, so the assumption of proportional hazards is violated. There are two more things we can easily test using the lifelines library. The first one is the multivariate log-rank test, in which the null hypothesis states that all the groups have the same “death” generating process, so their survival curves are identical. The results of the test indicate that we should reject the null hypothesis, so the survival curves are not identical, which we have already seen in the plot. Lastly, we can test the survival difference at a specific point in time. Coming back to the example, in the plot, we can see that the curves are furthest apart around t = 60. Let’s see if that difference is statistically significant. By looking at the test’s p-value, there is no reason to reject the null hypothesis stating that there is no difference between the survival at that point of time. In this article, I described a very popular tool for conducting survival analysis — the Kaplan-Meier estimator. We also covered the log-rank test for comparing two/multiple survival functions. The described approach is a very popular one, however, not without flaws. Before concluding, let’s take a look at the pros and cons of the Kaplan-Meier estimator/curves. Advantages: Gives the average view of the population, also per groups. Does not require a lot of features — only the information about the time-to-event and if the event actually occurred. Additionally, we can use any categorical features describing groups. Automatically handles class imbalance, as virtually any proportion of death to censored events is acceptable. As it is a non-parametric method, few assumptions are made about the underlying distribution of the data. Disadvantages: We cannot evaluate the magnitude of the predictor’s impact on survival probability. We cannot simultaneously account for multiple factors for observations, for example, the country of origin and the phone’s operating system. The assumption of independence between censoring and survival (at time t, censored observations should have the same prognosis as the ones without censoring) can be inapplicable/unrealistic. When the underlying data distribution is (to some extent) known, the approach is not as accurate as some competing techniques. Summing up, even with a few disadvantages the Kaplan-Meier survival curves are a great place to start off while conducting survival analysis. While doing so, we can get valuable insights about the potential predictors of survival and accelerate our progress with some more advanced techniques (which I will describe in future articles). You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. In case you found this article interesting, you might also like the other ones in the series: towardsdatascience.com towardsdatascience.com towardsdatascience.com [1] Kaplan, E. L., & Meier, P. (1958). Nonparametric estimation from incomplete observations. Journal of the American statistical association, 53(282), 457–481. — available here [2] S. Sawyer (2003). The Greenwood and Exponential Greenwood Confidence Intervals in Survival Analysis — available here [3] Kaplan-Meier Survival Curves and the Log-Rank Test — available here [4] Non-proportional hazards — so what? — available here [5] Bouliotis, G., & Billingham, L. (2011). Crossing survival curves: alternatives to the log-rank test. Trials, 12(S1), A137.
[ { "code": null, "e": 373, "s": 172, "text": "In my previous article, I described the potential use-cases of survival analysis and introduced all the building blocks required to understand the techniques used for analyzing the time-to-event data." }, { "code": null, "e": 638, "s": 373, "text": "I continue the series by explaining perhaps the simplest, yet very insightful approach to survival analysis — the Kaplan-Meier estimator. After a theoretical introduction, I will show you how to carry out the analysis in Python using the popular lifetimes library." }, { "code": null, "e": 1058, "s": 638, "text": "The Kaplan-Meier estimator (also known as the product-limit estimator, you will see why later on) is a non-parametric technique of estimating and plotting the survival probability as a function of time. It is often the first step in carrying out the survival analysis, as it is the simplest approach and requires the least assumptions. To carry out the analysis using the Kaplan-Meier approach, we assume the following:" }, { "code": null, "e": 1136, "s": 1058, "text": "The event of interest is unambiguous and happens at a clearly specified time." }, { "code": null, "e": 1255, "s": 1136, "text": "The survival probability of all observations is the same, it does not matter exactly when they have entered the study." }, { "code": null, "e": 1356, "s": 1255, "text": "Censored observations have the same survival prospects as observations that continue to be followed." }, { "code": null, "e": 1697, "s": 1356, "text": "In real-life cases, we never know the true survival function. That is why with the Kaplan-Meier estimator, we approximate the true survival function from the collected data. The estimator is defined as the fraction of observations who survived for a certain amount of time under the same circumstances and is given by the following formula:" }, { "code": null, "e": 1704, "s": 1697, "text": "where:" }, { "code": null, "e": 1752, "s": 1704, "text": "t_i is a time when at least one event happened," }, { "code": null, "e": 1807, "s": 1752, "text": "d_i is the number of events that happened at time t_i," }, { "code": null, "e": 2023, "s": 1807, "text": "n_i represents the number of individuals known to have survived up to time t_i (they have not yet had the death event or have been censored). Or to put it differently, the number of observations at risk at time t_i." }, { "code": null, "e": 2279, "s": 2023, "text": "From the product symbol in the formula, we can see the connection to the other name of the method, the product-limit estimator. The survival probability at time t is equal to the product of the percentage chance of surviving at time t and each prior time." }, { "code": null, "e": 2641, "s": 2279, "text": "What we most often associate with this approach to survival analysis and what we generally see in practice are the Kaplan-Meier curves — a plot of the Kaplan-Meier estimator over time. We can use those curves as an exploratory tool — to compare the survival function between cohorts, groups that received some kind of treatment or not, behavioral clusters, etc." }, { "code": null, "e": 3217, "s": 2641, "text": "The survival line is actually a series of decreasing horizontal steps, which approach the shape of the population’s true survival function given a large enough sample size. In practice, the plot is often accompanied by confidence intervals, to show how uncertain we are about the point estimates — wide confidence intervals indicate high uncertainty, probably due to the study containing only a few participants — caused by both observations dying and being censored. For more details on the calculation of the confidence intervals using the Greenwood method, please see [2]." }, { "code": null, "e": 3590, "s": 3217, "text": "The interpretation of the survival curve is quite simple, the y-axis represents the probability that the subject still has not experienced the event of interest after surviving up to time t, represented on the x-axis. Each drop in the survival function (approximated by the Kaplan-Meier estimator) is caused by the event of interest happening for at least one observation." }, { "code": null, "e": 4096, "s": 3590, "text": "The actual length of the vertical line represents the fraction of observations at risk that experienced the event at time t. This means that a single observation (not actually the same one, but simply singular) experiencing the event at two different times can result in a drop of difference size — depending on the number of observations at risk. This way, the height of the drop can also inform us about the number of observations at risk (even when unreported and/or there are no confidence intervals)." }, { "code": null, "e": 4227, "s": 4096, "text": "When no observations experienced the event of interest or some observations were censored, there is no drop in the survival curve." }, { "code": null, "e": 4602, "s": 4227, "text": "We have learned how to use the Kaplan-Meier estimator to approximate the true survival function of a population. And we know we can plot multiple curves to compare their shapes, for example, by the OS the users of our mobile app use. However, we still do not have a tool that will actually allow for comparison. Well, at least a more rigorous one than eyeballing the curves." }, { "code": null, "e": 4917, "s": 4602, "text": "That is when the log-rank test comes into play. It is a statistical test that compares the survival probabilities between two groups (or more, for that please see the Python implementation). The null hypothesis of the test states that there is no difference between the survival functions of the considered groups." }, { "code": null, "e": 5375, "s": 4917, "text": "The log-rank test uses the same assumptions as of the Kaplan-Meier estimator. Additionally, there is the proportional hazards assumption — the hazard ratio (please see the previous article for a reminder about the hazard rate) should be constant throughout the study period. In practice, this means that the log-rank test might not be an appropriate test if the survival curves cross. However, this is still a topic of active debate, please see [4] and [5]." }, { "code": null, "e": 5486, "s": 5375, "text": "For brevity, we do not cover the maths behind the test. If you are interested, please see this article or [3]." }, { "code": null, "e": 5610, "s": 5486, "text": "In this part, I wanted to mention some of the common mistakes that can occur while working with the Kaplan-Meier estimator." }, { "code": null, "e": 5818, "s": 5610, "text": "It might be tempting to remove censored data as it can significantly alter the shape of the Kaplan-Meier curve, however, this can lead to severe biases so we should always include it while fitting the model." }, { "code": null, "e": 6071, "s": 5818, "text": "Pay special attention when interpreting the end of the survival curves, as any big drops close to the end of the study can be explained by only a few observations reaching this point of time (this should also be indicated by wider confidence intervals)" }, { "code": null, "e": 6258, "s": 6071, "text": "By dichotomizing I mean using the median or “optimal” cut-off point to create groups such as “low” and “high” regarding any continuous metric. This approach can create multiple problems:" }, { "code": null, "e": 6539, "s": 6258, "text": "Finding an “optimal“ cut-off point can be very dataset-dependent and impossible to replicate in different studies. Also, by doing multiple comparisons, we risk increasing the chances of false positives (finding a difference in the survival functions, when actually there is none)." }, { "code": null, "e": 6886, "s": 6539, "text": "Dichotomizing decreases the power of the statistical test by forcing all measurements to a binary value, which in turn can lead to the need for a much larger sample size required to detect an effect. It is also worth mentioning that with survival analysis, the required sample size refers to the number of observations with the event of interest." }, { "code": null, "e": 7188, "s": 6886, "text": "When dichotomizing, we make poor assumptions about the distribution of risk among observations. Let’s assume we use the age of 50 as the split between young and old patients. If we do so, we assume that an 18-year-old is in the same risk group as a 49-year-old, which is not true in most of the cases." }, { "code": null, "e": 7714, "s": 7188, "text": "The Kaplan-Meier estimator is a univariable method, as it approximates the survival function using at most one variable/predictor. As a result, the results can be easily biased — either exaggerating or missing the signal. That is caused by the so-called omitted-variable bias, which causes the analysis to assume that the potential effects of multiple predictors should be attributed only to the single one, which we take into account. Because of that, multivariable methods such as the Cox regression should be used instead." }, { "code": null, "e": 7822, "s": 7714, "text": "It is time to implement what we have learned in practice. We start by importing all the required libraries." }, { "code": null, "e": 8224, "s": 7822, "text": "Then, we load the dataset and do some small wrangling to make it work nicely with the lifelines library. For the analysis, we use the popular Telco Customer Churn dataset (available here or on my GitHub). The dataset contains client information of a telephone/internet provider, including their tenure, what kind of services they use, some demographical data, and ultimately the flag indicating churn." }, { "code": null, "e": 8273, "s": 8224, "text": "For this analysis, we use the following columns:" }, { "code": null, "e": 8345, "s": 8273, "text": "tenure — the number of months the customer has stayed with the company," }, { "code": null, "e": 8450, "s": 8345, "text": "churn — information whether the customer churned (binary encoded: 1 if the event happened, 0 otherwise)," }, { "code": null, "e": 8513, "s": 8450, "text": "PaymentMethod— what kind of payment method the customers used." }, { "code": null, "e": 8641, "s": 8513, "text": "For the most basic scenario, we actually only need the time-to-event and the flag indicating if the event of interest happened." }, { "code": null, "e": 8973, "s": 8641, "text": "The KaplanMeierFitter works similarly to the classes known from scikit-learn: we first instantiate the object of the class and then use the fit method to fit the model to our data. While plotting, we specify at_risk_counts=True to additionally display information about the number of observations at risk at certain points of time." }, { "code": null, "e": 9191, "s": 8973, "text": "Normally, we would be interested in the median survival time, that is, the point in time in which on average 50% of the population has already died, or in this case, churned. We can access it using the following line:" }, { "code": null, "e": 9217, "s": 9191, "text": "kmf.median_survival_time_" }, { "code": null, "e": 9359, "s": 9217, "text": "However, in this case, the command returns inf, as we can see from the survival curve that we actually do not observe that point in our data." }, { "code": null, "e": 9539, "s": 9359, "text": "We have seen the basic use-case, now let’s complicate the analysis and plot the survival curves for each variant of the payment method. We can do so by running the following code:" }, { "code": null, "e": 9595, "s": 9539, "text": "Running the block of code generates the following plot:" }, { "code": null, "e": 9852, "s": 9595, "text": "We can see that the probability of survival is definitely the lowest for the electronic check, while the curves for automatic bank transfer/credit card are very similar. This is a perfect time to use the log-rank test to see if they are actually different." }, { "code": null, "e": 9894, "s": 9852, "text": "The following table presents the results." }, { "code": null, "e": 10263, "s": 9894, "text": "By looking at the p-value of 0.35, we can see that there are no reasons to reject the null hypothesis stating that the survival functions are identical. For this example, we only compared two methods of payment. However, there are definitely more combinations we could test. There is a handy function called pairwise_logrank_test, which makes the comparison very easy." }, { "code": null, "e": 10704, "s": 10263, "text": "In the table, we see the previous comparison we did, as well as all the other combinations. The bank transfer vs. credit card is the only case in which we should not reject the null hypothesis. Also, we should be cautious about interpreting the results of the log-rank test, as we can see in the plot above that the curves for the bank transfer and credit card payments actually cross, so the assumption of proportional hazards is violated." }, { "code": null, "e": 10965, "s": 10704, "text": "There are two more things we can easily test using the lifelines library. The first one is the multivariate log-rank test, in which the null hypothesis states that all the groups have the same “death” generating process, so their survival curves are identical." }, { "code": null, "e": 11123, "s": 10965, "text": "The results of the test indicate that we should reject the null hypothesis, so the survival curves are not identical, which we have already seen in the plot." }, { "code": null, "e": 11357, "s": 11123, "text": "Lastly, we can test the survival difference at a specific point in time. Coming back to the example, in the plot, we can see that the curves are furthest apart around t = 60. Let’s see if that difference is statistically significant." }, { "code": null, "e": 11520, "s": 11357, "text": "By looking at the test’s p-value, there is no reason to reject the null hypothesis stating that there is no difference between the survival at that point of time." }, { "code": null, "e": 11883, "s": 11520, "text": "In this article, I described a very popular tool for conducting survival analysis — the Kaplan-Meier estimator. We also covered the log-rank test for comparing two/multiple survival functions. The described approach is a very popular one, however, not without flaws. Before concluding, let’s take a look at the pros and cons of the Kaplan-Meier estimator/curves." }, { "code": null, "e": 11895, "s": 11883, "text": "Advantages:" }, { "code": null, "e": 11954, "s": 11895, "text": "Gives the average view of the population, also per groups." }, { "code": null, "e": 12141, "s": 11954, "text": "Does not require a lot of features — only the information about the time-to-event and if the event actually occurred. Additionally, we can use any categorical features describing groups." }, { "code": null, "e": 12251, "s": 12141, "text": "Automatically handles class imbalance, as virtually any proportion of death to censored events is acceptable." }, { "code": null, "e": 12357, "s": 12251, "text": "As it is a non-parametric method, few assumptions are made about the underlying distribution of the data." }, { "code": null, "e": 12372, "s": 12357, "text": "Disadvantages:" }, { "code": null, "e": 12456, "s": 12372, "text": "We cannot evaluate the magnitude of the predictor’s impact on survival probability." }, { "code": null, "e": 12597, "s": 12456, "text": "We cannot simultaneously account for multiple factors for observations, for example, the country of origin and the phone’s operating system." }, { "code": null, "e": 12788, "s": 12597, "text": "The assumption of independence between censoring and survival (at time t, censored observations should have the same prognosis as the ones without censoring) can be inapplicable/unrealistic." }, { "code": null, "e": 12915, "s": 12788, "text": "When the underlying data distribution is (to some extent) known, the approach is not as accurate as some competing techniques." }, { "code": null, "e": 13252, "s": 12915, "text": "Summing up, even with a few disadvantages the Kaplan-Meier survival curves are a great place to start off while conducting survival analysis. While doing so, we can get valuable insights about the potential predictors of survival and accelerate our progress with some more advanced techniques (which I will describe in future articles)." }, { "code": null, "e": 13414, "s": 13252, "text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments." }, { "code": null, "e": 13508, "s": 13414, "text": "In case you found this article interesting, you might also like the other ones in the series:" }, { "code": null, "e": 13531, "s": 13508, "text": "towardsdatascience.com" }, { "code": null, "e": 13554, "s": 13531, "text": "towardsdatascience.com" }, { "code": null, "e": 13577, "s": 13554, "text": "towardsdatascience.com" }, { "code": null, "e": 13755, "s": 13577, "text": "[1] Kaplan, E. L., & Meier, P. (1958). Nonparametric estimation from incomplete observations. Journal of the American statistical association, 53(282), 457–481. — available here" }, { "code": null, "e": 13876, "s": 13755, "text": "[2] S. Sawyer (2003). The Greenwood and Exponential Greenwood Confidence Intervals in Survival Analysis — available here" }, { "code": null, "e": 13948, "s": 13876, "text": "[3] Kaplan-Meier Survival Curves and the Log-Rank Test — available here" }, { "code": null, "e": 14005, "s": 13948, "text": "[4] Non-proportional hazards — so what? — available here" } ]
Why is the size of an empty class not zero in C++?
Suppose we have one empty class in C++. Now let us check whether its size is 0 or not. Actually, the standard does not permit objects (or classes) of size 0, this is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class must have a size at least 1. It is known that size of an empty class is not zero. Generally, it is 1 byte. See the below example. Let us see the following implementation to get better understanding − Live Demo #include<iostream> using namespace std; class MyClass { }; int main() { cout << sizeof(MyClass); } 1 It clearly shows that an object of one empty class will take at least one byte to ensure that the two different objects will have different addresses. See the below example. Live Demo #include<iostream> using namespace std; class MyClass { }; int main() { MyClass a, b; if (&a == &b) cout <<"Same "<< endl; else cout <<"Not same "<< endl; } Not same For dynamic allocation also, the new keyword returns different address for the same reason. Live Demo #include<iostream> using namespace std; class MyClass { }; int main() { MyClass *a = new MyClass(); MyClass *b = new MyClass(); if (a == b) cout <<"Same "<< endl; else cout <<"Not same "<< endl; } Not same
[ { "code": null, "e": 1516, "s": 1062, "text": "Suppose we have one empty class in C++. Now let us check whether its size is 0 or not. Actually, the standard does not permit objects (or classes) of size 0, this is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class must have a size at least 1. It is known that size of an empty class is not zero. Generally, it is 1 byte. See the below example." }, { "code": null, "e": 1586, "s": 1516, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1597, "s": 1586, "text": " Live Demo" }, { "code": null, "e": 1699, "s": 1597, "text": "#include<iostream>\nusing namespace std;\nclass MyClass {\n};\nint main() {\n cout << sizeof(MyClass);\n}" }, { "code": null, "e": 1701, "s": 1699, "text": "1" }, { "code": null, "e": 1875, "s": 1701, "text": "It clearly shows that an object of one empty class will take at least one byte to ensure that the two different objects will have different addresses. See the below example." }, { "code": null, "e": 1886, "s": 1875, "text": " Live Demo" }, { "code": null, "e": 2064, "s": 1886, "text": "#include<iostream>\nusing namespace std;\nclass MyClass {\n};\nint main() {\n MyClass a, b;\n if (&a == &b)\n cout <<\"Same \"<< endl;\n else\n cout <<\"Not same \"<< endl;\n}" }, { "code": null, "e": 2073, "s": 2064, "text": "Not same" }, { "code": null, "e": 2165, "s": 2073, "text": "For dynamic allocation also, the new keyword returns different address for the same reason." }, { "code": null, "e": 2176, "s": 2165, "text": " Live Demo" }, { "code": null, "e": 2397, "s": 2176, "text": "#include<iostream>\nusing namespace std;\nclass MyClass {\n};\nint main() {\n MyClass *a = new MyClass();\n MyClass *b = new MyClass();\n if (a == b)\n cout <<\"Same \"<< endl;\n else\n cout <<\"Not same \"<< endl;\n}" }, { "code": null, "e": 2406, "s": 2397, "text": "Not same" } ]
2D Shapes(Objects) Intersection Operation
This operation takes two or more shapes as inputs and returns the intersection area between them as shown below. You can perform an intersection operation on the shapes using the method named intersect(). Since this is a static method, you should call it using the class name (Shape or its subclasses) as shown below. Shape shape = Shape.intersect(circle1, circle2); Following is an example of the intersection operation. In here, we are drawing two circles and performing a intersection operation on them. Save this code in a file with the name IntersectionExample.java import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; public class IntersectionExample extends Application { @Override public void start(Stage stage) { //Drawing Circle1 Circle circle1 = new Circle(); //Setting the position of the circle circle1.setCenterX(250.0f); circle1.setCenterY(135.0f); //Setting the radius of the circle circle1.setRadius(100.0f); //Setting the color of the circle circle1.setFill(Color.DARKSLATEBLUE); //Drawing Circle2 Circle circle2 = new Circle(); //Setting the position of the circle circle2.setCenterX(350.0f); circle2.setCenterY(135.0f); //Setting the radius of the circle circle2.setRadius(100.0f); //Setting the color of the circle circle2.setFill(Color.BLUE); //Performing intersection operation on the circle Shape shape = Shape.intersect(circle1, circle2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Intersection Example"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac IntersectionExample.java java IntersectionExample On executing, the above program generates a JavaFX window displaying the following output − 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2013, "s": 1900, "text": "This operation takes two or more shapes as inputs and returns the intersection area between them as shown below." }, { "code": null, "e": 2218, "s": 2013, "text": "You can perform an intersection operation on the shapes using the method named intersect(). Since this is a static method, you should call it using the class name (Shape or its subclasses) as shown below." }, { "code": null, "e": 2269, "s": 2218, "text": "Shape shape = Shape.intersect(circle1, circle2); \n" }, { "code": null, "e": 2409, "s": 2269, "text": "Following is an example of the intersection operation. In here, we are drawing two circles and performing a intersection operation on them." }, { "code": null, "e": 2473, "s": 2409, "text": "Save this code in a file with the name IntersectionExample.java" }, { "code": null, "e": 4267, "s": 2473, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.paint.Color; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.Circle; \nimport javafx.scene.shape.Shape; \n \npublic class IntersectionExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing Circle1 \n Circle circle1 = new Circle();\n \n //Setting the position of the circle \n circle1.setCenterX(250.0f); \n circle1.setCenterY(135.0f); \n \n //Setting the radius of the circle \n circle1.setRadius(100.0f); \n \n //Setting the color of the circle \n circle1.setFill(Color.DARKSLATEBLUE); \n \n //Drawing Circle2 \n Circle circle2 = new Circle(); \n \n //Setting the position of the circle \n circle2.setCenterX(350.0f); \n circle2.setCenterY(135.0f); \n \n //Setting the radius of the circle \n circle2.setRadius(100.0f); \n \n //Setting the color of the circle \n circle2.setFill(Color.BLUE); \n \n //Performing intersection operation on the circle \n Shape shape = Shape.intersect(circle1, circle2); \n \n //Setting the fill color to the result \n shape.setFill(Color.DARKSLATEBLUE); \n \n //Creating a Group object \n Group root = new Group(shape); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Intersection Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene);\n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 4361, "s": 4267, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 4419, "s": 4361, "text": "javac IntersectionExample.java \njava IntersectionExample\n" }, { "code": null, "e": 4511, "s": 4419, "text": "On executing, the above program generates a JavaFX window displaying the following output −" }, { "code": null, "e": 4546, "s": 4511, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4557, "s": 4546, "text": " Syed Raza" }, { "code": null, "e": 4593, "s": 4557, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4629, "s": 4593, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 4662, "s": 4629, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 4698, "s": 4662, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 4705, "s": 4698, "text": " Print" }, { "code": null, "e": 4716, "s": 4705, "text": " Add Notes" } ]
Find N distinct numbers whose bitwise Or is equal to K - GeeksforGeeks
24 Mar, 2022 Given two integers N and K, the task is to find N distinct integers whose bit-wise OR is equal to K. If there does not exist any possible answer then print -1.Examples: Input: N = 3, K = 5 Output: 5 0 1 5 OR 0 OR 1 = 5Input: N = 10, K = 5 Output: -1 It is not possible to find any solution. Approach: We know that if bit-wise OR of a sequence of numbers is K then all the bit positions which are 0 in K must also be zero in all the numbers.So, we only have those positions to change where bit is 1 in K. Say that count is Bit_K.Now, we can form pow(2, Bit_K) distinct numbers with Bit_K bits. So if, we set one number to be K itself, then rest N – 1 numbers can be built by setting 0 all the bits in every number which are 0 in K and for other bit positions any permutation of Bit_K bits other than number K.If pow(2, Bit_K) < N then we cannot find any possible answer. We know that if bit-wise OR of a sequence of numbers is K then all the bit positions which are 0 in K must also be zero in all the numbers. So, we only have those positions to change where bit is 1 in K. Say that count is Bit_K. Now, we can form pow(2, Bit_K) distinct numbers with Bit_K bits. So if, we set one number to be K itself, then rest N – 1 numbers can be built by setting 0 all the bits in every number which are 0 in K and for other bit positions any permutation of Bit_K bits other than number K. If pow(2, Bit_K) < N then we cannot find any possible answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define MAX 32 ll pow2[MAX];bool visited[MAX];vector<int> ans; // Function to pre-calculate// all the powers of 2 upto MAXvoid power_2(){ ll ans = 1; for (int i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; }} // Function to return the// count of set bits in xint countSetBits(ll x){ // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Function to add num to the answer// by setting all bit positions as 0// which are also 0 in Kvoid add(ll num){ int point = 0; ll value = 0; for (ll i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num & 1) { value += (1 << i); } num /= 2; } } ans.push_back(value);} // Function to find and print N distinct// numbers whose bitwise OR is Kvoid solve(ll n, ll k){ // Choosing K itself as one number ans.push_back(k); // Find the count of set bits in K int countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { cout << -1; return; } int count = 0; for (ll i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (int i = 0; i < n; i++) { cout << ans[i] << " "; }} // Driver codeint main(){ ll n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static final int MAX = 32; static long []pow2 = new long[MAX];static boolean []visited = new boolean[MAX];static Vector<Long> ans = new Vector<>(); // Function to pre-calculate// all the powers of 2 upto MAXstatic void power_2(){ long ans = 1; for (int i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; }} // Function to return the// count of set bits in xstatic int countSetBits(long x){ // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Function to add num to the answer// by setting all bit positions as 0// which are also 0 in Kstatic void add(long num){ int point = 0; long value = 0; for (int i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num %2== 1) { value += (1 << i); } num /= 2; } } ans.add(value);} // Function to find and print N distinct// numbers whose bitwise OR is Kstatic void solve(long n, long k){ // Choosing K itself as one number ans.add(k); // Find the count of set bits in K int countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { System.out.print(-1); return; } int count = 0; for (long i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (int i = 0; i < n; i++) { System.out.print(ans.get(i)+" "); }} // Driver codepublic static void main(String[] args){ long n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k);}} // This code has been contributed by 29AjayKumar # Python 3 implementation of the approachMAX = 32 pow2 = [0 for i in range(MAX)]visited = [False for i in range(MAX)]ans = [] # Function to pre-calculate# all the powers of 2 upto MAXdef power_2(): an = 1 for i in range(MAX): pow2[i] = an an *= 2 # Function to return the# count of set bits in xdef countSetBits(x): # To store the count # of set bits setBits = 0 while (x != 0): x = x & (x - 1) setBits += 1 return setBits # Function to add num to the answer# by setting all bit positions as 0# which are also 0 in Kdef add(num): point = 0 value = 0 for i in range(MAX): # Bit i is 0 in K if (visited[i]): continue else: if (num & 1): value += (1 << i) num = num//2 ans.append(value) # Function to find and print N distinct# numbers whose bitwise OR is Kdef solve(n, k): # Choosing K itself as one number ans.append(k) # Find the count of set bits in K countk = countSetBits(k) # Impossible to get N # distinct integers if (pow2[countk] < n): print(-1) return count = 0 for i in range(pow2[countk] - 1): # Add i to the answer after # setting all the bits as 0 # which are 0 in K add(i) count += 1 # If N distinct numbers are generated if (count == n): break # Print the generated numbers for i in range(n): print(ans[i],end = " ") # Driver codeif __name__ == '__main__': n = 3 k = 5 # Pre-calculate all # the powers of 2 power_2() solve(n, k) # This code is contributed by# Surendra_Gangwar // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int MAX = 32; static long [] pow2 = new long[MAX]; static bool [] visited = new bool[MAX]; static List<long> ans = new List<long>(); // Function to pre-calculate // all the powers of 2 upto MAX static void power_2() { long ans = 1; for (int i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; } } // Function to return the // count of set bits in x static int countSetBits(long x) { // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits; } // Function to add num to the answer // by setting all bit positions as 0 // which are also 0 in K static void add(long num) { long value = 0; for (int i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num %2== 1) { value += (1 << i); } num /= 2; } } ans.Add(value); } // Function to find and print N distinct // numbers whose bitwise OR is K static void solve(long n, long k) { // Choosing K itself as one number ans.Add(k); // Find the count of set bits in K int countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { Console.WriteLine(-1); return; } int count = 0; for (long i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (int i = 0; i < n; i++) { Console.Write(ans[i]+ " "); } } // Driver code public static void Main() { long n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k); }} // This code is contributed by ihritik <script>// Javascript implementation of the approach const MAX = 32; let pow2 = new Array(MAX);let visited = new Array(MAX);let ans = []; // Function to pre-calculate// all the powers of 2 upto MAXfunction power_2(){ let ans = 1; for (let i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; }} // Function to return the// count of set bits in xfunction countSetBits(x){ // To store the count // of set bits let setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Function to add num to the answer// by setting all bit positions as 0// which are also 0 in Kfunction add(num){ let point = 0; let value = 0; for (let i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num & 1) { value += (1 << i); } num = parseInt(num / 2); } } ans.push(value);} // Function to find and print N distinct// numbers whose bitwise OR is Kfunction solve(n, k){ // Choosing K itself as one number ans.push(k); // Find the count of set bits in K let countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { document.write(-1); return; } let count = 0; for (let i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (let i = 0; i < n; i++) { document.write(ans[i] + " "); }} // Driver code let n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k); </script> 5 0 1 29AjayKumar ihritik SURENDRA_GANGWAR subham348 simmytarika5 Bitwise-OR Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Program to find parity Write an Efficient Method to Check if a Number is Multiple of 3 Hamming code Implementation in C/C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25013, "s": 24985, "text": "\n24 Mar, 2022" }, { "code": null, "e": 25184, "s": 25013, "text": "Given two integers N and K, the task is to find N distinct integers whose bit-wise OR is equal to K. If there does not exist any possible answer then print -1.Examples: " }, { "code": null, "e": 25308, "s": 25184, "text": "Input: N = 3, K = 5 Output: 5 0 1 5 OR 0 OR 1 = 5Input: N = 10, K = 5 Output: -1 It is not possible to find any solution. " }, { "code": null, "e": 25322, "s": 25310, "text": "Approach: " }, { "code": null, "e": 25891, "s": 25322, "text": "We know that if bit-wise OR of a sequence of numbers is K then all the bit positions which are 0 in K must also be zero in all the numbers.So, we only have those positions to change where bit is 1 in K. Say that count is Bit_K.Now, we can form pow(2, Bit_K) distinct numbers with Bit_K bits. So if, we set one number to be K itself, then rest N – 1 numbers can be built by setting 0 all the bits in every number which are 0 in K and for other bit positions any permutation of Bit_K bits other than number K.If pow(2, Bit_K) < N then we cannot find any possible answer." }, { "code": null, "e": 26031, "s": 25891, "text": "We know that if bit-wise OR of a sequence of numbers is K then all the bit positions which are 0 in K must also be zero in all the numbers." }, { "code": null, "e": 26120, "s": 26031, "text": "So, we only have those positions to change where bit is 1 in K. Say that count is Bit_K." }, { "code": null, "e": 26401, "s": 26120, "text": "Now, we can form pow(2, Bit_K) distinct numbers with Bit_K bits. So if, we set one number to be K itself, then rest N – 1 numbers can be built by setting 0 all the bits in every number which are 0 in K and for other bit positions any permutation of Bit_K bits other than number K." }, { "code": null, "e": 26463, "s": 26401, "text": "If pow(2, Bit_K) < N then we cannot find any possible answer." }, { "code": null, "e": 26516, "s": 26463, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26520, "s": 26516, "text": "C++" }, { "code": null, "e": 26525, "s": 26520, "text": "Java" }, { "code": null, "e": 26533, "s": 26525, "text": "Python3" }, { "code": null, "e": 26536, "s": 26533, "text": "C#" }, { "code": null, "e": 26547, "s": 26536, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define MAX 32 ll pow2[MAX];bool visited[MAX];vector<int> ans; // Function to pre-calculate// all the powers of 2 upto MAXvoid power_2(){ ll ans = 1; for (int i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; }} // Function to return the// count of set bits in xint countSetBits(ll x){ // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Function to add num to the answer// by setting all bit positions as 0// which are also 0 in Kvoid add(ll num){ int point = 0; ll value = 0; for (ll i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num & 1) { value += (1 << i); } num /= 2; } } ans.push_back(value);} // Function to find and print N distinct// numbers whose bitwise OR is Kvoid solve(ll n, ll k){ // Choosing K itself as one number ans.push_back(k); // Find the count of set bits in K int countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { cout << -1; return; } int count = 0; for (ll i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (int i = 0; i < n; i++) { cout << ans[i] << \" \"; }} // Driver codeint main(){ ll n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k); return 0;}", "e": 28393, "s": 26547, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static final int MAX = 32; static long []pow2 = new long[MAX];static boolean []visited = new boolean[MAX];static Vector<Long> ans = new Vector<>(); // Function to pre-calculate// all the powers of 2 upto MAXstatic void power_2(){ long ans = 1; for (int i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; }} // Function to return the// count of set bits in xstatic int countSetBits(long x){ // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Function to add num to the answer// by setting all bit positions as 0// which are also 0 in Kstatic void add(long num){ int point = 0; long value = 0; for (int i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num %2== 1) { value += (1 << i); } num /= 2; } } ans.add(value);} // Function to find and print N distinct// numbers whose bitwise OR is Kstatic void solve(long n, long k){ // Choosing K itself as one number ans.add(k); // Find the count of set bits in K int countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { System.out.print(-1); return; } int count = 0; for (long i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (int i = 0; i < n; i++) { System.out.print(ans.get(i)+\" \"); }} // Driver codepublic static void main(String[] args){ long n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k);}} // This code has been contributed by 29AjayKumar", "e": 30449, "s": 28393, "text": null }, { "code": "# Python 3 implementation of the approachMAX = 32 pow2 = [0 for i in range(MAX)]visited = [False for i in range(MAX)]ans = [] # Function to pre-calculate# all the powers of 2 upto MAXdef power_2(): an = 1 for i in range(MAX): pow2[i] = an an *= 2 # Function to return the# count of set bits in xdef countSetBits(x): # To store the count # of set bits setBits = 0 while (x != 0): x = x & (x - 1) setBits += 1 return setBits # Function to add num to the answer# by setting all bit positions as 0# which are also 0 in Kdef add(num): point = 0 value = 0 for i in range(MAX): # Bit i is 0 in K if (visited[i]): continue else: if (num & 1): value += (1 << i) num = num//2 ans.append(value) # Function to find and print N distinct# numbers whose bitwise OR is Kdef solve(n, k): # Choosing K itself as one number ans.append(k) # Find the count of set bits in K countk = countSetBits(k) # Impossible to get N # distinct integers if (pow2[countk] < n): print(-1) return count = 0 for i in range(pow2[countk] - 1): # Add i to the answer after # setting all the bits as 0 # which are 0 in K add(i) count += 1 # If N distinct numbers are generated if (count == n): break # Print the generated numbers for i in range(n): print(ans[i],end = \" \") # Driver codeif __name__ == '__main__': n = 3 k = 5 # Pre-calculate all # the powers of 2 power_2() solve(n, k) # This code is contributed by# Surendra_Gangwar", "e": 32120, "s": 30449, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int MAX = 32; static long [] pow2 = new long[MAX]; static bool [] visited = new bool[MAX]; static List<long> ans = new List<long>(); // Function to pre-calculate // all the powers of 2 upto MAX static void power_2() { long ans = 1; for (int i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; } } // Function to return the // count of set bits in x static int countSetBits(long x) { // To store the count // of set bits int setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits; } // Function to add num to the answer // by setting all bit positions as 0 // which are also 0 in K static void add(long num) { long value = 0; for (int i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num %2== 1) { value += (1 << i); } num /= 2; } } ans.Add(value); } // Function to find and print N distinct // numbers whose bitwise OR is K static void solve(long n, long k) { // Choosing K itself as one number ans.Add(k); // Find the count of set bits in K int countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { Console.WriteLine(-1); return; } int count = 0; for (long i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (int i = 0; i < n; i++) { Console.Write(ans[i]+ \" \"); } } // Driver code public static void Main() { long n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k); }} // This code is contributed by ihritik", "e": 34610, "s": 32120, "text": null }, { "code": "<script>// Javascript implementation of the approach const MAX = 32; let pow2 = new Array(MAX);let visited = new Array(MAX);let ans = []; // Function to pre-calculate// all the powers of 2 upto MAXfunction power_2(){ let ans = 1; for (let i = 0; i < MAX; i++) { pow2[i] = ans; ans *= 2; }} // Function to return the// count of set bits in xfunction countSetBits(x){ // To store the count // of set bits let setBits = 0; while (x != 0) { x = x & (x - 1); setBits++; } return setBits;} // Function to add num to the answer// by setting all bit positions as 0// which are also 0 in Kfunction add(num){ let point = 0; let value = 0; for (let i = 0; i < MAX; i++) { // Bit i is 0 in K if (visited[i]) continue; else { if (num & 1) { value += (1 << i); } num = parseInt(num / 2); } } ans.push(value);} // Function to find and print N distinct// numbers whose bitwise OR is Kfunction solve(n, k){ // Choosing K itself as one number ans.push(k); // Find the count of set bits in K let countk = countSetBits(k); // Impossible to get N // distinct integers if (pow2[countk] < n) { document.write(-1); return; } let count = 0; for (let i = 0; i < pow2[countk] - 1; i++) { // Add i to the answer after // setting all the bits as 0 // which are 0 in K add(i); count++; // If N distinct numbers are generated if (count == n) break; } // Print the generated numbers for (let i = 0; i < n; i++) { document.write(ans[i] + \" \"); }} // Driver code let n = 3, k = 5; // Pre-calculate all // the powers of 2 power_2(); solve(n, k); </script>", "e": 36440, "s": 34610, "text": null }, { "code": null, "e": 36446, "s": 36440, "text": "5 0 1" }, { "code": null, "e": 36460, "s": 36448, "text": "29AjayKumar" }, { "code": null, "e": 36468, "s": 36460, "text": "ihritik" }, { "code": null, "e": 36485, "s": 36468, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 36495, "s": 36485, "text": "subham348" }, { "code": null, "e": 36508, "s": 36495, "text": "simmytarika5" }, { "code": null, "e": 36519, "s": 36508, "text": "Bitwise-OR" }, { "code": null, "e": 36529, "s": 36519, "text": "Bit Magic" }, { "code": null, "e": 36542, "s": 36529, "text": "Mathematical" }, { "code": null, "e": 36555, "s": 36542, "text": "Mathematical" }, { "code": null, "e": 36565, "s": 36555, "text": "Bit Magic" }, { "code": null, "e": 36663, "s": 36565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36714, "s": 36663, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 36751, "s": 36714, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 36774, "s": 36751, "text": "Program to find parity" }, { "code": null, "e": 36838, "s": 36774, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 36875, "s": 36838, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 36905, "s": 36875, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36965, "s": 36905, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36980, "s": 36965, "text": "C++ Data Types" }, { "code": null, "e": 37023, "s": 36980, "text": "Set in C++ Standard Template Library (STL)" } ]
How to filter R DataFrame by values in a column? - GeeksforGeeks
30 May, 2021 In R Programming Language, dataframe columns can be subjected to constraints, and produce smaller subsets. However, while the conditions are applied, the following properties are maintained : Rows are considered to be a subset of the input. Rows in the subset appear in the same order as the original dataframe. Columns remain unmodified. The number of groups may be reduced, based on conditions. dataframe attributes are preserved during data filter. Any dataframe column in the R programming language can be referenced either through its name df$col-name or using its index position in the dataframe df[col-index]. The cell values of this column can then be subjected to constraints, logical or comparative conditions, and then a dataframe subset can be obtained. These conditions are applied to the row index of the dataframe so that the satisfied rows are returned. Selection based on a check of missing values or NA Cells in dataframe can contain missing values or NA as its elements, and they can be verified using is.na() method in R language. Example: R # declaring a dataframedata_frame = data.frame(col1 = c(NA,"b",NA,"e","e") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values are not NAdata_frame_mod <- data_frame[!is.na(data_frame$col1),] print ("Modified dataframe")print (data_frame_mod) Output [1] “Original dataframe” col1 col2 col3 1 <NA> 0 TRUE 2 b 2 FALSE 3 <NA> 1 FALSE 4 e 4 TRUE 5 e 5 TRUE [1] “Modified dataframe” col1 col2 col3 2 b 2 FALSE 4 e 4 TRUE 5 e 5 TRUE Selection based on a single comparative condition on a column Column values can be subjected to constraints to filter and subset the data. The values can be mapped to specific occurrences or within a range. Example: R # declaring a dataframedata_frame = data.frame(col1 = c("b","b","e","e","e") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which columns have col3# value equivalent to truedata_frame_mod <- data_frame[data_frame$col3==TRUE,] print ("Modified dataframe")print (data_frame_mod) Output [1] “Original dataframe” col1 col2 col3 1 b 0 TRUE 2 b 2 FALSE 3 e 1 FALSE 4 e 4 TRUE 5 e 5 TRUE [1] “Modified dataframe” col1 col2 col3 1 b 0 TRUE 4 e 4 TRUE 5 e 5 TRUE Selection based on multiple comparative conditions on a column Column values can be subjected to constraints to filter and subset the data. The conditions can be combined by logical & or | operators. The %in% operator is used here, in order to check values that match to any of the values within a specified vector. Example: R # declaring a dataframedata_frame = data.frame(col1 = c("b","b","d","e","e") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- data_frame[data_frame$col1 %in% c("b","e"),]print ("Modified dataframe")print (data_frame_mod) Output [1] “Original dataframe” col1 col2 col3 1 b 0 TRUE 2 b 2 FALSE 3 d 1 FALSE 4 e 4 TRUE 5 e 5 TRUE [1] “Modified dataframe” col1 col2 col3 1 b 0 TRUE 2 b 2 FALSE 4 e 4 TRUE 5 e 5 TRUE The dplyr library can be installed and loaded into the working space which is used to perform data manipulation. The filter() function is used to produce a subset of the dataframe, retaining all rows that satisfy the specified conditions. The filter() method in R can be applied to both grouped and ungrouped data. The expressions include comparison operators (==, >, >= ) , logical operators (&, |, !, xor()) , range operators (between(), near()) as well as NA value check against the column values. The subset dataframe has to be retained in a separate variable. Syntax: filter(df , cond) Parameter : df – The dataframe object cond – The condition to filter the data upon Example: R library ("dplyr") # declaring a dataframedata_frame = data.frame(col1 = c("b","b","d","e","e") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- filter(data_frame,col2>1) print ("Modified dataframe")print (data_frame_mod) Output [1] “Original dataframe” col1 col2 col3 1 b 0 TRUE 2 b 2 FALSE 3 d 1 FALSE 4 e 4 TRUE 5 e 5 TRUE [1] “Modified dataframe” col1 col2 col3 1 b 2 FALSE 2 e 4 TRUE 3 e 5 TRUE Also, the values can be checked using the %in% operator to match the column cell values with the elements contained in the input specified vector. Example: R library ("dplyr") # declaring a dataframedata_frame = data.frame(col1 = c("b","b","d","e","e") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print ("Original dataframe")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- filter(data_frame,col1 %in% c("b","e"))print ("Modified dataframe")print (data_frame_mod) Output [1] “Original dataframe” col1 col2 col3 1 b 0 TRUE 2 b 2 FALSE 3 d 1 FALSE 4 e 4 TRUE 5 e 5 TRUE [1] “Modified dataframe” col1 col2 col3 1 b 0 TRUE 2 b 2 FALSE 4 e 4 TRUE 5 e 5 TRUE Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R
[ { "code": null, "e": 25256, "s": 25228, "text": "\n30 May, 2021" }, { "code": null, "e": 25448, "s": 25256, "text": "In R Programming Language, dataframe columns can be subjected to constraints, and produce smaller subsets. However, while the conditions are applied, the following properties are maintained :" }, { "code": null, "e": 25497, "s": 25448, "text": "Rows are considered to be a subset of the input." }, { "code": null, "e": 25568, "s": 25497, "text": "Rows in the subset appear in the same order as the original dataframe." }, { "code": null, "e": 25595, "s": 25568, "text": "Columns remain unmodified." }, { "code": null, "e": 25653, "s": 25595, "text": "The number of groups may be reduced, based on conditions." }, { "code": null, "e": 25708, "s": 25653, "text": "dataframe attributes are preserved during data filter." }, { "code": null, "e": 26127, "s": 25708, "text": "Any dataframe column in the R programming language can be referenced either through its name df$col-name or using its index position in the dataframe df[col-index]. The cell values of this column can then be subjected to constraints, logical or comparative conditions, and then a dataframe subset can be obtained. These conditions are applied to the row index of the dataframe so that the satisfied rows are returned. " }, { "code": null, "e": 26178, "s": 26127, "text": "Selection based on a check of missing values or NA" }, { "code": null, "e": 26309, "s": 26178, "text": "Cells in dataframe can contain missing values or NA as its elements, and they can be verified using is.na() method in R language. " }, { "code": null, "e": 26318, "s": 26309, "text": "Example:" }, { "code": null, "e": 26320, "s": 26318, "text": "R" }, { "code": "# declaring a dataframedata_frame = data.frame(col1 = c(NA,\"b\",NA,\"e\",\"e\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values are not NAdata_frame_mod <- data_frame[!is.na(data_frame$col1),] print (\"Modified dataframe\")print (data_frame_mod)", "e": 26694, "s": 26320, "text": null }, { "code": null, "e": 26701, "s": 26694, "text": "Output" }, { "code": null, "e": 26726, "s": 26701, "text": "[1] “Original dataframe”" }, { "code": null, "e": 26743, "s": 26726, "text": " col1 col2 col3" }, { "code": null, "e": 26761, "s": 26743, "text": "1 <NA> 0 TRUE" }, { "code": null, "e": 26779, "s": 26761, "text": "2 b 2 FALSE" }, { "code": null, "e": 26797, "s": 26779, "text": "3 <NA> 1 FALSE" }, { "code": null, "e": 26815, "s": 26797, "text": "4 e 4 TRUE" }, { "code": null, "e": 26833, "s": 26815, "text": "5 e 5 TRUE" }, { "code": null, "e": 26858, "s": 26833, "text": "[1] “Modified dataframe”" }, { "code": null, "e": 26875, "s": 26858, "text": " col1 col2 col3" }, { "code": null, "e": 26893, "s": 26875, "text": "2 b 2 FALSE" }, { "code": null, "e": 26911, "s": 26893, "text": "4 e 4 TRUE" }, { "code": null, "e": 26929, "s": 26911, "text": "5 e 5 TRUE" }, { "code": null, "e": 26991, "s": 26929, "text": "Selection based on a single comparative condition on a column" }, { "code": null, "e": 27137, "s": 26991, "text": "Column values can be subjected to constraints to filter and subset the data. The values can be mapped to specific occurrences or within a range. " }, { "code": null, "e": 27146, "s": 27137, "text": "Example:" }, { "code": null, "e": 27148, "s": 27146, "text": "R" }, { "code": "# declaring a dataframedata_frame = data.frame(col1 = c(\"b\",\"b\",\"e\",\"e\",\"e\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which columns have col3# value equivalent to truedata_frame_mod <- data_frame[data_frame$col3==TRUE,] print (\"Modified dataframe\")print (data_frame_mod)", "e": 27548, "s": 27148, "text": null }, { "code": null, "e": 27555, "s": 27548, "text": "Output" }, { "code": null, "e": 27580, "s": 27555, "text": "[1] “Original dataframe”" }, { "code": null, "e": 27597, "s": 27580, "text": " col1 col2 col3" }, { "code": null, "e": 27615, "s": 27597, "text": "1 b 0 TRUE" }, { "code": null, "e": 27633, "s": 27615, "text": "2 b 2 FALSE" }, { "code": null, "e": 27651, "s": 27633, "text": "3 e 1 FALSE" }, { "code": null, "e": 27669, "s": 27651, "text": "4 e 4 TRUE" }, { "code": null, "e": 27687, "s": 27669, "text": "5 e 5 TRUE" }, { "code": null, "e": 27712, "s": 27687, "text": "[1] “Modified dataframe”" }, { "code": null, "e": 27728, "s": 27712, "text": " col1 col2 col3" }, { "code": null, "e": 27745, "s": 27728, "text": "1 b 0 TRUE" }, { "code": null, "e": 27762, "s": 27745, "text": "4 e 4 TRUE" }, { "code": null, "e": 27779, "s": 27762, "text": "5 e 5 TRUE" }, { "code": null, "e": 27842, "s": 27779, "text": "Selection based on multiple comparative conditions on a column" }, { "code": null, "e": 28096, "s": 27842, "text": "Column values can be subjected to constraints to filter and subset the data. The conditions can be combined by logical & or | operators. The %in% operator is used here, in order to check values that match to any of the values within a specified vector. " }, { "code": null, "e": 28105, "s": 28096, "text": "Example:" }, { "code": null, "e": 28107, "s": 28105, "text": "R" }, { "code": "# declaring a dataframedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"e\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- data_frame[data_frame$col1 %in% c(\"b\",\"e\"),]print (\"Modified dataframe\")print (data_frame_mod)", "e": 28513, "s": 28107, "text": null }, { "code": null, "e": 28520, "s": 28513, "text": "Output" }, { "code": null, "e": 28545, "s": 28520, "text": "[1] “Original dataframe”" }, { "code": null, "e": 28562, "s": 28545, "text": " col1 col2 col3" }, { "code": null, "e": 28580, "s": 28562, "text": "1 b 0 TRUE" }, { "code": null, "e": 28598, "s": 28580, "text": "2 b 2 FALSE" }, { "code": null, "e": 28616, "s": 28598, "text": "3 d 1 FALSE" }, { "code": null, "e": 28634, "s": 28616, "text": "4 e 4 TRUE" }, { "code": null, "e": 28652, "s": 28634, "text": "5 e 5 TRUE" }, { "code": null, "e": 28677, "s": 28652, "text": "[1] “Modified dataframe”" }, { "code": null, "e": 28694, "s": 28677, "text": " col1 col2 col3" }, { "code": null, "e": 28712, "s": 28694, "text": "1 b 0 TRUE" }, { "code": null, "e": 28730, "s": 28712, "text": "2 b 2 FALSE" }, { "code": null, "e": 28748, "s": 28730, "text": "4 e 4 TRUE" }, { "code": null, "e": 28766, "s": 28748, "text": "5 e 5 TRUE" }, { "code": null, "e": 28879, "s": 28766, "text": "The dplyr library can be installed and loaded into the working space which is used to perform data manipulation." }, { "code": null, "e": 29332, "s": 28879, "text": "The filter() function is used to produce a subset of the dataframe, retaining all rows that satisfy the specified conditions. The filter() method in R can be applied to both grouped and ungrouped data. The expressions include comparison operators (==, >, >= ) , logical operators (&, |, !, xor()) , range operators (between(), near()) as well as NA value check against the column values. The subset dataframe has to be retained in a separate variable. " }, { "code": null, "e": 29340, "s": 29332, "text": "Syntax:" }, { "code": null, "e": 29358, "s": 29340, "text": "filter(df , cond)" }, { "code": null, "e": 29371, "s": 29358, "text": "Parameter : " }, { "code": null, "e": 29398, "s": 29371, "text": "df – The dataframe object " }, { "code": null, "e": 29443, "s": 29398, "text": "cond – The condition to filter the data upon" }, { "code": null, "e": 29452, "s": 29443, "text": "Example:" }, { "code": null, "e": 29454, "s": 29452, "text": "R" }, { "code": "library (\"dplyr\") # declaring a dataframedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"e\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- filter(data_frame,col2>1) print (\"Modified dataframe\")print (data_frame_mod)", "e": 29862, "s": 29454, "text": null }, { "code": null, "e": 29869, "s": 29862, "text": "Output" }, { "code": null, "e": 29895, "s": 29869, "text": "[1] “Original dataframe” " }, { "code": null, "e": 29914, "s": 29895, "text": " col1 col2 col3 " }, { "code": null, "e": 29933, "s": 29914, "text": "1 b 0 TRUE " }, { "code": null, "e": 29952, "s": 29933, "text": "2 b 2 FALSE " }, { "code": null, "e": 29971, "s": 29952, "text": "3 d 1 FALSE " }, { "code": null, "e": 29990, "s": 29971, "text": "4 e 4 TRUE " }, { "code": null, "e": 30009, "s": 29990, "text": "5 e 5 TRUE " }, { "code": null, "e": 30035, "s": 30009, "text": "[1] “Modified dataframe” " }, { "code": null, "e": 30052, "s": 30035, "text": "col1 col2 col3 " }, { "code": null, "e": 30071, "s": 30052, "text": "1 b 2 FALSE " }, { "code": null, "e": 30090, "s": 30071, "text": "2 e 4 TRUE " }, { "code": null, "e": 30108, "s": 30090, "text": "3 e 5 TRUE" }, { "code": null, "e": 30256, "s": 30108, "text": "Also, the values can be checked using the %in% operator to match the column cell values with the elements contained in the input specified vector. " }, { "code": null, "e": 30265, "s": 30256, "text": "Example:" }, { "code": null, "e": 30267, "s": 30265, "text": "R" }, { "code": "library (\"dplyr\") # declaring a dataframedata_frame = data.frame(col1 = c(\"b\",\"b\",\"d\",\"e\",\"e\") , col2 = c(0,2,1,4,5), col3= c(TRUE,FALSE,FALSE,TRUE, TRUE)) print (\"Original dataframe\")print (data_frame) # checking which values of col1 # are equivalent to b or edata_frame_mod <- filter(data_frame,col1 %in% c(\"b\",\"e\"))print (\"Modified dataframe\")print (data_frame_mod)", "e": 30687, "s": 30267, "text": null }, { "code": null, "e": 30694, "s": 30687, "text": "Output" }, { "code": null, "e": 30719, "s": 30694, "text": "[1] “Original dataframe”" }, { "code": null, "e": 30735, "s": 30719, "text": "col1 col2 col3" }, { "code": null, "e": 30753, "s": 30735, "text": "1 b 0 TRUE" }, { "code": null, "e": 30771, "s": 30753, "text": "2 b 2 FALSE" }, { "code": null, "e": 30789, "s": 30771, "text": "3 d 1 FALSE" }, { "code": null, "e": 30807, "s": 30789, "text": "4 e 4 TRUE" }, { "code": null, "e": 30825, "s": 30807, "text": "5 e 5 TRUE" }, { "code": null, "e": 30850, "s": 30825, "text": "[1] “Modified dataframe”" }, { "code": null, "e": 30866, "s": 30850, "text": "col1 col2 col3" }, { "code": null, "e": 30884, "s": 30866, "text": "1 b 0 TRUE" }, { "code": null, "e": 30902, "s": 30884, "text": "2 b 2 FALSE" }, { "code": null, "e": 30920, "s": 30902, "text": "4 e 4 TRUE" }, { "code": null, "e": 30938, "s": 30920, "text": "5 e 5 TRUE" }, { "code": null, "e": 30945, "s": 30938, "text": "Picked" }, { "code": null, "e": 30966, "s": 30945, "text": "R DataFrame-Programs" }, { "code": null, "e": 30978, "s": 30966, "text": "R-DataFrame" }, { "code": null, "e": 30989, "s": 30978, "text": "R Language" }, { "code": null, "e": 31000, "s": 30989, "text": "R Programs" }, { "code": null, "e": 31098, "s": 31000, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31107, "s": 31098, "text": "Comments" }, { "code": null, "e": 31120, "s": 31107, "text": "Old Comments" }, { "code": null, "e": 31178, "s": 31120, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 31210, "s": 31178, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 31254, "s": 31210, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 31306, "s": 31254, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31338, "s": 31306, "text": "Printing Output of an R Program" }, { "code": null, "e": 31396, "s": 31338, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 31440, "s": 31396, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 31489, "s": 31440, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 31547, "s": 31489, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
Check privileges (grants) for a specific user in MySQL?
If you want to check privileges for a specific user, then use the below syntax − SHOW GRANTS FOR 'yourUserName'@'yourHostName'; The above syntax will check privileges for a specific user. To check the privileges for a specific user, then use FOR. Let’s say we have a username ‘JOHN‘ and host is ‘%’. Following is the query to get the privileges for user “JOHN” − mysql> SHOW GRANTS FOR 'JOHN'@'%'; This will produce the following output − +--------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- --------------+ | Grants for JOHN@% | +--------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- --------------+ | GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `JOHN`@`%` WITH GRANT OPTION | | GRANT BACKUP_ADMIN,BINLOG_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GR OUP_REPLICATION_ADMIN,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_SLAVE_A DMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SET_USE R_ID,SYSTEM_VARIABLES_ADMIN,XA_RECOVER_ADMIN ON *.* TO `JOHN`@`%` WITH GRANT OPTION | +--------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------- --------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1143, "s": 1062, "text": "If you want to check privileges for a specific user, then use the below syntax −" }, { "code": null, "e": 1190, "s": 1143, "text": "SHOW GRANTS FOR 'yourUserName'@'yourHostName';" }, { "code": null, "e": 1250, "s": 1190, "text": "The above syntax will check privileges for a specific user." }, { "code": null, "e": 1425, "s": 1250, "text": "To check the privileges for a specific user, then use FOR. Let’s say we have a username ‘JOHN‘ and host is ‘%’. Following is the query to get the privileges for user “JOHN” −" }, { "code": null, "e": 1460, "s": 1425, "text": "mysql> SHOW GRANTS FOR 'JOHN'@'%';" }, { "code": null, "e": 1501, "s": 1460, "text": "This will produce the following output −" }, { "code": null, "e": 3405, "s": 1501, "text": "+---------------------------------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------\n--------------+\n| Grants for JOHN@%\n|\n+---------------------------------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------\n--------------+\n| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN,\nPROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE\nTEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION\nCLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE\nUSER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO\n`JOHN`@`%` WITH GRANT OPTION |\n| GRANT\nBACKUP_ADMIN,BINLOG_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,GR\nOUP_REPLICATION_ADMIN,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_SLAVE_A\nDMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SET_USE\nR_ID,SYSTEM_VARIABLES_ADMIN,XA_RECOVER_ADMIN ON *.* TO `JOHN`@`%` WITH\nGRANT OPTION |\n+---------------------------------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------\n----------------------------------------------------------------------------------------------------------------------------\n--------------+\n2 rows in set (0.00 sec)" } ]
Visualizing Graph Embeddings with t-SNE in Python | by CJ Sullivan | Towards Data Science
In my previous post we discussed the purpose and nature of graph embeddings. The main idea is that to do machine learning on a graph we need to convert the graph into a series of vectors (embeddings) that we can then use to train our machine learning (ML) models. The catch is that graph embeddings can be difficult to tune. Similar to other ways to create embeddings and the models they are used for, there are a lot of hyperparameters that we need to consider and optimizing them to the specific application takes time. The subject of tuning the embeddings is something I will save for a future post. This post is about working to develop an intuition about the hyperparameters of the embeddings. More specifically, I am going to show you how you can inject graph embeddings created by the Graph Data Science (GDS) library in Neo4j and then visualize them with a Streamlit dashboard. Tomaz Bratanic developed the capability to visualize embeddings in the NEuler Neo4j tool, but I am going to demonstrate how to come at this in a purely pythonic way. You can find all of the code for this tutorial in this GitHub repo. The first thing we need to do is to create a graph to use for embedding creation using a free Neo4j Sandbox instance. For this demonstration we are going to use a graph that is pre-built into one of the Sandboxes, namely the Game of Thrones graph that has been the source of a lot of graph examples. (This graph goes through the first 5 books and I will warn you that Game of Thrones spoilers are coming up!) dev.neo4j.com When you get to the main Sandbox page, you will want to select the Graph Data Science type with pre-built data and launch the project: You will see the instance be created. Then you want to grab the connection details using the drop down to the right: Cool. Be sure to grab the Bolt URL and password, since those will be used to make our connection. If you click on Open: Open with Browser and then click on the database icon at the upper left, you should see that you have a pre-populated graph of 2642 nodes representing people, places, etc. and 16,474 relationships of a variety of types. At this point, you will want to go into the repo (you cloned it, right?) and we will adjust the Dockerfile with this information. I like to use Docker so the results are reproducible. So based on the above image, you will edit the last line of the Dockerfile to read (This Sandbox instance will be taken down by the time this article is published.) Excellent! Now we can build the Streamlit container that will be used to make the connection. I really like Streamlit because it allows you to quickly create dashboards, which can be exceptionally sophisticate, with a minimal amount of coding overhead. We will now build the container via the command line with the standard command: docker build -t neo_stream . and then we will fire it up with docker run -p 8501:8501 -v $PWD/src:/examples neo_stream (Note that you will need to adjust these commands if you are on Windows.) We now have our Streamlit container up and running, connected to our Neo4j Sandbox instance. Now that the container is running it will provide you the URL that you should navigate to with your browser. It will look something like http://172.17.0.2:8501. When you do so, you should see something that looks like this: Nice. Now let’s see what we have here. The first thing we can do is hit “Get graph list.” This will do two things. First, if you get some text back, you know that you have correctly made the connection to the Sandbox. Second, if there are any in-memory graphs created by GDS (see the API docs and this post to learn about those), then they will be listed here. Since we are just getting started, there shouldn’t be any. But we are going to create one now since they are the backbone of all of GDS. Give the graph a name and click “Create in-memory graph” (no spaces!). This is going to create a monopartite, undirected graph looking at which people in Game of Thrones interact with which other people, or (person1:Person)-[:INTERACTS]-(person2:Person) . When we do this, we will wind up with a graph that is 2166 nodes and 7814 relationships. Note that an undirected graph will double the number of relationships since it considers both orientations from person1 to person2 and person2 to person1. Spoiler alert: your embeddings will look different if you go with the natural orientation of the graph: (person1:Person)-[:INTERACTS]->(person2:Person) . Alright, now it is time to get to work and create some embeddings. As of the writing of this post, I have implemented two of the easier embeddings built into GDS, namely FastRP and node2vec. If you read the API docs, there are a lot of hyperparameters that you can and should play with because, as we know, defaults tend to not give the best results. I have included only a subset for each approach, but will add more in the future. For FastRP, I have the following: You can also click on the drop for node2vec and see what is tunable in there. I highly recommend you consult the API docs for each embedding method to get more information on what each means as describing each of them in detail is beyond the scope of this post (although in the future posts on embedding tuning we will get into the weeds on that!). So you can create both FastRP and node2vec embeddings. Now we want to visualize them. But for what goal? Let’s see if we can’t predict which characters are alive and dead at this point. This is a very basic node classification problem and it is a great starting point since this is a supervised learning problem. In the case of this data, I have labeled each Person nodes as 1 if they are alive and 0 if they are dead. We will use the t-Distributed Stochastic Neighbor Embedding (t-SNE) available in scikit-learnto perform a dimensionality reduction for the purposes of visualization in 2-dimensional space. (You could use any dimensionality reduction approach here, such as PCA. My choice of t-SNE is arbitrary.) I am going to pick some random values and generate some node2vec embeddings as shown here: Next, I am going to visualize these embeddings with the t-SNE tab. When I do that, I get this: Oh no! This is horrible! The red data points are the dead people and the blue ones are the living. We would hope that our red and blue points would cluster much better than this! I leave it as an exercise to the reader to tinker with these values and see if they can do better. (Trust me, you can!) There are some things to consider here. First, this is a very small graph. So really truly optimizing it is going to be hard in general. Second, if we really want to optimize them, we need to do more than look at a pretty picture in 2D of embeddings that are of much higher dimension. We might use a tool like this to gain the intuition of which hyperparameters are the most important for our graph and then use those for a grid search within an ML model for optimizing to our relevant metrics. Therefore, I encourage you to tinker around with these hyperparameters and see what happens. In future posts I plan to use graphs that are much larger where we can hopefully get some better embedding results and put them through their paces in ML models.
[ { "code": null, "e": 311, "s": 47, "text": "In my previous post we discussed the purpose and nature of graph embeddings. The main idea is that to do machine learning on a graph we need to convert the graph into a series of vectors (embeddings) that we can then use to train our machine learning (ML) models." }, { "code": null, "e": 650, "s": 311, "text": "The catch is that graph embeddings can be difficult to tune. Similar to other ways to create embeddings and the models they are used for, there are a lot of hyperparameters that we need to consider and optimizing them to the specific application takes time. The subject of tuning the embeddings is something I will save for a future post." }, { "code": null, "e": 1099, "s": 650, "text": "This post is about working to develop an intuition about the hyperparameters of the embeddings. More specifically, I am going to show you how you can inject graph embeddings created by the Graph Data Science (GDS) library in Neo4j and then visualize them with a Streamlit dashboard. Tomaz Bratanic developed the capability to visualize embeddings in the NEuler Neo4j tool, but I am going to demonstrate how to come at this in a purely pythonic way." }, { "code": null, "e": 1167, "s": 1099, "text": "You can find all of the code for this tutorial in this GitHub repo." }, { "code": null, "e": 1576, "s": 1167, "text": "The first thing we need to do is to create a graph to use for embedding creation using a free Neo4j Sandbox instance. For this demonstration we are going to use a graph that is pre-built into one of the Sandboxes, namely the Game of Thrones graph that has been the source of a lot of graph examples. (This graph goes through the first 5 books and I will warn you that Game of Thrones spoilers are coming up!)" }, { "code": null, "e": 1590, "s": 1576, "text": "dev.neo4j.com" }, { "code": null, "e": 1725, "s": 1590, "text": "When you get to the main Sandbox page, you will want to select the Graph Data Science type with pre-built data and launch the project:" }, { "code": null, "e": 1842, "s": 1725, "text": "You will see the instance be created. Then you want to grab the connection details using the drop down to the right:" }, { "code": null, "e": 2182, "s": 1842, "text": "Cool. Be sure to grab the Bolt URL and password, since those will be used to make our connection. If you click on Open: Open with Browser and then click on the database icon at the upper left, you should see that you have a pre-populated graph of 2642 nodes representing people, places, etc. and 16,474 relationships of a variety of types." }, { "code": null, "e": 2449, "s": 2182, "text": "At this point, you will want to go into the repo (you cloned it, right?) and we will adjust the Dockerfile with this information. I like to use Docker so the results are reproducible. So based on the above image, you will edit the last line of the Dockerfile to read" }, { "code": null, "e": 2531, "s": 2449, "text": "(This Sandbox instance will be taken down by the time this article is published.)" }, { "code": null, "e": 2864, "s": 2531, "text": "Excellent! Now we can build the Streamlit container that will be used to make the connection. I really like Streamlit because it allows you to quickly create dashboards, which can be exceptionally sophisticate, with a minimal amount of coding overhead. We will now build the container via the command line with the standard command:" }, { "code": null, "e": 2893, "s": 2864, "text": "docker build -t neo_stream ." }, { "code": null, "e": 2926, "s": 2893, "text": "and then we will fire it up with" }, { "code": null, "e": 2983, "s": 2926, "text": "docker run -p 8501:8501 -v $PWD/src:/examples neo_stream" }, { "code": null, "e": 3057, "s": 2983, "text": "(Note that you will need to adjust these commands if you are on Windows.)" }, { "code": null, "e": 3374, "s": 3057, "text": "We now have our Streamlit container up and running, connected to our Neo4j Sandbox instance. Now that the container is running it will provide you the URL that you should navigate to with your browser. It will look something like http://172.17.0.2:8501. When you do so, you should see something that looks like this:" }, { "code": null, "e": 3794, "s": 3374, "text": "Nice. Now let’s see what we have here. The first thing we can do is hit “Get graph list.” This will do two things. First, if you get some text back, you know that you have correctly made the connection to the Sandbox. Second, if there are any in-memory graphs created by GDS (see the API docs and this post to learn about those), then they will be listed here. Since we are just getting started, there shouldn’t be any." }, { "code": null, "e": 4526, "s": 3794, "text": "But we are going to create one now since they are the backbone of all of GDS. Give the graph a name and click “Create in-memory graph” (no spaces!). This is going to create a monopartite, undirected graph looking at which people in Game of Thrones interact with which other people, or (person1:Person)-[:INTERACTS]-(person2:Person) . When we do this, we will wind up with a graph that is 2166 nodes and 7814 relationships. Note that an undirected graph will double the number of relationships since it considers both orientations from person1 to person2 and person2 to person1. Spoiler alert: your embeddings will look different if you go with the natural orientation of the graph: (person1:Person)-[:INTERACTS]->(person2:Person) ." }, { "code": null, "e": 4993, "s": 4526, "text": "Alright, now it is time to get to work and create some embeddings. As of the writing of this post, I have implemented two of the easier embeddings built into GDS, namely FastRP and node2vec. If you read the API docs, there are a lot of hyperparameters that you can and should play with because, as we know, defaults tend to not give the best results. I have included only a subset for each approach, but will add more in the future. For FastRP, I have the following:" }, { "code": null, "e": 5342, "s": 4993, "text": "You can also click on the drop for node2vec and see what is tunable in there. I highly recommend you consult the API docs for each embedding method to get more information on what each means as describing each of them in detail is beyond the scope of this post (although in the future posts on embedding tuning we will get into the weeds on that!)." }, { "code": null, "e": 5761, "s": 5342, "text": "So you can create both FastRP and node2vec embeddings. Now we want to visualize them. But for what goal? Let’s see if we can’t predict which characters are alive and dead at this point. This is a very basic node classification problem and it is a great starting point since this is a supervised learning problem. In the case of this data, I have labeled each Person nodes as 1 if they are alive and 0 if they are dead." }, { "code": null, "e": 6056, "s": 5761, "text": "We will use the t-Distributed Stochastic Neighbor Embedding (t-SNE) available in scikit-learnto perform a dimensionality reduction for the purposes of visualization in 2-dimensional space. (You could use any dimensionality reduction approach here, such as PCA. My choice of t-SNE is arbitrary.)" }, { "code": null, "e": 6147, "s": 6056, "text": "I am going to pick some random values and generate some node2vec embeddings as shown here:" }, { "code": null, "e": 6242, "s": 6147, "text": "Next, I am going to visualize these embeddings with the t-SNE tab. When I do that, I get this:" }, { "code": null, "e": 6541, "s": 6242, "text": "Oh no! This is horrible! The red data points are the dead people and the blue ones are the living. We would hope that our red and blue points would cluster much better than this! I leave it as an exercise to the reader to tinker with these values and see if they can do better. (Trust me, you can!)" }, { "code": null, "e": 7129, "s": 6541, "text": "There are some things to consider here. First, this is a very small graph. So really truly optimizing it is going to be hard in general. Second, if we really want to optimize them, we need to do more than look at a pretty picture in 2D of embeddings that are of much higher dimension. We might use a tool like this to gain the intuition of which hyperparameters are the most important for our graph and then use those for a grid search within an ML model for optimizing to our relevant metrics. Therefore, I encourage you to tinker around with these hyperparameters and see what happens." } ]
MCQ on Memory allocation and compilation process in C
Here we will see some MCQ questions on Memory Allocation and Compilation Processes. Question 1 − What will be the output of the following code − Live Demo #include <stdio.h> #include <stdlib.h> int main() { union my_union { int i; float f; char c; }; union my_union* u; u = (union my_union*)malloc(sizeof(union my_union)); u->f = 20.60f; printf("%f", u->f); } Options − Garbage Value 20.600000 Syntax Error 20.6 Explanation Using unions, we can use same memory location to hold multiple type of data. All member of union uses same memory location which has maximum space. Here float is used, which has 20.60f = 20.600000. So answer B is correct. Question 2 − What is the correct sequence of the compilation Process − Options − Assembler, Compiler, Preprocessor, Linking Compiler, Assembler, Preprocessor, Linking Preprocessor, Compiler, Assembler, Linking Assembler, Compiler, Linking, Preprocessor Explanation − The option C is correct, At first it preprocess the code, then compile it, after that it creates assembly level code, or object code, then the linking is taken place. Question 3 − Which of the following statement is true? Options − During Linking the Code #include replaces by stdio.h During Preprocessing the Code #include replaces by stdio.h During Execution the Code #include replaces by stdio.h During Editing the Code #include replaces by stdio.h Explanation − The option B is correct. At first, it creates the preprocessed code, in that phase, it attaches the codes present in file mentioned in #include statements into the code then sent to the compiler. Question 4 − Purpose of using fflush() function − Options − To flush all streams and specified streams To flush only specified streams To flush input-output buffer This is invalid library function Explanation − This function is used to flush output stream only. It clears the output buffer and send the output to the console. The option A is correct. Question 5 − Point out the error of the following code − #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char* ptr; *ptr = (int*)malloc(30); strcpy(ptr, "ABC"); printf("%s", ptr); free(ptr); } Options − Error in strcpy() statement Error in *ptr = (int*)malloc(30); Error in free(ptr) No Error Explanation − The option B is correct. Here this makes integer from pointer, without a cast
[ { "code": null, "e": 1146, "s": 1062, "text": "Here we will see some MCQ questions on Memory Allocation and Compilation Processes." }, { "code": null, "e": 1207, "s": 1146, "text": "Question 1 − What will be the output of the following code −" }, { "code": null, "e": 1218, "s": 1207, "text": " Live Demo" }, { "code": null, "e": 1459, "s": 1218, "text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n union my_union {\n int i;\n float f;\n char c;\n };\n union my_union* u;\n u = (union my_union*)malloc(sizeof(union my_union));\n u->f = 20.60f;\n printf(\"%f\", u->f);\n}" }, { "code": null, "e": 1469, "s": 1459, "text": "Options −" }, { "code": null, "e": 1483, "s": 1469, "text": "Garbage Value" }, { "code": null, "e": 1493, "s": 1483, "text": "20.600000" }, { "code": null, "e": 1506, "s": 1493, "text": "Syntax Error" }, { "code": null, "e": 1511, "s": 1506, "text": "20.6" }, { "code": null, "e": 1523, "s": 1511, "text": "Explanation" }, { "code": null, "e": 1745, "s": 1523, "text": "Using unions, we can use same memory location to hold multiple type of data. All member of union uses same memory location which has maximum space. Here float is used, which has 20.60f = 20.600000. So answer B is correct." }, { "code": null, "e": 1816, "s": 1745, "text": "Question 2 − What is the correct sequence of the compilation Process −" }, { "code": null, "e": 1826, "s": 1816, "text": "Options −" }, { "code": null, "e": 1869, "s": 1826, "text": "Assembler, Compiler, Preprocessor, Linking" }, { "code": null, "e": 1912, "s": 1869, "text": "Compiler, Assembler, Preprocessor, Linking" }, { "code": null, "e": 1955, "s": 1912, "text": "Preprocessor, Compiler, Assembler, Linking" }, { "code": null, "e": 1998, "s": 1955, "text": "Assembler, Compiler, Linking, Preprocessor" }, { "code": null, "e": 2012, "s": 1998, "text": "Explanation −" }, { "code": null, "e": 2179, "s": 2012, "text": "The option C is correct, At first it preprocess the code, then compile it, after that it creates assembly level code, or object code, then the linking is\ntaken place." }, { "code": null, "e": 2234, "s": 2179, "text": "Question 3 − Which of the following statement is true?" }, { "code": null, "e": 2244, "s": 2234, "text": "Options −" }, { "code": null, "e": 2297, "s": 2244, "text": "During Linking the Code #include replaces by stdio.h" }, { "code": null, "e": 2356, "s": 2297, "text": "During Preprocessing the Code #include replaces by stdio.h" }, { "code": null, "e": 2411, "s": 2356, "text": "During Execution the Code #include replaces by stdio.h" }, { "code": null, "e": 2464, "s": 2411, "text": "During Editing the Code #include replaces by stdio.h" }, { "code": null, "e": 2478, "s": 2464, "text": "Explanation −" }, { "code": null, "e": 2674, "s": 2478, "text": "The option B is correct. At first, it creates the preprocessed code, in that phase, it attaches the codes present in file mentioned in #include statements into the code then sent to the compiler." }, { "code": null, "e": 2724, "s": 2674, "text": "Question 4 − Purpose of using fflush() function −" }, { "code": null, "e": 2734, "s": 2724, "text": "Options −" }, { "code": null, "e": 2777, "s": 2734, "text": "To flush all streams and specified streams" }, { "code": null, "e": 2809, "s": 2777, "text": "To flush only specified streams" }, { "code": null, "e": 2838, "s": 2809, "text": "To flush input-output buffer" }, { "code": null, "e": 2871, "s": 2838, "text": "This is invalid library function" }, { "code": null, "e": 2885, "s": 2871, "text": "Explanation −" }, { "code": null, "e": 3025, "s": 2885, "text": "This function is used to flush output stream only. It clears the output buffer and send the output to the console. The option A is correct." }, { "code": null, "e": 3082, "s": 3025, "text": "Question 5 − Point out the error of the following code −" }, { "code": null, "e": 3257, "s": 3082, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nint main() {\n char* ptr;\n *ptr = (int*)malloc(30);\n strcpy(ptr, \"ABC\");\n printf(\"%s\", ptr);\n free(ptr);\n}" }, { "code": null, "e": 3267, "s": 3257, "text": "Options −" }, { "code": null, "e": 3295, "s": 3267, "text": "Error in strcpy() statement" }, { "code": null, "e": 3329, "s": 3295, "text": "Error in *ptr = (int*)malloc(30);" }, { "code": null, "e": 3348, "s": 3329, "text": "Error in free(ptr)" }, { "code": null, "e": 3357, "s": 3348, "text": "No Error" }, { "code": null, "e": 3371, "s": 3357, "text": "Explanation −" }, { "code": null, "e": 3449, "s": 3371, "text": "The option B is correct. Here this makes integer from pointer, without a cast" } ]
What are the main file components in Cucumber?
The main file components in Cucumber are listed below − Feature file − This file has an extension of .feature. It comprises single or multiple test scenarios in plain text. All the scenarios are written with the keywords like Then, Given, When, And, But, Feature, Background and so on. Feature file − This file has an extension of .feature. It comprises single or multiple test scenarios in plain text. All the scenarios are written with the keywords like Then, Given, When, And, But, Feature, Background and so on. Feature file. Feature: Login Test Scenario: Tutorialspoint login validation Given: Launch the “https://www.tutorialspoint.com/index.htm” Step Definition File - This file has an extension of .java. It provides mapping of the test scenarios to the test script logic. Step Definition File - This file has an extension of .java. It provides mapping of the test scenarios to the test script logic. Step Definition file based on the above feature file. @Given (“^Launch the \"([^\"]*)\"$”) public void launch_application(String url){ System.out.println("The url is : " + url); } Test Runner file - This file has an extension of .java. It acts as a link between the step definition file and feature file. It gives the option of selecting a single or multiple feature files. It has the path of the step definition file and the feature file. Test Runner file - This file has an extension of .java. It acts as a link between the step definition file and feature file. It gives the option of selecting a single or multiple feature files. It has the path of the step definition file and the feature file. Test Runner file import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import cucumber.api.testng.AbstractTestNGCucumberTests; @CucumberOptions( features = "src/test/java/features", glue="stepDefinations") public class TestRunner extends AbstractTestNGCucumberTests { }
[ { "code": null, "e": 1118, "s": 1062, "text": "The main file components in Cucumber are listed below −" }, { "code": null, "e": 1348, "s": 1118, "text": "Feature file − This file has an extension of .feature. It comprises single or multiple test scenarios in plain text. All the scenarios are written with the\nkeywords like Then, Given, When, And, But, Feature, Background and so on." }, { "code": null, "e": 1578, "s": 1348, "text": "Feature file − This file has an extension of .feature. It comprises single or multiple test scenarios in plain text. All the scenarios are written with the\nkeywords like Then, Given, When, And, But, Feature, Background and so on." }, { "code": null, "e": 1592, "s": 1578, "text": "Feature file." }, { "code": null, "e": 1715, "s": 1592, "text": "Feature: Login Test\nScenario: Tutorialspoint login validation\nGiven: Launch the “https://www.tutorialspoint.com/index.htm”" }, { "code": null, "e": 1843, "s": 1715, "text": "Step Definition File - This file has an extension of .java. It provides mapping\nof the test scenarios to the test script logic." }, { "code": null, "e": 1971, "s": 1843, "text": "Step Definition File - This file has an extension of .java. It provides mapping\nof the test scenarios to the test script logic." }, { "code": null, "e": 2025, "s": 1971, "text": "Step Definition file based on the above feature file." }, { "code": null, "e": 2154, "s": 2025, "text": "@Given (“^Launch the \\\"([^\\\"]*)\\\"$”)\npublic void launch_application(String url){\n System.out.println(\"The url is : \" + url);\n}" }, { "code": null, "e": 2414, "s": 2154, "text": "Test Runner file - This file has an extension of .java. It acts as a link between\nthe step definition file and feature file. It gives the option of selecting a single\nor multiple feature files. It has the path of the step definition file and the feature file." }, { "code": null, "e": 2674, "s": 2414, "text": "Test Runner file - This file has an extension of .java. It acts as a link between\nthe step definition file and feature file. It gives the option of selecting a single\nor multiple feature files. It has the path of the step definition file and the feature file." }, { "code": null, "e": 2691, "s": 2674, "text": "Test Runner file" }, { "code": null, "e": 3002, "s": 2691, "text": "import org.junit.runner.RunWith;\nimport cucumber.api.CucumberOptions;\nimport cucumber.api.junit.Cucumber;\nimport cucumber.api.testng.AbstractTestNGCucumberTests;\n@CucumberOptions(\n features = \"src/test/java/features\",\n glue=\"stepDefinations\")\npublic class TestRunner extends AbstractTestNGCucumberTests { }" } ]
How can we update the values of a collection using LINQ in C#?
If the collection is a List, then we can make use of ForEach extension method which is available as part of LINQ. Live Demo using System; using System.Collections.Generic; namespace DemoApplication { class Program { static void Main(string[] args) { List<Fruit> fruits = new List<Fruit> { new Fruit { Name = "Apple", Size = "Small" }, new Fruit { Name = "Orange", Size = "Small" } }; foreach(var fruit in fruits) { Console.WriteLine($"Fruit Details Before Update. {fruit.Name}, {fruit.Size}"); } fruits.ForEach(fruit => { fruit.Size = "Large"; }); foreach (var fruit in fruits) { Console.WriteLine($"Fruit Details After Update. {fruit.Name}, {fruit.Size}"); } Console.ReadLine(); } } public class Fruit { public string Name { get; set; } public string Size { get; set; } } } The output of the above code is Fruit Details Before Update. Apple, Small Fruit Details Before Update. Orange, Small Fruit Details After Update. Apple, Large Fruit Details After Update. Orange, Large If we want to update the list items based on a condition, we can make use of Where() clause. Live Demo using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication { class Program { static void Main(string[] args) { IEnumerable<Fruit> fruits = new List<Fruit> { new Fruit { Name = "Apple", Size = "Small" }, new Fruit { Name = "Orange", Size = "Small" }, new Fruit { Name = "Mango", Size = "Medium" } }; foreach(var fruit in fruits) { Console.WriteLine($"Fruit Details Before Update. {fruit.Name}, {fruit.Size}"); } foreach (var fruit in fruits.Where(w => w.Size == "Small")) { fruit.Size = "Large"; } foreach (var fruit in fruits) { Console.WriteLine($"Fruit Details After Update. {fruit.Name}, {fruit.Size}"); } Console.ReadLine(); } } public class Fruit { public string Name { get; set; } public string Size { get; set; } } } The output of the above code is Fruit Details Before Update. Apple, Small Fruit Details Before Update. Orange, Small Fruit Details Before Update. Mango, Medium Fruit Details After Update. Apple, Large Fruit Details After Update. Orange, Large Fruit Details After Update. Mango, Medium In the above we are filtering only the fruits having small size and updating the values. So, the where clause filters the record based on a condition.
[ { "code": null, "e": 1176, "s": 1062, "text": "If the collection is a List, then we can make use of ForEach extension method which is available as part of LINQ." }, { "code": null, "e": 1187, "s": 1176, "text": " Live Demo" }, { "code": null, "e": 2078, "s": 1187, "text": "using System;\nusing System.Collections.Generic;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n List<Fruit> fruits = new List<Fruit> {\n new Fruit {\n Name = \"Apple\",\n Size = \"Small\"\n },\n new Fruit {\n Name = \"Orange\",\n Size = \"Small\"\n }\n };\n foreach(var fruit in fruits) {\n Console.WriteLine($\"Fruit Details Before Update. {fruit.Name}, {fruit.Size}\");\n }\n fruits.ForEach(fruit => { fruit.Size = \"Large\"; });\n foreach (var fruit in fruits) {\n Console.WriteLine($\"Fruit Details After Update. {fruit.Name}, {fruit.Size}\");\n }\n Console.ReadLine();\n }\n }\n public class Fruit {\n public string Name { get; set; }\n public string Size { get; set; }\n }\n}" }, { "code": null, "e": 2110, "s": 2078, "text": "The output of the above code is" }, { "code": null, "e": 2278, "s": 2110, "text": "Fruit Details Before Update. Apple, Small\nFruit Details Before Update. Orange, Small\nFruit Details After Update. Apple, Large\nFruit Details After Update. Orange, Large" }, { "code": null, "e": 2371, "s": 2278, "text": "If we want to update the list items based on a condition, we can make use of Where() clause." }, { "code": null, "e": 2382, "s": 2371, "text": " Live Demo" }, { "code": null, "e": 3455, "s": 2382, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n IEnumerable<Fruit> fruits = new List<Fruit> {\n new Fruit {\n Name = \"Apple\",\n Size = \"Small\"\n },\n new Fruit {\n Name = \"Orange\",\n Size = \"Small\"\n },\n new Fruit {\n Name = \"Mango\",\n Size = \"Medium\"\n }\n };\n foreach(var fruit in fruits) {\n Console.WriteLine($\"Fruit Details Before Update. {fruit.Name}, {fruit.Size}\");\n }\n foreach (var fruit in fruits.Where(w => w.Size == \"Small\")) {\n fruit.Size = \"Large\";\n }\n foreach (var fruit in fruits) {\n Console.WriteLine($\"Fruit Details After Update. {fruit.Name}, {fruit.Size}\");\n }\n Console.ReadLine();\n }\n }\n public class Fruit {\n public string Name { get; set; }\n public string Size { get; set; }\n }\n}" }, { "code": null, "e": 3487, "s": 3455, "text": "The output of the above code is" }, { "code": null, "e": 3740, "s": 3487, "text": "Fruit Details Before Update. Apple, Small\nFruit Details Before Update. Orange, Small\nFruit Details Before Update. Mango, Medium\nFruit Details After Update. Apple, Large\nFruit Details After Update. Orange, Large\nFruit Details After Update. Mango, Medium" }, { "code": null, "e": 3891, "s": 3740, "text": "In the above we are filtering only the fruits having small size and updating the values. So, the where clause filters the record based on a condition." } ]
.NET Core - Create a Testing Project
In this chapter, we will discuss how to create a Testing project using .NET Core. Unit testing is a development process for the software that has the smallest testable parts of an application, which are called units. They are individually and independently scrutinized for any proper operation. Unit testing is can either be automated or done manually as well. Let us now open the New Project dialog box and select Visual C# → .NET Core template. On this dialog box, you can see that there is no project template for unit testing. To create a unit test project, we should use the command line utility. Let us go to the Solution folder that we created; create a test folder and inside the test folder create another folder and call it StringLibraryTests. Let us now use the dotnet commandline utility to create a new test project by executing the following command − dotnet new -t xunittest You can now see that a new C# project is created; let us look into the folder by executing the v command and you will see project.json and Tests.cs files as shown below. Here is the code in project.json file. { "version": "1.0.0-*", "buildOptions": { "debugType": "portable" }, "dependencies": { "System.Runtime.Serialization.Primitives": "4.1.1", "xunit": "2.1.0", "dotnet-test-xunit": "1.0.0-rc2-192208-24" }, "testRunner": "xunit", "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.1" } }, "imports": [ "dotnet5.4", "portable-net451+win8" ] } } } Following is the code in the Test.cs file. using System; using Xunit; namespace Tests { public class Tests { [Fact] public void Test1() { Assert.True(true); } } } To fetch the necessary dependencies from NuGet, let us execute the following command − dotnet restore We can run the test when the necessary dependencies are restored. You can see that the compilation succeeded; as you go down you can see some information about the test executed. Currently we have 1 test executed, 0 error, 0 failed, 0 skipped and the time taken by the execution process also mentioned as information. Print Add Notes Bookmark this page
[ { "code": null, "e": 2747, "s": 2386, "text": "In this chapter, we will discuss how to create a Testing project using .NET Core. Unit testing is a development process for the software that has the smallest testable parts of an application, which are called units. They are individually and independently scrutinized for any proper operation. Unit testing is can either be automated or done manually as well." }, { "code": null, "e": 2833, "s": 2747, "text": "Let us now open the New Project dialog box and select Visual C# → .NET Core template." }, { "code": null, "e": 3140, "s": 2833, "text": "On this dialog box, you can see that there is no project template for unit testing. To create a unit test project, we should use the command line utility. Let us go to the Solution folder that we created; create a test folder and inside the test folder create another folder and call it StringLibraryTests." }, { "code": null, "e": 3252, "s": 3140, "text": "Let us now use the dotnet commandline utility to create a new test project by executing the following command −" }, { "code": null, "e": 3277, "s": 3252, "text": "dotnet new -t xunittest\n" }, { "code": null, "e": 3447, "s": 3277, "text": "You can now see that a new C# project is created; let us look into the folder by executing the v command and you will see project.json and Tests.cs files as shown below." }, { "code": null, "e": 3486, "s": 3447, "text": "Here is the code in project.json file." }, { "code": null, "e": 4093, "s": 3486, "text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"debugType\": \"portable\" \n }, \n \"dependencies\": { \n \"System.Runtime.Serialization.Primitives\": \"4.1.1\", \n \"xunit\": \"2.1.0\", \n \"dotnet-test-xunit\": \"1.0.0-rc2-192208-24\" \n }, \n \"testRunner\": \"xunit\", \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n } \n }, \n \"imports\": [ \n \"dotnet5.4\", \n \"portable-net451+win8\" \n ] \n } \n } \n} " }, { "code": null, "e": 4136, "s": 4093, "text": "Following is the code in the Test.cs file." }, { "code": null, "e": 4299, "s": 4136, "text": "using System; \nusing Xunit; \nnamespace Tests { \n public class Tests { \n [Fact] \n public void Test1() { \n Assert.True(true); \n } \n } \n} " }, { "code": null, "e": 4386, "s": 4299, "text": "To fetch the necessary dependencies from NuGet, let us execute the following command −" }, { "code": null, "e": 4402, "s": 4386, "text": "dotnet restore\n" }, { "code": null, "e": 4468, "s": 4402, "text": "We can run the test when the necessary dependencies are restored." }, { "code": null, "e": 4581, "s": 4468, "text": "You can see that the compilation succeeded; as you go down you can see some information about the test executed." }, { "code": null, "e": 4720, "s": 4581, "text": "Currently we have 1 test executed, 0 error, 0 failed, 0 skipped and the time taken by the execution process also mentioned as information." }, { "code": null, "e": 4727, "s": 4720, "text": " Print" }, { "code": null, "e": 4738, "s": 4727, "text": " Add Notes" } ]
Convert.ToBase64String() Method in C#
The Convert.ToBase64String() method in C# is used to convert the value of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits. Following is the syntax − public static string ToBase64String (byte[] arr); Above, arr is an array of 8-bit unsigned integers. Let us now see an example to implement the Convert.ToBase64String() method − Using System; public class Demo { public static void Main(){ byte[] val1 = {5,10,15,20,25,30}; string str = Convert.ToBase64String(val1); Console.WriteLine("Base 64 string: '{0}'", str); byte[] val2 = Convert.FromBase64String(str); Console.WriteLine("Converted byte value: {0}", BitConverter.ToString(val2)); } } This will produce the following output − Base 64 string: 'BQoPFBke' Converted byte value: 05-0A-0F-14-19-1E
[ { "code": null, "e": 1249, "s": 1062, "text": "The Convert.ToBase64String() method in C# is used to convert the value of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits." }, { "code": null, "e": 1275, "s": 1249, "text": "Following is the syntax −" }, { "code": null, "e": 1325, "s": 1275, "text": "public static string ToBase64String (byte[] arr);" }, { "code": null, "e": 1376, "s": 1325, "text": "Above, arr is an array of 8-bit unsigned integers." }, { "code": null, "e": 1453, "s": 1376, "text": "Let us now see an example to implement the Convert.ToBase64String() method −" }, { "code": null, "e": 1802, "s": 1453, "text": "Using System;\npublic class Demo {\n public static void Main(){\n byte[] val1 = {5,10,15,20,25,30};\n string str = Convert.ToBase64String(val1);\n Console.WriteLine(\"Base 64 string: '{0}'\", str);\n byte[] val2 = Convert.FromBase64String(str);\n Console.WriteLine(\"Converted byte value: {0}\", BitConverter.ToString(val2));\n }\n}" }, { "code": null, "e": 1843, "s": 1802, "text": "This will produce the following output −" }, { "code": null, "e": 1910, "s": 1843, "text": "Base 64 string: 'BQoPFBke'\nConverted byte value: 05-0A-0F-14-19-1E" } ]
Cohesion in Java - GeeksforGeeks
06 Dec, 2021 Cohesion in Java is the Object-Oriented principle most closely associated with making sure that a class is designed with a single, well-focused purpose. In object-oriented design, cohesion refers all to how a single class is designed. Note: The more focused a class is, the more cohesiveness of that class is more. The advantage of high cohesion is that such classes are much easier to maintain (and less frequently changed) than classes with low cohesion. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes. Example: Suppose we have a class that multiplies two numbers, but the same class creates a pop-up window displaying the result. This is an example of a low cohesive class because the window and the multiplication operation don’t have much in common. To make it high cohesive, we would have to create a class Display and a class Multiply. The Display will call Multiply’s method to get the result and display it. This way to develop a high cohesive solution. Let us understand the structure of the high cohesive program: Java // Java program to illustrate// high cohesive behavior class Multiply { int a = 5; int b = 5; public int mul(int a, int b) { this.a = a; this.b = b; return a * b; }} class Display { public static void main(String[] args) { Multiply m = new Multiply(); System.out.println(m.mul(5, 5)); }} 25 Java // Java program to illustrate// high cohesive behavior class Name { String name; public String getName(String name) { this.name = name; return name; }} class Age { int age; public int getAge(int age) { this.age = age; return age; }} class Number { int mobileno; public int getNumber(int mobileno) { this.mobileno = mobileno; return mobileno; }} class Display { public static void main(String[] args) { Name n = new Name(); System.out.println(n.getName("Geeksforgeeks")); Age a = new Age(); System.out.println(a.getAge(10)); Number no = new Number(); System.out.println(no.getNumber(1234567891)); }} Geeksforgeeks 10 1234567891 Pictorial view of high cohesion and low cohesion: Explanation: In the above image, we can see that in low cohesion only one class is responsible to execute lots of jobs that are not in common which reduces the chance of reusability and maintenance. But in high cohesion, there is a separate class for all the jobs to execute a specific job, which results in better usability and maintenance. Difference between high cohesion and low cohesion: High cohesion is when you have a class that does a well-defined job. Low cohesion is when a class does a lot of jobs that don’t have much in common. High cohesion gives us better-maintaining facility and Low cohesion results in monolithic classes that are difficult to maintain, understand and reduce re-usability This article is contributed by Bishal Kumar Dubey. 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. nishkarshgandhi Java-Class and Object Java Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java Set in Java LinkedList in Java Collections in Java
[ { "code": null, "e": 24211, "s": 24183, "text": "\n06 Dec, 2021" }, { "code": null, "e": 24447, "s": 24211, "text": "Cohesion in Java is the Object-Oriented principle most closely associated with making sure that a class is designed with a single, well-focused purpose. In object-oriented design, cohesion refers all to how a single class is designed. " }, { "code": null, "e": 24528, "s": 24447, "text": "Note: The more focused a class is, the more cohesiveness of that class is more. " }, { "code": null, "e": 24793, "s": 24528, "text": "The advantage of high cohesion is that such classes are much easier to maintain (and less frequently changed) than classes with low cohesion. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes. " }, { "code": null, "e": 25251, "s": 24793, "text": "Example: Suppose we have a class that multiplies two numbers, but the same class creates a pop-up window displaying the result. This is an example of a low cohesive class because the window and the multiplication operation don’t have much in common. To make it high cohesive, we would have to create a class Display and a class Multiply. The Display will call Multiply’s method to get the result and display it. This way to develop a high cohesive solution." }, { "code": null, "e": 25314, "s": 25251, "text": "Let us understand the structure of the high cohesive program: " }, { "code": null, "e": 25319, "s": 25314, "text": "Java" }, { "code": "// Java program to illustrate// high cohesive behavior class Multiply { int a = 5; int b = 5; public int mul(int a, int b) { this.a = a; this.b = b; return a * b; }} class Display { public static void main(String[] args) { Multiply m = new Multiply(); System.out.println(m.mul(5, 5)); }}", "e": 25672, "s": 25319, "text": null }, { "code": null, "e": 25675, "s": 25672, "text": "25" }, { "code": null, "e": 25680, "s": 25675, "text": "Java" }, { "code": "// Java program to illustrate// high cohesive behavior class Name { String name; public String getName(String name) { this.name = name; return name; }} class Age { int age; public int getAge(int age) { this.age = age; return age; }} class Number { int mobileno; public int getNumber(int mobileno) { this.mobileno = mobileno; return mobileno; }} class Display { public static void main(String[] args) { Name n = new Name(); System.out.println(n.getName(\"Geeksforgeeks\")); Age a = new Age(); System.out.println(a.getAge(10)); Number no = new Number(); System.out.println(no.getNumber(1234567891)); }}", "e": 26408, "s": 25680, "text": null }, { "code": null, "e": 26436, "s": 26408, "text": "Geeksforgeeks\n10\n1234567891" }, { "code": null, "e": 26488, "s": 26436, "text": "Pictorial view of high cohesion and low cohesion: " }, { "code": null, "e": 26830, "s": 26488, "text": "Explanation: In the above image, we can see that in low cohesion only one class is responsible to execute lots of jobs that are not in common which reduces the chance of reusability and maintenance. But in high cohesion, there is a separate class for all the jobs to execute a specific job, which results in better usability and maintenance." }, { "code": null, "e": 26882, "s": 26830, "text": "Difference between high cohesion and low cohesion: " }, { "code": null, "e": 27031, "s": 26882, "text": "High cohesion is when you have a class that does a well-defined job. Low cohesion is when a class does a lot of jobs that don’t have much in common." }, { "code": null, "e": 27196, "s": 27031, "text": "High cohesion gives us better-maintaining facility and Low cohesion results in monolithic classes that are difficult to maintain, understand and reduce re-usability" }, { "code": null, "e": 27623, "s": 27196, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using 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": 27639, "s": 27623, "text": "nishkarshgandhi" }, { "code": null, "e": 27661, "s": 27639, "text": "Java-Class and Object" }, { "code": null, "e": 27666, "s": 27661, "text": "Java" }, { "code": null, "e": 27688, "s": 27666, "text": "Java-Class and Object" }, { "code": null, "e": 27693, "s": 27688, "text": "Java" }, { "code": null, "e": 27791, "s": 27693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27823, "s": 27791, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27842, "s": 27823, "text": "Interfaces in Java" }, { "code": null, "e": 27860, "s": 27842, "text": "ArrayList in Java" }, { "code": null, "e": 27892, "s": 27860, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27907, "s": 27892, "text": "Stream In Java" }, { "code": null, "e": 27927, "s": 27907, "text": "Stack Class in Java" }, { "code": null, "e": 27951, "s": 27927, "text": "Singleton Class in Java" }, { "code": null, "e": 27963, "s": 27951, "text": "Set in Java" }, { "code": null, "e": 27982, "s": 27963, "text": "LinkedList in Java" } ]
What is the difference between PCA and Factor Analysis? | by Joos Korstanje | Towards Data Science
PCA, short for Principal Component Analysis, and Factor Analysis, are two statistical methods that are often covered together in classes on Multivariate Statistics. In this article, you will discover the mathematical and practical differences between the two methods. Multivariate Statistics is a group of statistical methods that focus on studying multiple variables together while focusing on the variation that those variables have in common. Multivariate Statistics deals with the treatment of data sets with a large number of dimensions. Its goals are therefore different from supervised modeling, but also different from segmentation and clustering models. There are many models in the family of Multivariate Statistics. In this article, I will focus on the difference between PCA and Factor Analysis, two commonly used Multivariate models. Modern datasets often have a very large number of variables. This makes it difficult to inspect each of the variables individually, due to the practical fact that the human mind cannot easily digest data on such a large scale. When a dataset contains a large number of variables, there is often a serious amount of overlap between those variables. The components that are found by PCA are ordered from the highest information content to the lowest information content. PCA is a statistical method that allows you to “regroup” your variables into a smaller number of variables, called components. This regrouping is done based on variation that is common to multiple variables. The goal of PCA is to regroup variables in such a way that the first (newly created) component contains a maximum of variation. The second component contains the second-largest amount of variation, etc etc. The last component logically contains the smallest amount of variation. Thanks to this ordering of components, it is made possible to retain only a few of the newly created components, while still retaining a maximum amount of variation. We can then use the components rather than the original variables for data exploration. The mathematical definition of the PCA problem is to find a linear combination of the original variables with maximum variance. This means that we are going to create a (new) component. Let’s call it z. This z is going to be computed based on our original variables (X1, X2, ...) multiplied by a weight for each of our variables (u1, u2, ...). This can be written as z = Xu. The mathematical goal is to find the values for u that will maximize the variance of z, with a constraint of unit length on u. This problem is mathematically called a constrained optimization using Lagrange Multiplier, but in practice, we use computers to do the whole PCA operation at once. This can also be described as applying matrix decomposition to the correlation matrix of the original variables. PCA is efficient in finding the components that maximize variance. This is great if we are interested in reducing the number of variables while keeping a maximum of variance. Sometimes, however, we are not purely interested in maximizating variance: we might want to give the most useful interpretations to our newly defined dimensions. And this is not always easiest with the solution found by a PCA. We can then apply Factor Analysis: an alternative to PCA that has a little bit more flexibility. Just like PCA, Factor Analysis is also a model that allows reducing information in a larger number of variables into a smaller number of variables. In Factor Analysis we call those “latent variables”. Factor Analysis tries to find latent variables that make sense to us. We can rotate the solution until we find latent variables that have a clear interpretation and “make sense”. Factor Analysis is based on a model called the common factor model. It starts from the principle that there a certain number of factors in a data set, and that each of the measured variables captures a part of one or more of those factors. An example of Factor Analysis is given in the following schema. Imagine many students in a school. They all get grades for many subject matters. We could imagine that these different grades are partly correlated: a more intellectually gifted student would have higher grades overall. This would be an example of a latent variable. But we could also imagine having students who are overall good in languages, but bad in technical subjects. In this case, we could try to find a latent variable for language ability and a second latent variable for technical ability. We now have latent variables that measure the general ability of a student for Language and Technical subjects. But it would still be possible that some students are great at languages overall, but that they are just bad at German. This is why the Common Factor Model has specific factors: they measure the impact of one specific measured variable on the measured variable. We could describe it as “Ability for learning German while taking into account the general ability for learning languages”. As said, the mathematical model in Factor Analysis is much more conceptual than the PCA model. Where the PCA model is more of a pragmatic approach, in Factor Analysis we are hypothesizing that latent variables exist. In a case with two latent variables, we can compute our original variables X by attributing one part of its variation to our first common latent variable (let’s call it k1), part to the second common latent variable (k2), and part to a specific factor (specific to this variable; called d). In a case with 4 original variables, the Factor Analysis model would be as follows: X1 = c11 * k1 + c12 * k2 + d1X2 = c21 * k1 + c22 * k2 + d2X3 = c31 * k1 + c32 * k2 + d3X4 = c41 * k1 + c42 * k2 + d4 c are each coefficient of the coefficient matrix, which are the values that we need to estimate. To solve this, the same mathematical solution as in PCA is used, except for a small difference. In PCA we apply matrix decomposition to the correlation matrix. In Factor Analysis, we apply matrix decomposition to a correlation matrix in which the diagonal entries are replaced by 1 — var(d), one minus the variance of the specific factor of the variable. So in short, the mathematical difference between PCA and Factor Analysis is the use of specific factors for each original variable. Let’s get back to the example with students in a school who take 4 exams: two languages exams and two technical exams. We expect two underlying factors: language ability and technical ability. PCA does not estimate specific effects, so it simply finds the mathematical definition of the “best” components (components who maximize variance). Those could be a component for language ability and a component for technical ability, but it also could be something else. Factor Analysis will also estimate the components, but we now call them common factors. Besides that, it also estimates the specific factors. It will therefore give us two common factors (language and technical) and four specific factors (abilities on test 1, test 2, test 3, and test 4 that are unexplained by language or technical ability). Even though we don’t really care for the specific factors, the fact that they have been estimated gives us a different definition of the common factors / components. Resulting from this mathematical difference, we have also a big difference between the application of PCA and Factor Analysis. In PCA, there is one fixed outcome that orders the components from the highest explanatory value to the lowest explanatory value. In Factor Analysis, we can apply rotations to our solution, which will allow for finding a solution that has a more coherent business explication to each of the factors that was identified. The possibility to apply rotation to a Factor Analysis makes it a great tool for treating multivariate questionnaire studies in marketing and psychology. The fact that Factor Analysis is much more flexible for interpretation makes it a great tool for exploration and interpretation. Two examples: In marketing: resume product evaluation questionnaire with many questions in a few latent factors for product improvement. In psychology: reduce very long personality test responses into a small number of personality traits. PCA allows us to find the components that contain the maximum amount of information in fewer variables. This makes it a great tool for dimension reduction. PCA on the other hand is used in cases where we want to retain the largest amount of variation in the smallest number of variables possible. This can for example be used to simplify further analysis. PCA is also much used in data preparation for Machine Learning tasks, where we want to help the Machine Learning model by already “summarising” the data in an easier to digest form. To get started with PCA and Factor Analysis in Python or R, here are a few quick pointers to useful libraries that you will need. The implementations of PCA are as good in Python as in R. However, Factor Analysis is not yet very mature in Scikit Learn and it may be useful to check out the R alternative. To get started with PCA in Python, you can use the PCA function from sklearn.decomposition. It can be used as follows: from sklearn.decomposition import PCAfrom sklearn import datasetsiris = datasets.load_iris()X = iris.datamy_pca = PCA(n_components=2)my_pca.fit(X)print(my_pca.explained_variance_ratio_)print(my_pca.singular_values_) To get started with Factor Analysis in Python, you can use the FactorAnalysis function from sklearn.decomposition. In version 0.23 of scikit-learn, rotation is not yet available. But varimax rotation will soon be available and is already available in the nightly build of version 0.24. It can be used as follows: from sklearn.decomposition import FactorAnalysisfrom sklearn import datasetsiris = datasets.load_iris()X = iris.datamy_fa = FactorAnalysis(n_components=2)# in new version of sklearn:# my_fa = FactorAnalysis(n_components=2, rotation='varimax') X_transformed = my_fa.fit_transform(X) In R, there are multiple implementation of PCA available, but prcompis a good option. It can be used as follows: data(iris)iris_data <- iris[, 1:4] my_pca <- prcomp(iris_data, center = TRUE, scale = TRUE)print(my_pca) Factor Analysis is much more developed in the R Psych package when compared to the Scikit Learn implementation. It can be used as follows: install.packages(“psych”)library(psych)data(iris)iris_data <- iris[, 1:4]iris_cor <- cor(iris)my_fa <- fa(r = iris_cor, nfactors = 2)print(my_fa)# or the alternative with varimax rotation:my_fa <- factor.pa(iris, nfactors=3, rotation="varimax")print(my_fa)# or the alternative with proimax rotationmy_fa <- factor.pa(iris, nfactors=3, rotation="promax")print(my_fa) Another great R library for PCA and Factor Analyis is FactoMineR. It has a really large range of additional options for going further in Multivariate Statistics. So in conclusion, we observe the difference between PCA and Factor Analysis in three points: Firstly, the goal is different. PCA has as a goal to define new variables based on the highest variance explained and so forth. FA has as a goal to define new variables that we can understand and interpret in a business / practical manner. Then as a consequence, the mathematics behind the two methods are, while close to each other, not exactly the same. Although both methods use decomposition, they differ in the details. This also causes the fact that Factor Analysis has an additional possibility for rotation of the final solution, while PCA does not. As Factor Analysis is more flexible for interpretation, due to the possibility of rotation of the solution, it is very valuable in studies for marketing and psychology. PCA’s advantage is that it allows for dimension reduction while still keeping a maximum amount of information in a data set. This is often used to simplify exploratory analyses or to prepare data for Machine Learning pipelines. I hope this article has been useful to you. Thanks for reading and don’t hesitate to stay tuned for more!
[ { "code": null, "e": 336, "s": 171, "text": "PCA, short for Principal Component Analysis, and Factor Analysis, are two statistical methods that are often covered together in classes on Multivariate Statistics." }, { "code": null, "e": 439, "s": 336, "text": "In this article, you will discover the mathematical and practical differences between the two methods." }, { "code": null, "e": 617, "s": 439, "text": "Multivariate Statistics is a group of statistical methods that focus on studying multiple variables together while focusing on the variation that those variables have in common." }, { "code": null, "e": 714, "s": 617, "text": "Multivariate Statistics deals with the treatment of data sets with a large number of dimensions." }, { "code": null, "e": 834, "s": 714, "text": "Its goals are therefore different from supervised modeling, but also different from segmentation and clustering models." }, { "code": null, "e": 1018, "s": 834, "text": "There are many models in the family of Multivariate Statistics. In this article, I will focus on the difference between PCA and Factor Analysis, two commonly used Multivariate models." }, { "code": null, "e": 1245, "s": 1018, "text": "Modern datasets often have a very large number of variables. This makes it difficult to inspect each of the variables individually, due to the practical fact that the human mind cannot easily digest data on such a large scale." }, { "code": null, "e": 1366, "s": 1245, "text": "When a dataset contains a large number of variables, there is often a serious amount of overlap between those variables." }, { "code": null, "e": 1487, "s": 1366, "text": "The components that are found by PCA are ordered from the highest information content to the lowest information content." }, { "code": null, "e": 1695, "s": 1487, "text": "PCA is a statistical method that allows you to “regroup” your variables into a smaller number of variables, called components. This regrouping is done based on variation that is common to multiple variables." }, { "code": null, "e": 1974, "s": 1695, "text": "The goal of PCA is to regroup variables in such a way that the first (newly created) component contains a maximum of variation. The second component contains the second-largest amount of variation, etc etc. The last component logically contains the smallest amount of variation." }, { "code": null, "e": 2228, "s": 1974, "text": "Thanks to this ordering of components, it is made possible to retain only a few of the newly created components, while still retaining a maximum amount of variation. We can then use the components rather than the original variables for data exploration." }, { "code": null, "e": 2356, "s": 2228, "text": "The mathematical definition of the PCA problem is to find a linear combination of the original variables with maximum variance." }, { "code": null, "e": 2572, "s": 2356, "text": "This means that we are going to create a (new) component. Let’s call it z. This z is going to be computed based on our original variables (X1, X2, ...) multiplied by a weight for each of our variables (u1, u2, ...)." }, { "code": null, "e": 2603, "s": 2572, "text": "This can be written as z = Xu." }, { "code": null, "e": 2895, "s": 2603, "text": "The mathematical goal is to find the values for u that will maximize the variance of z, with a constraint of unit length on u. This problem is mathematically called a constrained optimization using Lagrange Multiplier, but in practice, we use computers to do the whole PCA operation at once." }, { "code": null, "e": 3008, "s": 2895, "text": "This can also be described as applying matrix decomposition to the correlation matrix of the original variables." }, { "code": null, "e": 3183, "s": 3008, "text": "PCA is efficient in finding the components that maximize variance. This is great if we are interested in reducing the number of variables while keeping a maximum of variance." }, { "code": null, "e": 3507, "s": 3183, "text": "Sometimes, however, we are not purely interested in maximizating variance: we might want to give the most useful interpretations to our newly defined dimensions. And this is not always easiest with the solution found by a PCA. We can then apply Factor Analysis: an alternative to PCA that has a little bit more flexibility." }, { "code": null, "e": 3708, "s": 3507, "text": "Just like PCA, Factor Analysis is also a model that allows reducing information in a larger number of variables into a smaller number of variables. In Factor Analysis we call those “latent variables”." }, { "code": null, "e": 3887, "s": 3708, "text": "Factor Analysis tries to find latent variables that make sense to us. We can rotate the solution until we find latent variables that have a clear interpretation and “make sense”." }, { "code": null, "e": 4127, "s": 3887, "text": "Factor Analysis is based on a model called the common factor model. It starts from the principle that there a certain number of factors in a data set, and that each of the measured variables captures a part of one or more of those factors." }, { "code": null, "e": 4458, "s": 4127, "text": "An example of Factor Analysis is given in the following schema. Imagine many students in a school. They all get grades for many subject matters. We could imagine that these different grades are partly correlated: a more intellectually gifted student would have higher grades overall. This would be an example of a latent variable." }, { "code": null, "e": 4692, "s": 4458, "text": "But we could also imagine having students who are overall good in languages, but bad in technical subjects. In this case, we could try to find a latent variable for language ability and a second latent variable for technical ability." }, { "code": null, "e": 5190, "s": 4692, "text": "We now have latent variables that measure the general ability of a student for Language and Technical subjects. But it would still be possible that some students are great at languages overall, but that they are just bad at German. This is why the Common Factor Model has specific factors: they measure the impact of one specific measured variable on the measured variable. We could describe it as “Ability for learning German while taking into account the general ability for learning languages”." }, { "code": null, "e": 5407, "s": 5190, "text": "As said, the mathematical model in Factor Analysis is much more conceptual than the PCA model. Where the PCA model is more of a pragmatic approach, in Factor Analysis we are hypothesizing that latent variables exist." }, { "code": null, "e": 5698, "s": 5407, "text": "In a case with two latent variables, we can compute our original variables X by attributing one part of its variation to our first common latent variable (let’s call it k1), part to the second common latent variable (k2), and part to a specific factor (specific to this variable; called d)." }, { "code": null, "e": 5782, "s": 5698, "text": "In a case with 4 original variables, the Factor Analysis model would be as follows:" }, { "code": null, "e": 5899, "s": 5782, "text": "X1 = c11 * k1 + c12 * k2 + d1X2 = c21 * k1 + c22 * k2 + d2X3 = c31 * k1 + c32 * k2 + d3X4 = c41 * k1 + c42 * k2 + d4" }, { "code": null, "e": 5996, "s": 5899, "text": "c are each coefficient of the coefficient matrix, which are the values that we need to estimate." }, { "code": null, "e": 6351, "s": 5996, "text": "To solve this, the same mathematical solution as in PCA is used, except for a small difference. In PCA we apply matrix decomposition to the correlation matrix. In Factor Analysis, we apply matrix decomposition to a correlation matrix in which the diagonal entries are replaced by 1 — var(d), one minus the variance of the specific factor of the variable." }, { "code": null, "e": 6483, "s": 6351, "text": "So in short, the mathematical difference between PCA and Factor Analysis is the use of specific factors for each original variable." }, { "code": null, "e": 6676, "s": 6483, "text": "Let’s get back to the example with students in a school who take 4 exams: two languages exams and two technical exams. We expect two underlying factors: language ability and technical ability." }, { "code": null, "e": 6948, "s": 6676, "text": "PCA does not estimate specific effects, so it simply finds the mathematical definition of the “best” components (components who maximize variance). Those could be a component for language ability and a component for technical ability, but it also could be something else." }, { "code": null, "e": 7291, "s": 6948, "text": "Factor Analysis will also estimate the components, but we now call them common factors. Besides that, it also estimates the specific factors. It will therefore give us two common factors (language and technical) and four specific factors (abilities on test 1, test 2, test 3, and test 4 that are unexplained by language or technical ability)." }, { "code": null, "e": 7457, "s": 7291, "text": "Even though we don’t really care for the specific factors, the fact that they have been estimated gives us a different definition of the common factors / components." }, { "code": null, "e": 7714, "s": 7457, "text": "Resulting from this mathematical difference, we have also a big difference between the application of PCA and Factor Analysis. In PCA, there is one fixed outcome that orders the components from the highest explanatory value to the lowest explanatory value." }, { "code": null, "e": 7904, "s": 7714, "text": "In Factor Analysis, we can apply rotations to our solution, which will allow for finding a solution that has a more coherent business explication to each of the factors that was identified." }, { "code": null, "e": 8058, "s": 7904, "text": "The possibility to apply rotation to a Factor Analysis makes it a great tool for treating multivariate questionnaire studies in marketing and psychology." }, { "code": null, "e": 8201, "s": 8058, "text": "The fact that Factor Analysis is much more flexible for interpretation makes it a great tool for exploration and interpretation. Two examples:" }, { "code": null, "e": 8324, "s": 8201, "text": "In marketing: resume product evaluation questionnaire with many questions in a few latent factors for product improvement." }, { "code": null, "e": 8426, "s": 8324, "text": "In psychology: reduce very long personality test responses into a small number of personality traits." }, { "code": null, "e": 8582, "s": 8426, "text": "PCA allows us to find the components that contain the maximum amount of information in fewer variables. This makes it a great tool for dimension reduction." }, { "code": null, "e": 8964, "s": 8582, "text": "PCA on the other hand is used in cases where we want to retain the largest amount of variation in the smallest number of variables possible. This can for example be used to simplify further analysis. PCA is also much used in data preparation for Machine Learning tasks, where we want to help the Machine Learning model by already “summarising” the data in an easier to digest form." }, { "code": null, "e": 9269, "s": 8964, "text": "To get started with PCA and Factor Analysis in Python or R, here are a few quick pointers to useful libraries that you will need. The implementations of PCA are as good in Python as in R. However, Factor Analysis is not yet very mature in Scikit Learn and it may be useful to check out the R alternative." }, { "code": null, "e": 9361, "s": 9269, "text": "To get started with PCA in Python, you can use the PCA function from sklearn.decomposition." }, { "code": null, "e": 9388, "s": 9361, "text": "It can be used as follows:" }, { "code": null, "e": 9604, "s": 9388, "text": "from sklearn.decomposition import PCAfrom sklearn import datasetsiris = datasets.load_iris()X = iris.datamy_pca = PCA(n_components=2)my_pca.fit(X)print(my_pca.explained_variance_ratio_)print(my_pca.singular_values_)" }, { "code": null, "e": 9719, "s": 9604, "text": "To get started with Factor Analysis in Python, you can use the FactorAnalysis function from sklearn.decomposition." }, { "code": null, "e": 9890, "s": 9719, "text": "In version 0.23 of scikit-learn, rotation is not yet available. But varimax rotation will soon be available and is already available in the nightly build of version 0.24." }, { "code": null, "e": 9917, "s": 9890, "text": "It can be used as follows:" }, { "code": null, "e": 10199, "s": 9917, "text": "from sklearn.decomposition import FactorAnalysisfrom sklearn import datasetsiris = datasets.load_iris()X = iris.datamy_fa = FactorAnalysis(n_components=2)# in new version of sklearn:# my_fa = FactorAnalysis(n_components=2, rotation='varimax') X_transformed = my_fa.fit_transform(X)" }, { "code": null, "e": 10312, "s": 10199, "text": "In R, there are multiple implementation of PCA available, but prcompis a good option. It can be used as follows:" }, { "code": null, "e": 10417, "s": 10312, "text": "data(iris)iris_data <- iris[, 1:4] my_pca <- prcomp(iris_data, center = TRUE, scale = TRUE)print(my_pca)" }, { "code": null, "e": 10556, "s": 10417, "text": "Factor Analysis is much more developed in the R Psych package when compared to the Scikit Learn implementation. It can be used as follows:" }, { "code": null, "e": 10922, "s": 10556, "text": "install.packages(“psych”)library(psych)data(iris)iris_data <- iris[, 1:4]iris_cor <- cor(iris)my_fa <- fa(r = iris_cor, nfactors = 2)print(my_fa)# or the alternative with varimax rotation:my_fa <- factor.pa(iris, nfactors=3, rotation=\"varimax\")print(my_fa)# or the alternative with proimax rotationmy_fa <- factor.pa(iris, nfactors=3, rotation=\"promax\")print(my_fa)" }, { "code": null, "e": 11084, "s": 10922, "text": "Another great R library for PCA and Factor Analyis is FactoMineR. It has a really large range of additional options for going further in Multivariate Statistics." }, { "code": null, "e": 11177, "s": 11084, "text": "So in conclusion, we observe the difference between PCA and Factor Analysis in three points:" }, { "code": null, "e": 11305, "s": 11177, "text": "Firstly, the goal is different. PCA has as a goal to define new variables based on the highest variance explained and so forth." }, { "code": null, "e": 11417, "s": 11305, "text": "FA has as a goal to define new variables that we can understand and interpret in a business / practical manner." }, { "code": null, "e": 11602, "s": 11417, "text": "Then as a consequence, the mathematics behind the two methods are, while close to each other, not exactly the same. Although both methods use decomposition, they differ in the details." }, { "code": null, "e": 11735, "s": 11602, "text": "This also causes the fact that Factor Analysis has an additional possibility for rotation of the final solution, while PCA does not." }, { "code": null, "e": 11904, "s": 11735, "text": "As Factor Analysis is more flexible for interpretation, due to the possibility of rotation of the solution, it is very valuable in studies for marketing and psychology." }, { "code": null, "e": 12132, "s": 11904, "text": "PCA’s advantage is that it allows for dimension reduction while still keeping a maximum amount of information in a data set. This is often used to simplify exploratory analyses or to prepare data for Machine Learning pipelines." } ]
Reduced-Rank Vector Autoregressive Model for High-Dimensional Time Series Forecasting | by Xinyu Chen (陈新宇) | Towards Data Science
Nowadays, with the remarkable development of data collection/availability techniques, we have more opportunities to approach many kinds of time series data in a lot of scientific and industrial fields. There are many types of time series data, including univariate time series, multivariate time series, and multidimensional time series. For multivariate time series, the data has more than one time-dependent variable, and each variable has dependencies on other variables. Therefore, vector autoregressive (VAR) model is a classical approach for multivariate time series analysis mainly due to its ability for identifying co-evolution patterns of the time-dependent variables. However, there is a special case that if we have a large amount of variables (e.g., thousands or millions of variables) but only have a limited number of time steps, then the multivariate time series would be high-dimensional. For instance, Figure 1 shows an intuitive illustration of the VAR model for high-dimensional time series data. Here, the high-dimensional time series data are represented as “tall-skinny” matrices. In this simple illustration, it is not difficult to see that there are many parameters in the coefficient matrix, exceeding the number of time series observations. In most cases, this VAR model is ill-posed because it would suffer from the over-parameterization issue. To address this issue in VAR, one important direction is developing the reduced-rank VAR model parameterized by matrix factorization. In this blog post, we introduce a reduced-rank VAR model for multivariate time series analysis. The model is proposed by Velu, Reinsel, and Wichern in 1986 [1]. Before this art, Velu also discussed the estimation of certain reduced-rank autoregressive models in his unpublished PhD thesis at University of Wisconsin. Later in 1998, Velu and Reinsel published the book “Multivariate Reduced-Rank Regression: Theory and Applications” [2]. Although the reduced-rank VAR has a long history, the paper did not attract a lot of attention in the past few decades. As we have many kinds of high-dimensional time series data, many high-dimensional VAR models actually hold a similar idea as reduced-rank VAR. This post is not limited to the content of the most previous reduced-rank VAR paper. We also provide a simple model description of the reduced-rank VAR model and give a toy example to illustrate its applications. In addition, we reproduce the model in Python, particularly with the Numpy package. Figure 1 shows the basic idea of VAR. Given a time series data X of size N-by-T where N is the number of variables and T is the number of time steps, then in any time step t, the first-order VAR, or VAR(1), takes the form of where xt denotes the snapshot vector in time t and the size is N-by-1. A is the coefficient matrix, and it is of size N-by-N. To address the over-parameterization issue in VAR, we can assume that the coefficient matrix A has a reduced rank, and define two matrices W (of size N-by-R) and V (of size R-by-N) such that A=WV where the coefficient matrix is reparameterized by a matrix factorization. In this case, it leads to a reduced-rank VAR model as shown in Figure 2. It is obvious that if we impose a suitable reduced rank R, parameters in the component matrices W and V would be less than the parameters in the coefficient matrix A. This in fact provides a technical path for addressing the over-parameterization issue of VAR in the high-dimensional time series data. From a machine learning perspective, to estimate the parameters in the reduced-rank VAR model, we can formulate the autoregression errors as a L2-norm loss function: For this optimization problem, we can obtain the closed-form solutions to W and V in the form of vector. However, the vector form is not the best choice for developing an algorithm. Here, we take into account a new optimization problem: where we define and the closed-form solutions to W and V are now given by Since the closed-form solution to W involves V, and the closed-form solution to V involves W, we can use an Alternating Minimization scheme. For the least squares solutions, the algorithm is actually Alternating Least Squares (ALS). There are only three main steps of this iterative algorithm: Initialize W and V with random values. Iterative step 1: Update W by the least squares solution as mentioned above. Iterative step 2: Update V by the least squares solution as mentioned above. We can define a function for the reduced-rank VAR model in Python. import numpy as npdef rrvar(data, R, pred_step, maxiter = 100): """Reduced-rank VAR algorithm.""" N, T = data.shape X1 = data[:, : -1] X2 = data[:, 1 :] V = np.random.randn(R, N) for it in range(maxiter): W = X2 @ np.linalg.pinv(V @ X1) V = np.linalg.pinv(W) @ X2 @ np.linalg.pinv(X1) mat = np.append(data, np.zeros((N, pred_step)), axis = 1) for s in range(pred_step): mat[:, T + s] = W @ V @ mat[:, T + s - 1] return mat[:, - pred_step :] This is a reduced-rank VAR algorithm where we have inputs like multivariate time series data and reduced rank. We evaluate the algorithm by considering the following example: The example data is of size 20-by-10, and this is a “tall-skinny” data. We will try to set the reduced rank as 2 and test the algorithm. Write the code in Python: X = np.zeros((20, 10))for i in range(20): X[i, :] = np.arange(i + 1, i + 11)pred_step = 2R = 2mat_hat = rrvar(X, R, pred_step)print(mat_hat) The results are: [[11. 12.] [12. 13.] [13. 14.] [14. 15.] [15. 16.] [16. 17.] [17. 18.] [18. 19.] [19. 20.] [20. 21.] [21. 22.] [22. 23.] [23. 24.] [24. 25.] [25. 26.] [26. 27.] [27. 28.] [28. 29.] [29. 30.] [30. 31.]] The results are completely same as the ground truth data. Reduced-rank VAR is an important time series forecasting approach in the case of high-dimensional data. It have many advantages like compressing the coefficients and solving the over-parameterization issue in VAR. Despite the matrix factorization tool in the reduced-rank VAR, there are also some other tools like tensor factorization. Relying on this post, it is not hard to extend the reduced-rank VAR model with a higher order. [1] Velu, R. P., Reinsel, G. C., & Wichern, D. W. (1986). Reduced rank models for multiple time series. Biometrika, 73(1), 105–118. [2] Velu, R., & Reinsel, G. C. (1998). Multivariate reduced-rank regression: theory and applications. Springer Science & Business Media. [3] Xinyu Chen (2021). Matrix Autoregressive Model for Multidimensional Time Series Forecasting. Medium. Website: https://towardsdatascience.com/matrix-autoregressive-model-for-multidimensional-time-series-forecasting-6a4d7dce5143
[ { "code": null, "e": 851, "s": 172, "text": "Nowadays, with the remarkable development of data collection/availability techniques, we have more opportunities to approach many kinds of time series data in a lot of scientific and industrial fields. There are many types of time series data, including univariate time series, multivariate time series, and multidimensional time series. For multivariate time series, the data has more than one time-dependent variable, and each variable has dependencies on other variables. Therefore, vector autoregressive (VAR) model is a classical approach for multivariate time series analysis mainly due to its ability for identifying co-evolution patterns of the time-dependent variables." }, { "code": null, "e": 1276, "s": 851, "text": "However, there is a special case that if we have a large amount of variables (e.g., thousands or millions of variables) but only have a limited number of time steps, then the multivariate time series would be high-dimensional. For instance, Figure 1 shows an intuitive illustration of the VAR model for high-dimensional time series data. Here, the high-dimensional time series data are represented as “tall-skinny” matrices." }, { "code": null, "e": 1679, "s": 1276, "text": "In this simple illustration, it is not difficult to see that there are many parameters in the coefficient matrix, exceeding the number of time series observations. In most cases, this VAR model is ill-posed because it would suffer from the over-parameterization issue. To address this issue in VAR, one important direction is developing the reduced-rank VAR model parameterized by matrix factorization." }, { "code": null, "e": 2116, "s": 1679, "text": "In this blog post, we introduce a reduced-rank VAR model for multivariate time series analysis. The model is proposed by Velu, Reinsel, and Wichern in 1986 [1]. Before this art, Velu also discussed the estimation of certain reduced-rank autoregressive models in his unpublished PhD thesis at University of Wisconsin. Later in 1998, Velu and Reinsel published the book “Multivariate Reduced-Rank Regression: Theory and Applications” [2]." }, { "code": null, "e": 2379, "s": 2116, "text": "Although the reduced-rank VAR has a long history, the paper did not attract a lot of attention in the past few decades. As we have many kinds of high-dimensional time series data, many high-dimensional VAR models actually hold a similar idea as reduced-rank VAR." }, { "code": null, "e": 2676, "s": 2379, "text": "This post is not limited to the content of the most previous reduced-rank VAR paper. We also provide a simple model description of the reduced-rank VAR model and give a toy example to illustrate its applications. In addition, we reproduce the model in Python, particularly with the Numpy package." }, { "code": null, "e": 2901, "s": 2676, "text": "Figure 1 shows the basic idea of VAR. Given a time series data X of size N-by-T where N is the number of variables and T is the number of time steps, then in any time step t, the first-order VAR, or VAR(1), takes the form of" }, { "code": null, "e": 3027, "s": 2901, "text": "where xt denotes the snapshot vector in time t and the size is N-by-1. A is the coefficient matrix, and it is of size N-by-N." }, { "code": null, "e": 3218, "s": 3027, "text": "To address the over-parameterization issue in VAR, we can assume that the coefficient matrix A has a reduced rank, and define two matrices W (of size N-by-R) and V (of size R-by-N) such that" }, { "code": null, "e": 3223, "s": 3218, "text": "A=WV" }, { "code": null, "e": 3673, "s": 3223, "text": "where the coefficient matrix is reparameterized by a matrix factorization. In this case, it leads to a reduced-rank VAR model as shown in Figure 2. It is obvious that if we impose a suitable reduced rank R, parameters in the component matrices W and V would be less than the parameters in the coefficient matrix A. This in fact provides a technical path for addressing the over-parameterization issue of VAR in the high-dimensional time series data." }, { "code": null, "e": 3839, "s": 3673, "text": "From a machine learning perspective, to estimate the parameters in the reduced-rank VAR model, we can formulate the autoregression errors as a L2-norm loss function:" }, { "code": null, "e": 4076, "s": 3839, "text": "For this optimization problem, we can obtain the closed-form solutions to W and V in the form of vector. However, the vector form is not the best choice for developing an algorithm. Here, we take into account a new optimization problem:" }, { "code": null, "e": 4092, "s": 4076, "text": "where we define" }, { "code": null, "e": 4150, "s": 4092, "text": "and the closed-form solutions to W and V are now given by" }, { "code": null, "e": 4444, "s": 4150, "text": "Since the closed-form solution to W involves V, and the closed-form solution to V involves W, we can use an Alternating Minimization scheme. For the least squares solutions, the algorithm is actually Alternating Least Squares (ALS). There are only three main steps of this iterative algorithm:" }, { "code": null, "e": 4483, "s": 4444, "text": "Initialize W and V with random values." }, { "code": null, "e": 4560, "s": 4483, "text": "Iterative step 1: Update W by the least squares solution as mentioned above." }, { "code": null, "e": 4637, "s": 4560, "text": "Iterative step 2: Update V by the least squares solution as mentioned above." }, { "code": null, "e": 4704, "s": 4637, "text": "We can define a function for the reduced-rank VAR model in Python." }, { "code": null, "e": 5197, "s": 4704, "text": "import numpy as npdef rrvar(data, R, pred_step, maxiter = 100): \"\"\"Reduced-rank VAR algorithm.\"\"\" N, T = data.shape X1 = data[:, : -1] X2 = data[:, 1 :] V = np.random.randn(R, N) for it in range(maxiter): W = X2 @ np.linalg.pinv(V @ X1) V = np.linalg.pinv(W) @ X2 @ np.linalg.pinv(X1) mat = np.append(data, np.zeros((N, pred_step)), axis = 1) for s in range(pred_step): mat[:, T + s] = W @ V @ mat[:, T + s - 1] return mat[:, - pred_step :]" }, { "code": null, "e": 5308, "s": 5197, "text": "This is a reduced-rank VAR algorithm where we have inputs like multivariate time series data and reduced rank." }, { "code": null, "e": 5372, "s": 5308, "text": "We evaluate the algorithm by considering the following example:" }, { "code": null, "e": 5509, "s": 5372, "text": "The example data is of size 20-by-10, and this is a “tall-skinny” data. We will try to set the reduced rank as 2 and test the algorithm." }, { "code": null, "e": 5535, "s": 5509, "text": "Write the code in Python:" }, { "code": null, "e": 5679, "s": 5535, "text": "X = np.zeros((20, 10))for i in range(20): X[i, :] = np.arange(i + 1, i + 11)pred_step = 2R = 2mat_hat = rrvar(X, R, pred_step)print(mat_hat)" }, { "code": null, "e": 5696, "s": 5679, "text": "The results are:" }, { "code": null, "e": 5898, "s": 5696, "text": "[[11. 12.] [12. 13.] [13. 14.] [14. 15.] [15. 16.] [16. 17.] [17. 18.] [18. 19.] [19. 20.] [20. 21.] [21. 22.] [22. 23.] [23. 24.] [24. 25.] [25. 26.] [26. 27.] [27. 28.] [28. 29.] [29. 30.] [30. 31.]]" }, { "code": null, "e": 5956, "s": 5898, "text": "The results are completely same as the ground truth data." }, { "code": null, "e": 6387, "s": 5956, "text": "Reduced-rank VAR is an important time series forecasting approach in the case of high-dimensional data. It have many advantages like compressing the coefficients and solving the over-parameterization issue in VAR. Despite the matrix factorization tool in the reduced-rank VAR, there are also some other tools like tensor factorization. Relying on this post, it is not hard to extend the reduced-rank VAR model with a higher order." }, { "code": null, "e": 6519, "s": 6387, "text": "[1] Velu, R. P., Reinsel, G. C., & Wichern, D. W. (1986). Reduced rank models for multiple time series. Biometrika, 73(1), 105–118." }, { "code": null, "e": 6656, "s": 6519, "text": "[2] Velu, R., & Reinsel, G. C. (1998). Multivariate reduced-rank regression: theory and applications. Springer Science & Business Media." } ]
Accessing a parent Element using JavaScript
Following is the code for accessing a parent element using JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: #8a2be2; } .parent1, .parent2, .parent3 { display: inline-block; margin: 10px; } .child1, .child2, .child3 { width: 70px; height: 70px; } .child1 { background-color: red; } .child2 { background-color: pink; } .child3 { background-color: blue; } </style> </head> <body> <h1>Accessing a parent Element using JavaScript</h1> <div class="parent1"> <div class="child1">Child 1</div> </div> <div class="parent2"> <div class="child2">Child 2</div> </div> <div class="parent3"> <div class="child3">Child 3</div> </div> <br /> <div class="result"></div> <h3>Click on the any of the above div to know its parent element</h3> <script> let resEle = document.querySelector(".result"); document.querySelector(".child3").addEventListener("click", (event) => { resEle.innerHTML = "The parent node is " + event.target.parentNode.className; }); document.querySelector(".child1").addEventListener("click", (event) => { resEle.innerHTML = "The parent node is " + event.target.parentNode.className; }); document.querySelector(".child2").addEventListener("click", (event) => { resEle.innerHTML = "The parent node is " + event.target.parentNode.className; }); </script> </body> </html> On clicking any of the divs, the following output will be produced −
[ { "code": null, "e": 1134, "s": 1062, "text": "Following is the code for accessing a parent element using JavaScript −" }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 2778, "s": 1145, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: #8a2be2;\n }\n .parent1,\n .parent2,\n .parent3 {\n display: inline-block;\n margin: 10px;\n }\n .child1,\n .child2,\n .child3 {\n width: 70px;\n height: 70px;\n }\n .child1 {\n background-color: red;\n }\n .child2 {\n background-color: pink;\n }\n .child3 {\n background-color: blue;\n }\n</style>\n</head>\n<body>\n<h1>Accessing a parent Element using JavaScript</h1>\n<div class=\"parent1\">\n<div class=\"child1\">Child 1</div>\n</div>\n<div class=\"parent2\">\n<div class=\"child2\">Child 2</div>\n</div>\n<div class=\"parent3\">\n<div class=\"child3\">Child 3</div>\n</div>\n<br />\n<div class=\"result\"></div>\n<h3>Click on the any of the above div to know its parent element</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".child3\").addEventListener(\"click\", (event) => {\n resEle.innerHTML =\n \"The parent node is \" + event.target.parentNode.className;\n });\n document.querySelector(\".child1\").addEventListener(\"click\", (event) => {\n resEle.innerHTML =\n \"The parent node is \" + event.target.parentNode.className;\n });\n document.querySelector(\".child2\").addEventListener(\"click\", (event) => {\n resEle.innerHTML =\n \"The parent node is \" + event.target.parentNode.className;\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2847, "s": 2778, "text": "On clicking any of the divs, the following output will be produced −" } ]
Python program to sort and find the data in the student records
29 May, 2021 Consider a software for maintaining records of the students in a class. Consider the following functions which are required to be performed: Sorting of names according to First Name of the students.Finding the Minimum marks among all the marksFinding contact number of student using his/her First Name. Sorting of names according to First Name of the students. Finding the Minimum marks among all the marks Finding contact number of student using his/her First Name. The task is to write a Python program to implement the software having these three functionalities. Approach: For the above problem we should use a dictionary that either takes a name as a whole to key and other data as value to it or vice versa. Here I have taken the name as a key and contact number, marks as the value associated with the name. So at first the user needs to enter the details of the students and these details will be stored in dictionary as {[‘first name’, ‘second name’]:(‘contact number’, ‘marks’)}. Then we create a new list of tuples that store data according to the function requirement. In the program four user-defined functions have been created: sort( ) function that sorts the record based on the first name.minmarks( ) function that finds the minimum marks from all records.searchdetail( ) function that takes first name as an input and fetch student contact number from the corresponding record.option() function for showing the options. sort( ) function that sorts the record based on the first name. minmarks( ) function that finds the minimum marks from all records. searchdetail( ) function that takes first name as an input and fetch student contact number from the corresponding record. option() function for showing the options. Below is the implementation: Python3 print("-----Program for Student Information-----") D = dict() n = int(input('How many student record you want to store?? ')) # Add student information# to the dictionaryfor i in range(0,n): x, y = input("Enter the complete name (First and last name) of student: ").split() z = input("Enter contact number: ") m = input('Enter Marks: ') D[x, y] = (z, m) # define a function for shorting# names based on first namedef sort(): ls = list() # fetch key and value using # items() method for sname,details in D.items(): # store key parts as an tuple tup = (sname[0],sname[1]) # add tuple to the list ls.append(tup) # sort the final list of tuples ls = sorted(ls) for i in ls: # print first name and second name print(i[0],i[1]) return # define a function for# finding the minimum marks# in stored datadef minmarks(): ls = list() # fetch key and value using # items() methods for sname,details in D.items(): # add details second element # (marks) to the list ls.append(details[1]) # sort the list elemnts ls = sorted(ls) print("Minimum marks: ", min(ls)) return # define a function for searching# student contact numberdef searchdetail(fname): ls = list() for sname,details in D.items(): tup=(sname,details) ls.append(tup) for i in ls: if i[0][0] == fname: print(i[1][0]) return # define a function for# asking the optionsdef option(): choice = int(input('Enter the operation detail: \n \ 1: Sorting using first name \n \ 2: Finding Minimum marks \n \ 3: Search contact number using first name: \n \ 4: Exit\n \ Option: ')) if choice == 1: # function call sort() print('Want to perform some other operation??? Y or N: ') inp = input() if inp == 'Y': option() # exit function call exit() elif choice == 2: minmarks() print('Want to perform some other operation??? Y or N: ') inp = input() if inp == 'Y': option() exit() elif choice == 3: first = input('Enter first name of student: ') searchdetail(first) print('Want to perform some other operation??? Y or N: ') inp = input() if inp == 'Y': option() exit() else: print('Thanks for executing me!!!!') exit() option() Output: -----Program for Student Information----- How many student record you want to store?? 3 Enter the complete name (First and last name) of student: shubham shukla Enter contact number: 1234567890 Enter Marks: 85 Enter the complete name (First and last name) of student: rinki singh Enter contact number: 0987654321 Enter Marks: 50 Enter the complete name (First and last name) of student: abhishek sharma Enter contact number: 5432167890 Enter Marks: 65 Enter the operation detail: 1: Sorting using first name 2: Finding Minimum marks 3: Search contact number using first name: 4: Exit Option: 1 abhishek sharma rinki singh shubham shukla Want to perform some other operation??? Y or N: Y Enter the operation detail: 1: Sorting using first name 2: Finding Minimum marks 3: Search contact number using first name: 4: Exit Option: 2 Minimum marks: 50 Want to perform some other operation??? Y or N: Y Enter the operation detail: 1: Sorting using first name 2: Finding Minimum marks 3: Search contact number using first name: 4: Exit Option: 3 Enter first name of student: rinki 0987654321 Want to perform some other operation??? Y or N: N ruhelaa48 school-programming Python Python Programs 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() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2021" }, { "code": null, "e": 195, "s": 54, "text": "Consider a software for maintaining records of the students in a class. Consider the following functions which are required to be performed:" }, { "code": null, "e": 357, "s": 195, "text": "Sorting of names according to First Name of the students.Finding the Minimum marks among all the marksFinding contact number of student using his/her First Name." }, { "code": null, "e": 415, "s": 357, "text": "Sorting of names according to First Name of the students." }, { "code": null, "e": 461, "s": 415, "text": "Finding the Minimum marks among all the marks" }, { "code": null, "e": 521, "s": 461, "text": "Finding contact number of student using his/her First Name." }, { "code": null, "e": 621, "s": 521, "text": "The task is to write a Python program to implement the software having these three functionalities." }, { "code": null, "e": 1197, "s": 621, "text": "Approach: For the above problem we should use a dictionary that either takes a name as a whole to key and other data as value to it or vice versa. Here I have taken the name as a key and contact number, marks as the value associated with the name. So at first the user needs to enter the details of the students and these details will be stored in dictionary as {[‘first name’, ‘second name’]:(‘contact number’, ‘marks’)}. Then we create a new list of tuples that store data according to the function requirement. In the program four user-defined functions have been created:" }, { "code": null, "e": 1492, "s": 1197, "text": "sort( ) function that sorts the record based on the first name.minmarks( ) function that finds the minimum marks from all records.searchdetail( ) function that takes first name as an input and fetch student contact number from the corresponding record.option() function for showing the options." }, { "code": null, "e": 1556, "s": 1492, "text": "sort( ) function that sorts the record based on the first name." }, { "code": null, "e": 1624, "s": 1556, "text": "minmarks( ) function that finds the minimum marks from all records." }, { "code": null, "e": 1747, "s": 1624, "text": "searchdetail( ) function that takes first name as an input and fetch student contact number from the corresponding record." }, { "code": null, "e": 1790, "s": 1747, "text": "option() function for showing the options." }, { "code": null, "e": 1819, "s": 1790, "text": "Below is the implementation:" }, { "code": null, "e": 1827, "s": 1819, "text": "Python3" }, { "code": "print(\"-----Program for Student Information-----\") D = dict() n = int(input('How many student record you want to store?? ')) # Add student information# to the dictionaryfor i in range(0,n): x, y = input(\"Enter the complete name (First and last name) of student: \").split() z = input(\"Enter contact number: \") m = input('Enter Marks: ') D[x, y] = (z, m) # define a function for shorting# names based on first namedef sort(): ls = list() # fetch key and value using # items() method for sname,details in D.items(): # store key parts as an tuple tup = (sname[0],sname[1]) # add tuple to the list ls.append(tup) # sort the final list of tuples ls = sorted(ls) for i in ls: # print first name and second name print(i[0],i[1]) return # define a function for# finding the minimum marks# in stored datadef minmarks(): ls = list() # fetch key and value using # items() methods for sname,details in D.items(): # add details second element # (marks) to the list ls.append(details[1]) # sort the list elemnts ls = sorted(ls) print(\"Minimum marks: \", min(ls)) return # define a function for searching# student contact numberdef searchdetail(fname): ls = list() for sname,details in D.items(): tup=(sname,details) ls.append(tup) for i in ls: if i[0][0] == fname: print(i[1][0]) return # define a function for# asking the optionsdef option(): choice = int(input('Enter the operation detail: \\n \\ 1: Sorting using first name \\n \\ 2: Finding Minimum marks \\n \\ 3: Search contact number using first name: \\n \\ 4: Exit\\n \\ Option: ')) if choice == 1: # function call sort() print('Want to perform some other operation??? Y or N: ') inp = input() if inp == 'Y': option() # exit function call exit() elif choice == 2: minmarks() print('Want to perform some other operation??? Y or N: ') inp = input() if inp == 'Y': option() exit() elif choice == 3: first = input('Enter first name of student: ') searchdetail(first) print('Want to perform some other operation??? Y or N: ') inp = input() if inp == 'Y': option() exit() else: print('Thanks for executing me!!!!') exit() option()", "e": 4424, "s": 1827, "text": null }, { "code": null, "e": 4432, "s": 4424, "text": "Output:" }, { "code": null, "e": 5658, "s": 4432, "text": "-----Program for Student Information-----\nHow many student record you want to store?? 3\nEnter the complete name (First and last name) of student: shubham shukla\nEnter contact number: 1234567890\nEnter Marks: 85\nEnter the complete name (First and last name) of student: rinki singh\nEnter contact number: 0987654321\nEnter Marks: 50\nEnter the complete name (First and last name) of student: abhishek sharma\nEnter contact number: 5432167890\nEnter Marks: 65\nEnter the operation detail: \n 1: Sorting using first name \n 2: Finding Minimum marks \n 3: Search contact number using first name: \n 4: Exit\n Option: 1\nabhishek sharma\nrinki singh\nshubham shukla\nWant to perform some other operation??? Y or N: \nY\nEnter the operation detail: \n 1: Sorting using first name \n 2: Finding Minimum marks \n 3: Search contact number using first name: \n 4: Exit\n Option: 2\nMinimum marks: 50\nWant to perform some other operation??? Y or N: \nY\nEnter the operation detail: \n 1: Sorting using first name \n 2: Finding Minimum marks \n 3: Search contact number using first name: \n 4: Exit\n Option: 3\nEnter first name of student: rinki\n0987654321\nWant to perform some other operation??? Y or N: \nN" }, { "code": null, "e": 5668, "s": 5658, "text": "ruhelaa48" }, { "code": null, "e": 5687, "s": 5668, "text": "school-programming" }, { "code": null, "e": 5694, "s": 5687, "text": "Python" }, { "code": null, "e": 5710, "s": 5694, "text": "Python Programs" }, { "code": null, "e": 5808, "s": 5710, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5826, "s": 5808, "text": "Python Dictionary" }, { "code": null, "e": 5868, "s": 5826, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5890, "s": 5868, "text": "Enumerate() in Python" }, { "code": null, "e": 5925, "s": 5890, "text": "Read a file line by line in Python" }, { "code": null, "e": 5951, "s": 5925, "text": "Python String | replace()" }, { "code": null, "e": 5994, "s": 5951, "text": "Python program to convert a list to string" }, { "code": null, "e": 6016, "s": 5994, "text": "Defaultdict in Python" }, { "code": null, "e": 6055, "s": 6016, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 6093, "s": 6055, "text": "Python | Convert a list to dictionary" } ]
How to Draw Polyline in Google Maps in Android?
24 Jan, 2021 Google Maps is used in many Android applications. While using Google Maps there are many modifications which you will get to see while using Maps in this apps. When we have used Google Maps in different apps such as OLA and Uber we will get to see lines and routes drawn on our Maps. In this article, we will take a look at drawing Polyline on Google Maps in Android. We will be building a simple application in which we will display our Map. On this map, we will display a polygon between three locations as Brisbane, Tamworth, and Newcastle. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project. Step 2: Generating an API key for using Google Maps To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. Step 3: Adding Polyline on Google Maps in Android Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.graphics.Color;import android.os.Bundle; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.PolylineOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // below are the latitude and longitude of 4 different locations. LatLng TamWorth = new LatLng(-31.083332, 150.916672); LatLng NewCastle = new LatLng(-32.916668, 151.750000); LatLng Brisbane = new LatLng(-27.470125, 153.021072); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // inside on map ready method // we will be displaying polygon on Google Maps. // on below line we will be adding polyline on Google Maps. mMap.addPolyline((new PolylineOptions()).add(Brisbane, NewCastle, TamWorth, Brisbane). // below line is use to specify the width of poly line. width(5) // below line is use to add color to our poly line. .color(Color.RED) // below line is to make our poly line geodesic. .geodesic(true)); // on below line we will be starting the drawing of polyline. googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Brisbane, 13)); }} After adding this code. Now run your app and see the output of the app. Note: In the Google Developer Console (https://console.developers.google.com), ensure that the “Google Maps Android API v2” is enabled. And also ensure that your API Key exists. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 397, "s": 28, "text": "Google Maps is used in many Android applications. While using Google Maps there are many modifications which you will get to see while using Maps in this apps. When we have used Google Maps in different apps such as OLA and Uber we will get to see lines and routes drawn on our Maps. In this article, we will take a look at drawing Polyline on Google Maps in Android. " }, { "code": null, "e": 740, "s": 397, "text": "We will be building a simple application in which we will display our Map. On this map, we will display a polygon between three locations as Brisbane, Tamworth, and Newcastle. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 769, "s": 740, "text": "Step 1: Create a New Project" }, { "code": null, "e": 995, "s": 769, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project." }, { "code": null, "e": 1047, "s": 995, "text": "Step 2: Generating an API key for using Google Maps" }, { "code": null, "e": 1405, "s": 1047, "text": "To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. " }, { "code": null, "e": 1455, "s": 1405, "text": "Step 3: Adding Polyline on Google Maps in Android" }, { "code": null, "e": 1645, "s": 1455, "text": "Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 1650, "s": 1645, "text": "Java" }, { "code": "import android.graphics.Color;import android.os.Bundle; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.PolylineOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // below are the latitude and longitude of 4 different locations. LatLng TamWorth = new LatLng(-31.083332, 150.916672); LatLng NewCastle = new LatLng(-32.916668, 151.750000); LatLng Brisbane = new LatLng(-27.470125, 153.021072); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // inside on map ready method // we will be displaying polygon on Google Maps. // on below line we will be adding polyline on Google Maps. mMap.addPolyline((new PolylineOptions()).add(Brisbane, NewCastle, TamWorth, Brisbane). // below line is use to specify the width of poly line. width(5) // below line is use to add color to our poly line. .color(Color.RED) // below line is to make our poly line geodesic. .geodesic(true)); // on below line we will be starting the drawing of polyline. googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Brisbane, 13)); }}", "e": 4202, "s": 1650, "text": null }, { "code": null, "e": 4274, "s": 4202, "text": "After adding this code. Now run your app and see the output of the app." }, { "code": null, "e": 4452, "s": 4274, "text": "Note: In the Google Developer Console (https://console.developers.google.com), ensure that the “Google Maps Android API v2” is enabled. And also ensure that your API Key exists." }, { "code": null, "e": 4460, "s": 4452, "text": "android" }, { "code": null, "e": 4484, "s": 4460, "text": "Technical Scripter 2020" }, { "code": null, "e": 4492, "s": 4484, "text": "Android" }, { "code": null, "e": 4497, "s": 4492, "text": "Java" }, { "code": null, "e": 4516, "s": 4497, "text": "Technical Scripter" }, { "code": null, "e": 4521, "s": 4516, "text": "Java" }, { "code": null, "e": 4529, "s": 4521, "text": "Android" } ]
How to flip an image horizontally or vertically in Python?
25 May, 2021 Prerequisites: PIL Given an image the task here is to generate a Python script to flip an image horizontally and vertically. Here the module used for the task is PIL and transpose() function of this module. Syntax: transpose(degree) Keywords FLIP_TOP_BOTTOM and FLIP_LEFT_RIGHT will be passed to transpose method to flip it. FLIP_TOP_BOTTOM – returns an original image flipped Vertically FLIP_LEFT_RIGHT- returns an original image flipped Horizontally Import module Open original image Transform the image as required Save the new transformed image. Image in use: Example: Flipping image vertically Python3 # importing PIL Modulefrom PIL import Image # open the original imageoriginal_img = Image.open("original.png") # Flip the original image verticallyvertical_img = original_img.transpose(method=Image.FLIP_TOP_BOTTOM)vertical_img.save("vertical.png") # close all our files objectoriginal_img.close()vertical_img.close() Output: Example : Flip image horizontally Python3 # importing PIL Modulefrom PIL import Image # open the original imageoriginal_img = Image.open("original.png") # Flip the original image horizontallyhorz_img = original_img.transpose(method=Image.FLIP_LEFT_RIGHT)horz_img.save("horizontal.png") # close all our files objectoriginal_img.close()horz_img.close() Output: simmytarika5 Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 May, 2021" }, { "code": null, "e": 47, "s": 28, "text": "Prerequisites: PIL" }, { "code": null, "e": 236, "s": 47, "text": "Given an image the task here is to generate a Python script to flip an image horizontally and vertically. Here the module used for the task is PIL and transpose() function of this module. " }, { "code": null, "e": 244, "s": 236, "text": "Syntax:" }, { "code": null, "e": 262, "s": 244, "text": "transpose(degree)" }, { "code": null, "e": 354, "s": 262, "text": "Keywords FLIP_TOP_BOTTOM and FLIP_LEFT_RIGHT will be passed to transpose method to flip it." }, { "code": null, "e": 417, "s": 354, "text": "FLIP_TOP_BOTTOM – returns an original image flipped Vertically" }, { "code": null, "e": 481, "s": 417, "text": "FLIP_LEFT_RIGHT- returns an original image flipped Horizontally" }, { "code": null, "e": 495, "s": 481, "text": "Import module" }, { "code": null, "e": 515, "s": 495, "text": "Open original image" }, { "code": null, "e": 547, "s": 515, "text": "Transform the image as required" }, { "code": null, "e": 579, "s": 547, "text": "Save the new transformed image." }, { "code": null, "e": 593, "s": 579, "text": "Image in use:" }, { "code": null, "e": 628, "s": 593, "text": "Example: Flipping image vertically" }, { "code": null, "e": 636, "s": 628, "text": "Python3" }, { "code": "# importing PIL Modulefrom PIL import Image # open the original imageoriginal_img = Image.open(\"original.png\") # Flip the original image verticallyvertical_img = original_img.transpose(method=Image.FLIP_TOP_BOTTOM)vertical_img.save(\"vertical.png\") # close all our files objectoriginal_img.close()vertical_img.close()", "e": 953, "s": 636, "text": null }, { "code": null, "e": 961, "s": 953, "text": "Output:" }, { "code": null, "e": 995, "s": 961, "text": "Example : Flip image horizontally" }, { "code": null, "e": 1003, "s": 995, "text": "Python3" }, { "code": "# importing PIL Modulefrom PIL import Image # open the original imageoriginal_img = Image.open(\"original.png\") # Flip the original image horizontallyhorz_img = original_img.transpose(method=Image.FLIP_LEFT_RIGHT)horz_img.save(\"horizontal.png\") # close all our files objectoriginal_img.close()horz_img.close()", "e": 1313, "s": 1003, "text": null }, { "code": null, "e": 1321, "s": 1313, "text": "Output:" }, { "code": null, "e": 1334, "s": 1321, "text": "simmytarika5" }, { "code": null, "e": 1341, "s": 1334, "text": "Picked" }, { "code": null, "e": 1352, "s": 1341, "text": "Python-pil" }, { "code": null, "e": 1359, "s": 1352, "text": "Python" } ]
Java Program to Solve Set Cover Problem
12 Jul, 2022 Problem Statement: Given a set of elements 1 to n and a set S of n sets whose union equals everything, the problem is to find the minimum numbers of subsets equal the set in a pair of 2. Concept: This problem is to solve the set problems. We can use permutations and combinations to solve this problem. Illustration: Input: All Possible Combination = {{1,2}, {3,4}, {8,9}, {10,7}, {5,8}, {11,6}, {4,5}, {6,7}, {10,11},} Numbers = {1,2,3,4,5,6,7,8,9,10,11} Output: The short combination was : [[1, 2], [3, 4], [8, 9], [10, 7], [5, 8], [11, 6]] Input: All Possible Combination = {{1,2}, {3,4}, {2,7}, {5,3}, {4,5}, {6,7}, } Numbers = {1,2,3,4,5,6,7} Output: The short combination was : [[1, 2], [3, 4], [5, 3], [6, 7]] Approach: At first, we give the possible sets and numbers of combinations as input in an array.Create a list and store all of them.Taking a Set and store the solution in that set.Call the shortest combo functionThis function takes a set as input and throws an exception if size greater than 20Iterates the size of all possible combinations and the new SetIt then right shifts the value and then ending it to 1, we add all the solutions to the array List.This array List is returned by eliminating the duplicate values in the List At first, we give the possible sets and numbers of combinations as input in an array. Create a list and store all of them. Taking a Set and store the solution in that set. Call the shortest combo function This function takes a set as input and throws an exception if size greater than 20 Iterates the size of all possible combinations and the new Set It then right shifts the value and then ending it to 1, we add all the solutions to the array List. This array List is returned by eliminating the duplicate values in the List Implementation: Example Java // Java Program to Solve Set Cover Problem// assuming at Maximum 2 Elements in a Subset // Importing input output classesimport java.io.*;// Importing necessarily required utility classes// from java.util packageimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.LinkedHashSet;import java.util.List;import java.util.Set; // Main classpublic class GFG { // Interface // Declaring the interface thereby taking // abstract methods of the interface interface Filter<T> { boolean matches(T t); } // Method 1 // Declaring a method-'shortcombo' // Declaring in form of set also returning a set private static <T> Set<T> shortcombo(Filter<Set<T> > filter, List<T> sets) { // Taking the size of the set final int size = sets.size(); // Condition check // If the size of the set is greater than 25 // We throw an exception like too many combinations if (size > 20) throw new IllegalArgumentException( "Too many Combinations"); // Now the comb will left shift 1 time of size int comb = 1 << size; // Taking a set with reg=ference possible // this Arraylist will contain all the possible // solution List<Set<T> > possible = new ArrayList<Set<T> >(); // Taking a loop which iterates till comb for (int i = 0; i < comb; i++) { // Taking a lInkedHashSet of reference // combination Set<T> combination = new LinkedHashSet<T>(); // Taking a loop and iterating till size for (int j = 0; j < size; j++) { // If now we right shift i and j // and then ending it with 1 // This possible logic will give us how many // combinations are possible if (((i >> j) & 1) != 0) // Now the combinations are added to the // set combination.add(sets.get(j)); } // It is added to the possible reference possible.add(combination); } // Collections can be now sorted accordingly // using the sort() method over Collections class Collections.sort( possible, new Comparator<Set<T> >() { // We can find the minimum length by taking // the difference between sizes of possible // list public int compare(Set<T> a1, Set<T> a2) { return a1.size() - a2.size(); } }); // Now we take the iteration till possible for (Set<T> possibleSol : possible) { // Then we check for matching of the possible // solution // If it does we return the solution // If it doesnot we return null if (filter.matches(possibleSol)) return possibleSol; } return null; } // Method 2 // Main method public static void main(String[] args) { // Taking all the possible combinations // Custom entries in array Integer[][] all = { { 1, 2 }, { 3, 4 }, { 8, 9 }, { 10, 7 }, { 5, 8 }, { 11, 6 }, { 4, 5 }, { 6, 7 }, { 10, 11 }, }; // Here is the list of numbers to be chosen from // Again, custom entries in array Integer[] solution = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // Here let us take set as an object of an ArrayList List<Set<Integer> > sets = new ArrayList<Set<Integer> >(); // Now taking an array of the function all for (Integer[] array : all) // Now taking those elements and adding them to // an LinkedHashSet sets.add(new LinkedHashSet<Integer>( Arrays.asList(array))); // Now taking a set integer sol and // setting it as solution final Set<Integer> sol = new LinkedHashSet<Integer>( Arrays.asList(solution)); // Now taking a filter to check the values Filter<Set<Set<Integer> > > filter = new Filter<Set<Set<Integer> > >() { // Now taking boolean function matches // This function helps iterate all values // over the integers variable which adds // up all that to an union which will give // us the desired result public boolean matches( Set<Set<Integer> > integers) { Set<Integer> union = new LinkedHashSet<Integer>(); // Iterating using for-each loop for (Set<Integer> ints : integers) union.addAll(ints); return union.equals(sol); } }; // Now the below set will call the short combo // function This function will sort the shortest // combo Set<Set<Integer> > firstSol = shortcombo(filter, sets); // Print and display out the same System.out.println("The short combination was : " + firstSol); }} The short combination was : [[1, 2], [3, 4], [8, 9], [10, 7], [5, 8], [11, 6]] simmytarika5 surinderdawra388 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jul, 2022" }, { "code": null, "e": 215, "s": 28, "text": "Problem Statement: Given a set of elements 1 to n and a set S of n sets whose union equals everything, the problem is to find the minimum numbers of subsets equal the set in a pair of 2." }, { "code": null, "e": 332, "s": 215, "text": "Concept: This problem is to solve the set problems. We can use permutations and combinations to solve this problem. " }, { "code": null, "e": 346, "s": 332, "text": "Illustration:" }, { "code": null, "e": 453, "s": 346, "text": "Input: All Possible Combination = {{1,2}, {3,4}, {8,9}, {10,7}, {5,8}, {11,6}, {4,5}, {6,7}, {10,11},}" }, { "code": null, "e": 505, "s": 453, "text": " Numbers = {1,2,3,4,5,6,7,8,9,10,11}" }, { "code": null, "e": 592, "s": 505, "text": "Output: The short combination was : [[1, 2], [3, 4], [8, 9], [10, 7], [5, 8], [11, 6]]" }, { "code": null, "e": 675, "s": 592, "text": "Input: All Possible Combination = {{1,2}, {3,4}, {2,7}, {5,3}, {4,5}, {6,7}, }" }, { "code": null, "e": 716, "s": 675, "text": " Numbers = {1,2,3,4,5,6,7}" }, { "code": null, "e": 785, "s": 716, "text": "Output: The short combination was : [[1, 2], [3, 4], [5, 3], [6, 7]]" }, { "code": null, "e": 795, "s": 785, "text": "Approach:" }, { "code": null, "e": 1315, "s": 795, "text": "At first, we give the possible sets and numbers of combinations as input in an array.Create a list and store all of them.Taking a Set and store the solution in that set.Call the shortest combo functionThis function takes a set as input and throws an exception if size greater than 20Iterates the size of all possible combinations and the new SetIt then right shifts the value and then ending it to 1, we add all the solutions to the array List.This array List is returned by eliminating the duplicate values in the List" }, { "code": null, "e": 1401, "s": 1315, "text": "At first, we give the possible sets and numbers of combinations as input in an array." }, { "code": null, "e": 1438, "s": 1401, "text": "Create a list and store all of them." }, { "code": null, "e": 1487, "s": 1438, "text": "Taking a Set and store the solution in that set." }, { "code": null, "e": 1520, "s": 1487, "text": "Call the shortest combo function" }, { "code": null, "e": 1603, "s": 1520, "text": "This function takes a set as input and throws an exception if size greater than 20" }, { "code": null, "e": 1666, "s": 1603, "text": "Iterates the size of all possible combinations and the new Set" }, { "code": null, "e": 1766, "s": 1666, "text": "It then right shifts the value and then ending it to 1, we add all the solutions to the array List." }, { "code": null, "e": 1842, "s": 1766, "text": "This array List is returned by eliminating the duplicate values in the List" }, { "code": null, "e": 1858, "s": 1842, "text": "Implementation:" }, { "code": null, "e": 1866, "s": 1858, "text": "Example" }, { "code": null, "e": 1871, "s": 1866, "text": "Java" }, { "code": "// Java Program to Solve Set Cover Problem// assuming at Maximum 2 Elements in a Subset // Importing input output classesimport java.io.*;// Importing necessarily required utility classes// from java.util packageimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.LinkedHashSet;import java.util.List;import java.util.Set; // Main classpublic class GFG { // Interface // Declaring the interface thereby taking // abstract methods of the interface interface Filter<T> { boolean matches(T t); } // Method 1 // Declaring a method-'shortcombo' // Declaring in form of set also returning a set private static <T> Set<T> shortcombo(Filter<Set<T> > filter, List<T> sets) { // Taking the size of the set final int size = sets.size(); // Condition check // If the size of the set is greater than 25 // We throw an exception like too many combinations if (size > 20) throw new IllegalArgumentException( \"Too many Combinations\"); // Now the comb will left shift 1 time of size int comb = 1 << size; // Taking a set with reg=ference possible // this Arraylist will contain all the possible // solution List<Set<T> > possible = new ArrayList<Set<T> >(); // Taking a loop which iterates till comb for (int i = 0; i < comb; i++) { // Taking a lInkedHashSet of reference // combination Set<T> combination = new LinkedHashSet<T>(); // Taking a loop and iterating till size for (int j = 0; j < size; j++) { // If now we right shift i and j // and then ending it with 1 // This possible logic will give us how many // combinations are possible if (((i >> j) & 1) != 0) // Now the combinations are added to the // set combination.add(sets.get(j)); } // It is added to the possible reference possible.add(combination); } // Collections can be now sorted accordingly // using the sort() method over Collections class Collections.sort( possible, new Comparator<Set<T> >() { // We can find the minimum length by taking // the difference between sizes of possible // list public int compare(Set<T> a1, Set<T> a2) { return a1.size() - a2.size(); } }); // Now we take the iteration till possible for (Set<T> possibleSol : possible) { // Then we check for matching of the possible // solution // If it does we return the solution // If it doesnot we return null if (filter.matches(possibleSol)) return possibleSol; } return null; } // Method 2 // Main method public static void main(String[] args) { // Taking all the possible combinations // Custom entries in array Integer[][] all = { { 1, 2 }, { 3, 4 }, { 8, 9 }, { 10, 7 }, { 5, 8 }, { 11, 6 }, { 4, 5 }, { 6, 7 }, { 10, 11 }, }; // Here is the list of numbers to be chosen from // Again, custom entries in array Integer[] solution = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; // Here let us take set as an object of an ArrayList List<Set<Integer> > sets = new ArrayList<Set<Integer> >(); // Now taking an array of the function all for (Integer[] array : all) // Now taking those elements and adding them to // an LinkedHashSet sets.add(new LinkedHashSet<Integer>( Arrays.asList(array))); // Now taking a set integer sol and // setting it as solution final Set<Integer> sol = new LinkedHashSet<Integer>( Arrays.asList(solution)); // Now taking a filter to check the values Filter<Set<Set<Integer> > > filter = new Filter<Set<Set<Integer> > >() { // Now taking boolean function matches // This function helps iterate all values // over the integers variable which adds // up all that to an union which will give // us the desired result public boolean matches( Set<Set<Integer> > integers) { Set<Integer> union = new LinkedHashSet<Integer>(); // Iterating using for-each loop for (Set<Integer> ints : integers) union.addAll(ints); return union.equals(sol); } }; // Now the below set will call the short combo // function This function will sort the shortest // combo Set<Set<Integer> > firstSol = shortcombo(filter, sets); // Print and display out the same System.out.println(\"The short combination was : \" + firstSol); }}", "e": 7213, "s": 1871, "text": null }, { "code": null, "e": 7292, "s": 7213, "text": "The short combination was : [[1, 2], [3, 4], [8, 9], [10, 7], [5, 8], [11, 6]]" }, { "code": null, "e": 7305, "s": 7292, "text": "simmytarika5" }, { "code": null, "e": 7322, "s": 7305, "text": "surinderdawra388" }, { "code": null, "e": 7329, "s": 7322, "text": "Picked" }, { "code": null, "e": 7334, "s": 7329, "text": "Java" }, { "code": null, "e": 7348, "s": 7334, "text": "Java Programs" }, { "code": null, "e": 7353, "s": 7348, "text": "Java" } ]
Python – Convert Image to String and vice-versa
23 Dec, 2020 To store or transfer an Image to some we need to convert it into a string such that the string should portray the image which we give as input. So In Python to do this Operation, it is a straight forward task not complicated because we have a lot of functions in Python available. Here First We Import “Base64“ Method To Encode The Given Image Next, We Opened Our Image File In rb Mode Which Is Read In Binary Mode. The We Read Our Image With image2.read() Which Reads The Image And Encode it Using b64encode() It Is Method That Is Used To Encode Data Into Base64 Finally, we Print Our Encoded String Image used: Python3 import base64 with open("food.jpeg", "rb") as image2string: converted_string = base64.b64encode(image2string.read())print(converted_string) with open('encode.bin', "wb") as file: file.write(converted_string) Output: This Is The Output Of Image That is Converted To String Using Base64 Here We got the output but if you notice in Starting Of String we get this b’ This We Can Say As Base64 Encoded String in Pair of single quotation. So if we want to remove that we can do the Following By Replacing The Print Statement With print(my_string.decode(‘utf-8’)) Here To Convert It From String It Is Actually A Reverse Process Which Is Also Straight Forward Method First We Import Base64. Then We Open Our binary File Where We Dumped Our String. Then Open The File rb Mode Which Is Read In Binary Mode. Store The Data That was Read From File Into A Variable. Then Close The File Then Just Give Any Image File Name (ex:”myimage.png”) And Open It In wb Mode Write In Binary Decode The Binary With b64.decode() Then Close The File With .close() Note: We will use the above-created string for converting it back to the image Python3 import base64 file = open('encode.bin', 'rb')byte = file.read()file.close() decodeit = open('hello_level.jpeg', 'wb')decodeit.write(base64.b64decode((byte)))decodeit.close() Output: Picked python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Dec, 2020" }, { "code": null, "e": 333, "s": 52, "text": "To store or transfer an Image to some we need to convert it into a string such that the string should portray the image which we give as input. So In Python to do this Operation, it is a straight forward task not complicated because we have a lot of functions in Python available." }, { "code": null, "e": 397, "s": 333, "text": "Here First We Import “Base64“ Method To Encode The Given Image " }, { "code": null, "e": 469, "s": 397, "text": "Next, We Opened Our Image File In rb Mode Which Is Read In Binary Mode." }, { "code": null, "e": 618, "s": 469, "text": "The We Read Our Image With image2.read() Which Reads The Image And Encode it Using b64encode() It Is Method That Is Used To Encode Data Into Base64 " }, { "code": null, "e": 656, "s": 618, "text": "Finally, we Print Our Encoded String " }, { "code": null, "e": 668, "s": 656, "text": "Image used:" }, { "code": null, "e": 676, "s": 668, "text": "Python3" }, { "code": "import base64 with open(\"food.jpeg\", \"rb\") as image2string: converted_string = base64.b64encode(image2string.read())print(converted_string) with open('encode.bin', \"wb\") as file: file.write(converted_string)", "e": 894, "s": 676, "text": null }, { "code": null, "e": 902, "s": 894, "text": "Output:" }, { "code": null, "e": 972, "s": 902, "text": "This Is The Output Of Image That is Converted To String Using Base64" }, { "code": null, "e": 1244, "s": 972, "text": "Here We got the output but if you notice in Starting Of String we get this b’ This We Can Say As Base64 Encoded String in Pair of single quotation. So if we want to remove that we can do the Following By Replacing The Print Statement With print(my_string.decode(‘utf-8’))" }, { "code": null, "e": 1346, "s": 1244, "text": "Here To Convert It From String It Is Actually A Reverse Process Which Is Also Straight Forward Method" }, { "code": null, "e": 1484, "s": 1346, "text": "First We Import Base64. Then We Open Our binary File Where We Dumped Our String. Then Open The File rb Mode Which Is Read In Binary Mode." }, { "code": null, "e": 1561, "s": 1484, "text": "Store The Data That was Read From File Into A Variable. Then Close The File " }, { "code": null, "e": 1656, "s": 1561, "text": "Then Just Give Any Image File Name (ex:”myimage.png”) And Open It In wb Mode Write In Binary " }, { "code": null, "e": 1726, "s": 1656, "text": "Decode The Binary With b64.decode() Then Close The File With .close()" }, { "code": null, "e": 1805, "s": 1726, "text": "Note: We will use the above-created string for converting it back to the image" }, { "code": null, "e": 1813, "s": 1805, "text": "Python3" }, { "code": "import base64 file = open('encode.bin', 'rb')byte = file.read()file.close() decodeit = open('hello_level.jpeg', 'wb')decodeit.write(base64.b64decode((byte)))decodeit.close()", "e": 1991, "s": 1813, "text": null }, { "code": null, "e": 1999, "s": 1991, "text": "Output:" }, { "code": null, "e": 2006, "s": 1999, "text": "Picked" }, { "code": null, "e": 2020, "s": 2006, "text": "python-string" }, { "code": null, "e": 2027, "s": 2020, "text": "Python" } ]
Scala Int max() method with example
30 Jan, 2020 The max() method is utilized to return the maximum value of the two specified int numbers. Method Definition: (First_Number).max(Second_Number) Return Type: It returns true the maximum value of the two specified int numbers. Example #1: // Scala program of Int max()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying max method val result = (5).max(9) // Displays output println(result) }} 9 Example #2: // Scala program of Int max()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying max method val result = (5).max(5) // Displays output println(result) }} 5 Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 119, "s": 28, "text": "The max() method is utilized to return the maximum value of the two specified int numbers." }, { "code": null, "e": 172, "s": 119, "text": "Method Definition: (First_Number).max(Second_Number)" }, { "code": null, "e": 253, "s": 172, "text": "Return Type: It returns true the maximum value of the two specified int numbers." }, { "code": null, "e": 265, "s": 253, "text": "Example #1:" }, { "code": "// Scala program of Int max()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying max method val result = (5).max(9) // Displays output println(result) }} ", "e": 537, "s": 265, "text": null }, { "code": null, "e": 540, "s": 537, "text": "9\n" }, { "code": null, "e": 552, "s": 540, "text": "Example #2:" }, { "code": "// Scala program of Int max()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying max method val result = (5).max(5) // Displays output println(result) }} ", "e": 824, "s": 552, "text": null }, { "code": null, "e": 827, "s": 824, "text": "5\n" }, { "code": null, "e": 833, "s": 827, "text": "Scala" }, { "code": null, "e": 846, "s": 833, "text": "Scala-Method" }, { "code": null, "e": 852, "s": 846, "text": "Scala" } ]
Program for Page Replacement Algorithms | Set 2 (FIFO)
13 Jul, 2022 Prerequisite : Page Replacement Algorithms In operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults. First In First Out (FIFO) page replacement algorithm – Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of the queue is selected for removal. Example -1. Consider page reference string 1, 3, 0, 3, 5, 6 and 3 page slots. Initially all slots are empty, so when 1, 3, 0 came they are allocated to the empty slots —> 3 Page Faults. when 3 comes, it is already in memory so —> 0 Page Faults. Then 5 comes, it is not available in memory so it replaces the oldest page slot i.e 1. —>1Page Fault. Finally 6 comes, it is also not available in memory so it replaces the oldest page slot i.e 3 —>1 Page Fault. So total page faults = 5. Example -2. Consider the following reference string: 0, 2, 1, 6, 4, 0, 1, 0, 3, 1, 2, 1. Using FIFO page replacement algorithm – So, total number of page faults = 9. Given memory capacity (as number of pages it can hold) and a string representing pages to be referred, write a function to find number of page faults. Implementation – Let capacity be the number of pages that memory can hold. Let set be the current set of pages in memory. 1- Start traversing the pages. i) If set holds less pages than capacity. a) Insert page into the set one by one until the size of set reaches capacity or all page requests are processed. b) Simultaneously maintain the pages in the queue to perform FIFO. c) Increment page fault ii) Else If current page is present in set, do nothing. Else a) Remove the first page from the queue as it was the first to be entered in the memory b) Replace the first page in the queue with the current page in the string. c) Store current page in the queue. d) Increment page faults. 2. Return page faults. Implementation: C++ Java Python3 C# // C++ implementation of FIFO page replacement// in Operating Systems.#include<bits/stdc++.h>using namespace std; // Function to find page faults using FIFOint pageFaults(int pages[], int n, int capacity){ // To represent set of current pages. We use // an unordered_set so that we quickly check // if a page is present in set or not unordered_set<int> s; // To store the pages in FIFO manner queue<int> indexes; // Start from initial page int page_faults = 0; for (int i=0; i<n; i++) { // Check if the set can hold more pages if (s.size() < capacity) { // Insert it into set if not present // already which represents page fault if (s.find(pages[i])==s.end()) { // Insert the current page into the set s.insert(pages[i]); // increment page fault page_faults++; // Push the current page into the queue indexes.push(pages[i]); } } // If the set is full then need to perform FIFO // i.e. remove the first page of the queue from // set and queue both and insert the current page else { // Check if current page is not already // present in the set if (s.find(pages[i]) == s.end()) { // Store the first page in the // queue to be used to find and // erase the page from the set int val = indexes.front(); // Pop the first page from the queue indexes.pop(); // Remove the indexes page from the set s.erase(val); // insert the current page in the set s.insert(pages[i]); // push the current page into // the queue indexes.push(pages[i]); // Increment page faults page_faults++; } } } return page_faults;} // Driver codeint main(){ int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2}; int n = sizeof(pages)/sizeof(pages[0]); int capacity = 4; cout << pageFaults(pages, n, capacity); return 0;} // Java implementation of FIFO page replacement// in Operating Systems. import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; class Test{ // Method to find page faults using FIFO static int pageFaults(int pages[], int n, int capacity) { // To represent set of current pages. We use // an unordered_set so that we quickly check // if a page is present in set or not HashSet<Integer> s = new HashSet<>(capacity); // To store the pages in FIFO manner Queue<Integer> indexes = new LinkedList<>() ; // Start from initial page int page_faults = 0; for (int i=0; i<n; i++) { // Check if the set can hold more pages if (s.size() < capacity) { // Insert it into set if not present // already which represents page fault if (!s.contains(pages[i])) { s.add(pages[i]); // increment page fault page_faults++; // Push the current page into the queue indexes.add(pages[i]); } } // If the set is full then need to perform FIFO // i.e. remove the first page of the queue from // set and queue both and insert the current page else { // Check if current page is not already // present in the set if (!s.contains(pages[i])) { //Pop the first page from the queue int val = indexes.peek(); indexes.poll(); // Remove the indexes page s.remove(val); // insert the current page s.add(pages[i]); // push the current page into // the queue indexes.add(pages[i]); // Increment page faults page_faults++; } } } return page_faults; } // Driver method public static void main(String args[]) { int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2}; int capacity = 4; System.out.println(pageFaults(pages, pages.length, capacity)); }}// This code is contributed by Gaurav Miglani # Python3 implementation of FIFO page# replacement in Operating Systems.from queue import Queue # Function to find page faults using FIFOdef pageFaults(pages, n, capacity): # To represent set of current pages. # We use an unordered_set so that we # quickly check if a page is present # in set or not s = set() # To store the pages in FIFO manner indexes = Queue() # Start from initial page page_faults = 0 for i in range(n): # Check if the set can hold # more pages if (len(s) < capacity): # Insert it into set if not present # already which represents page fault if (pages[i] not in s): s.add(pages[i]) # increment page fault page_faults += 1 # Push the current page into # the queue indexes.put(pages[i]) # If the set is full then need to perform FIFO # i.e. remove the first page of the queue from # set and queue both and insert the current page else: # Check if current page is not # already present in the set if (pages[i] not in s): # Pop the first page from the queue val = indexes.queue[0] indexes.get() # Remove the indexes page s.remove(val) # insert the current page s.add(pages[i]) # push the current page into # the queue indexes.put(pages[i]) # Increment page faults page_faults += 1 return page_faults # Driver codeif __name__ == '__main__': pages = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2] n = len(pages) capacity = 4 print(pageFaults(pages, n, capacity)) # This code is contributed by PranchalK // C# implementation of FIFO page replacement// in Operating Systems.using System;using System.Collections;using System.Collections.Generic; class Test{ // Method to find page faults using FIFO static int pageFaults(int []pages, int n, int capacity) { // To represent set of current pages. We use // an unordered_set so that we quickly check // if a page is present in set or not HashSet<int> s = new HashSet<int>(capacity); // To store the pages in FIFO manner Queue indexes = new Queue() ; // Start from initial page int page_faults = 0; for (int i = 0; i < n; i++) { // Check if the set can hold more pages if (s.Count < capacity) { // Insert it into set if not present // already which represents page fault if (!s.Contains(pages[i])) { s.Add(pages[i]); // increment page fault page_faults++; // Push the current page into the queue indexes.Enqueue(pages[i]); } } // If the set is full then need to perform FIFO // i.e. Remove the first page of the queue from // set and queue both and insert the current page else { // Check if current page is not already // present in the set if (!s.Contains(pages[i])) { //Pop the first page from the queue int val = (int)indexes.Peek(); indexes.Dequeue(); // Remove the indexes page s.Remove(val); // insert the current page s.Add(pages[i]); // push the current page into // the queue indexes.Enqueue(pages[i]); // Increment page faults page_faults++; } } } return page_faults; } // Driver method public static void Main(String []args) { int []pages = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2}; int capacity = 4; Console.Write(pageFaults(pages, pages.Length, capacity)); }} // This code is contributed by Arnab Kundu 7 Note – We can also find the number of page hits. Just have to maintain a separate count. If the current page is already in the memory then that must be count as Page-hit. Belady’s anomaly: Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm. For example, if we consider reference string 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4 and 3 slots, we get 9 total page faults, but if we increase slots to 4, we get 10 page faults. This article is contributed by Sahil Chhabra. 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. Villan PranchalKatiyar andrew1234 verma_anushka hardikkoriintern Greedy Queue Greedy Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jul, 2022" }, { "code": null, "e": 580, "s": 54, "text": "Prerequisite : Page Replacement Algorithms In operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults. " }, { "code": null, "e": 636, "s": 580, "text": "First In First Out (FIFO) page replacement algorithm – " }, { "code": null, "e": 645, "s": 636, "text": "Chapters" }, { "code": null, "e": 672, "s": 645, "text": "descriptions off, selected" }, { "code": null, "e": 722, "s": 672, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 745, "s": 722, "text": "captions off, selected" }, { "code": null, "e": 753, "s": 745, "text": "English" }, { "code": null, "e": 777, "s": 753, "text": "This is a modal window." }, { "code": null, "e": 846, "s": 777, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 868, "s": 846, "text": "End of dialog window." }, { "code": null, "e": 1137, "s": 868, "text": " This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of the queue is selected for removal. " }, { "code": null, "e": 1324, "s": 1137, "text": "Example -1. Consider page reference string 1, 3, 0, 3, 5, 6 and 3 page slots. Initially all slots are empty, so when 1, 3, 0 came they are allocated to the empty slots —> 3 Page Faults. " }, { "code": null, "e": 1486, "s": 1324, "text": "when 3 comes, it is already in memory so —> 0 Page Faults. Then 5 comes, it is not available in memory so it replaces the oldest page slot i.e 1. —>1Page Fault. " }, { "code": null, "e": 1597, "s": 1486, "text": "Finally 6 comes, it is also not available in memory so it replaces the oldest page slot i.e 3 —>1 Page Fault. " }, { "code": null, "e": 1624, "s": 1597, "text": "So total page faults = 5. " }, { "code": null, "e": 1754, "s": 1624, "text": "Example -2. Consider the following reference string: 0, 2, 1, 6, 4, 0, 1, 0, 3, 1, 2, 1. Using FIFO page replacement algorithm – " }, { "code": null, "e": 1944, "s": 1754, "text": " So, total number of page faults = 9. Given memory capacity (as number of pages it can hold) and a string representing pages to be referred, write a function to find number of page faults. " }, { "code": null, "e": 2066, "s": 1944, "text": "Implementation – Let capacity be the number of pages that memory can hold. Let set be the current set of pages in memory." }, { "code": null, "e": 2739, "s": 2066, "text": "1- Start traversing the pages.\n i) If set holds less pages than capacity.\n a) Insert page into the set one by one until \n the size of set reaches capacity or all\n page requests are processed.\n b) Simultaneously maintain the pages in the\n queue to perform FIFO.\n c) Increment page fault\n ii) Else \n If current page is present in set, do nothing.\n Else \n a) Remove the first page from the queue\n as it was the first to be entered in\n the memory\n b) Replace the first page in the queue with \n the current page in the string.\n c) Store current page in the queue.\n d) Increment page faults.\n\n2. Return page faults." }, { "code": null, "e": 2755, "s": 2739, "text": "Implementation:" }, { "code": null, "e": 2759, "s": 2755, "text": "C++" }, { "code": null, "e": 2764, "s": 2759, "text": "Java" }, { "code": null, "e": 2772, "s": 2764, "text": "Python3" }, { "code": null, "e": 2775, "s": 2772, "text": "C#" }, { "code": "// C++ implementation of FIFO page replacement// in Operating Systems.#include<bits/stdc++.h>using namespace std; // Function to find page faults using FIFOint pageFaults(int pages[], int n, int capacity){ // To represent set of current pages. We use // an unordered_set so that we quickly check // if a page is present in set or not unordered_set<int> s; // To store the pages in FIFO manner queue<int> indexes; // Start from initial page int page_faults = 0; for (int i=0; i<n; i++) { // Check if the set can hold more pages if (s.size() < capacity) { // Insert it into set if not present // already which represents page fault if (s.find(pages[i])==s.end()) { // Insert the current page into the set s.insert(pages[i]); // increment page fault page_faults++; // Push the current page into the queue indexes.push(pages[i]); } } // If the set is full then need to perform FIFO // i.e. remove the first page of the queue from // set and queue both and insert the current page else { // Check if current page is not already // present in the set if (s.find(pages[i]) == s.end()) { // Store the first page in the // queue to be used to find and // erase the page from the set int val = indexes.front(); // Pop the first page from the queue indexes.pop(); // Remove the indexes page from the set s.erase(val); // insert the current page in the set s.insert(pages[i]); // push the current page into // the queue indexes.push(pages[i]); // Increment page faults page_faults++; } } } return page_faults;} // Driver codeint main(){ int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2}; int n = sizeof(pages)/sizeof(pages[0]); int capacity = 4; cout << pageFaults(pages, n, capacity); return 0;}", "e": 5055, "s": 2775, "text": null }, { "code": "// Java implementation of FIFO page replacement// in Operating Systems. import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; class Test{ // Method to find page faults using FIFO static int pageFaults(int pages[], int n, int capacity) { // To represent set of current pages. We use // an unordered_set so that we quickly check // if a page is present in set or not HashSet<Integer> s = new HashSet<>(capacity); // To store the pages in FIFO manner Queue<Integer> indexes = new LinkedList<>() ; // Start from initial page int page_faults = 0; for (int i=0; i<n; i++) { // Check if the set can hold more pages if (s.size() < capacity) { // Insert it into set if not present // already which represents page fault if (!s.contains(pages[i])) { s.add(pages[i]); // increment page fault page_faults++; // Push the current page into the queue indexes.add(pages[i]); } } // If the set is full then need to perform FIFO // i.e. remove the first page of the queue from // set and queue both and insert the current page else { // Check if current page is not already // present in the set if (!s.contains(pages[i])) { //Pop the first page from the queue int val = indexes.peek(); indexes.poll(); // Remove the indexes page s.remove(val); // insert the current page s.add(pages[i]); // push the current page into // the queue indexes.add(pages[i]); // Increment page faults page_faults++; } } } return page_faults; } // Driver method public static void main(String args[]) { int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2}; int capacity = 4; System.out.println(pageFaults(pages, pages.length, capacity)); }}// This code is contributed by Gaurav Miglani", "e": 7534, "s": 5055, "text": null }, { "code": "# Python3 implementation of FIFO page# replacement in Operating Systems.from queue import Queue # Function to find page faults using FIFOdef pageFaults(pages, n, capacity): # To represent set of current pages. # We use an unordered_set so that we # quickly check if a page is present # in set or not s = set() # To store the pages in FIFO manner indexes = Queue() # Start from initial page page_faults = 0 for i in range(n): # Check if the set can hold # more pages if (len(s) < capacity): # Insert it into set if not present # already which represents page fault if (pages[i] not in s): s.add(pages[i]) # increment page fault page_faults += 1 # Push the current page into # the queue indexes.put(pages[i]) # If the set is full then need to perform FIFO # i.e. remove the first page of the queue from # set and queue both and insert the current page else: # Check if current page is not # already present in the set if (pages[i] not in s): # Pop the first page from the queue val = indexes.queue[0] indexes.get() # Remove the indexes page s.remove(val) # insert the current page s.add(pages[i]) # push the current page into # the queue indexes.put(pages[i]) # Increment page faults page_faults += 1 return page_faults # Driver codeif __name__ == '__main__': pages = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2] n = len(pages) capacity = 4 print(pageFaults(pages, n, capacity)) # This code is contributed by PranchalK", "e": 9459, "s": 7534, "text": null }, { "code": "// C# implementation of FIFO page replacement// in Operating Systems.using System;using System.Collections;using System.Collections.Generic; class Test{ // Method to find page faults using FIFO static int pageFaults(int []pages, int n, int capacity) { // To represent set of current pages. We use // an unordered_set so that we quickly check // if a page is present in set or not HashSet<int> s = new HashSet<int>(capacity); // To store the pages in FIFO manner Queue indexes = new Queue() ; // Start from initial page int page_faults = 0; for (int i = 0; i < n; i++) { // Check if the set can hold more pages if (s.Count < capacity) { // Insert it into set if not present // already which represents page fault if (!s.Contains(pages[i])) { s.Add(pages[i]); // increment page fault page_faults++; // Push the current page into the queue indexes.Enqueue(pages[i]); } } // If the set is full then need to perform FIFO // i.e. Remove the first page of the queue from // set and queue both and insert the current page else { // Check if current page is not already // present in the set if (!s.Contains(pages[i])) { //Pop the first page from the queue int val = (int)indexes.Peek(); indexes.Dequeue(); // Remove the indexes page s.Remove(val); // insert the current page s.Add(pages[i]); // push the current page into // the queue indexes.Enqueue(pages[i]); // Increment page faults page_faults++; } } } return page_faults; } // Driver method public static void Main(String []args) { int []pages = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2}; int capacity = 4; Console.Write(pageFaults(pages, pages.Length, capacity)); }} // This code is contributed by Arnab Kundu", "e": 11912, "s": 9459, "text": null }, { "code": null, "e": 11914, "s": 11912, "text": "7" }, { "code": null, "e": 12086, "s": 11914, "text": "Note – We can also find the number of page hits. Just have to maintain a separate count. If the current page is already in the memory then that must be count as Page-hit. " }, { "code": null, "e": 12104, "s": 12086, "text": "Belady’s anomaly:" }, { "code": null, "e": 12461, "s": 12104, "text": "Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm. For example, if we consider reference string 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4 and 3 slots, we get 9 total page faults, but if we increase slots to 4, we get 10 page faults. " }, { "code": null, "e": 12758, "s": 12461, "text": "This article is contributed by Sahil Chhabra. 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." }, { "code": null, "e": 12765, "s": 12758, "text": "Villan" }, { "code": null, "e": 12781, "s": 12765, "text": "PranchalKatiyar" }, { "code": null, "e": 12792, "s": 12781, "text": "andrew1234" }, { "code": null, "e": 12806, "s": 12792, "text": "verma_anushka" }, { "code": null, "e": 12823, "s": 12806, "text": "hardikkoriintern" }, { "code": null, "e": 12830, "s": 12823, "text": "Greedy" }, { "code": null, "e": 12836, "s": 12830, "text": "Queue" }, { "code": null, "e": 12843, "s": 12836, "text": "Greedy" }, { "code": null, "e": 12849, "s": 12843, "text": "Queue" } ]
How to find the height of a text in HTML canvas using JavaScript ?
25 Dec, 2020 In this article, we will find the height of the text canvas using JavaScript. Approach: In the following example, the height attribute of the HTML canvas is used. First set the font in pt to set the height. context.font = '26pt Calibri'; Then the current text is aligned in the center by using values ‘middle’ and color ‘yellow’. context.textAlign = 'middle'; context.fillStyle = 'yellow'; Then, check the width of the text using the measureText() method before writing to the canvas. Finally, the text is written on the canvas using the fillText() method. Example 1: HTML <!DOCTYPE HTML><html> <head> <style> body { margin: 0px; padding: 0px; } </style></head> <body> <canvas id="myCanvas" width="550" height="200"> </canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var x = canvas.width / 3; var y = canvas.height / 2 - 15; var text = 'HI '; // Set the font to set the height context.font = '26pt Calibri'; context.textAlign = 'middle'; context.fillStyle = 'yellow'; context.fillText(text, x, y); context.font = '20pt Calibri'; // Check the width of the text var metrics = context.measureText(text); var width = metrics.width; // Text is aligned in the left context.textAlign = 'left'; context.fillStyle = '#010'; context.fillText('(' + width + 'px wide)', x, y + 40); </script></body> </html> Approach: First get the 2d drawing context of the canvas by using getContext() method. Set the font and the text string. Then write the text with x and y co-ordinates using fillText() method as given below. Example 2: HTML <!DOCTYPE html><html> <body> <canvas id="Canvas" width="300" height="150" style="border:1px solid #010;"> Your browser isn't supporting HTML5 canvas tag. </canvas> <script> var c = document.getElementById("Canvas"); var x = c.getContext("2d"); x.font = "30px Arial"; var txt = "Computer Science" x.fillText("width:" + x.measureText(txt).width, 10, 50); x.fillText(txt, 10, 100); </script></body> </html> HTML-Canvas JavaScript-Misc Picked Technical Scripter 2020 HTML JavaScript Technical Scripter 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": "\n25 Dec, 2020" }, { "code": null, "e": 132, "s": 54, "text": "In this article, we will find the height of the text canvas using JavaScript." }, { "code": null, "e": 261, "s": 132, "text": "Approach: In the following example, the height attribute of the HTML canvas is used. First set the font in pt to set the height." }, { "code": null, "e": 292, "s": 261, "text": "context.font = '26pt Calibri';" }, { "code": null, "e": 384, "s": 292, "text": "Then the current text is aligned in the center by using values ‘middle’ and color ‘yellow’." }, { "code": null, "e": 444, "s": 384, "text": "context.textAlign = 'middle';\ncontext.fillStyle = 'yellow';" }, { "code": null, "e": 611, "s": 444, "text": "Then, check the width of the text using the measureText() method before writing to the canvas. Finally, the text is written on the canvas using the fillText() method." }, { "code": null, "e": 622, "s": 611, "text": "Example 1:" }, { "code": null, "e": 627, "s": 622, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <style> body { margin: 0px; padding: 0px; } </style></head> <body> <canvas id=\"myCanvas\" width=\"550\" height=\"200\"> </canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var x = canvas.width / 3; var y = canvas.height / 2 - 15; var text = 'HI '; // Set the font to set the height context.font = '26pt Calibri'; context.textAlign = 'middle'; context.fillStyle = 'yellow'; context.fillText(text, x, y); context.font = '20pt Calibri'; // Check the width of the text var metrics = context.measureText(text); var width = metrics.width; // Text is aligned in the left context.textAlign = 'left'; context.fillStyle = '#010'; context.fillText('(' + width + 'px wide)', x, y + 40); </script></body> </html>", "e": 1625, "s": 627, "text": null }, { "code": null, "e": 1832, "s": 1625, "text": "Approach: First get the 2d drawing context of the canvas by using getContext() method. Set the font and the text string. Then write the text with x and y co-ordinates using fillText() method as given below." }, { "code": null, "e": 1843, "s": 1832, "text": "Example 2:" }, { "code": null, "e": 1848, "s": 1843, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <canvas id=\"Canvas\" width=\"300\" height=\"150\" style=\"border:1px solid #010;\"> Your browser isn't supporting HTML5 canvas tag. </canvas> <script> var c = document.getElementById(\"Canvas\"); var x = c.getContext(\"2d\"); x.font = \"30px Arial\"; var txt = \"Computer Science\" x.fillText(\"width:\" + x.measureText(txt).width, 10, 50); x.fillText(txt, 10, 100); </script></body> </html>", "e": 2345, "s": 1848, "text": null }, { "code": null, "e": 2357, "s": 2345, "text": "HTML-Canvas" }, { "code": null, "e": 2373, "s": 2357, "text": "JavaScript-Misc" }, { "code": null, "e": 2380, "s": 2373, "text": "Picked" }, { "code": null, "e": 2404, "s": 2380, "text": "Technical Scripter 2020" }, { "code": null, "e": 2409, "s": 2404, "text": "HTML" }, { "code": null, "e": 2420, "s": 2409, "text": "JavaScript" }, { "code": null, "e": 2439, "s": 2420, "text": "Technical Scripter" }, { "code": null, "e": 2456, "s": 2439, "text": "Web Technologies" }, { "code": null, "e": 2461, "s": 2456, "text": "HTML" } ]
Birthday Reminder Application in Python
In this section we will see how to create a birthday reminder application using Python. Create an application using Python, which can check whether there is any birthday on the current day or not. If it is the birthday of some listed person, send a notification to the System with the name of that person. We need a file, where we can store the date and month and the name of the person as a lookup file for this application. The file will look like this − Here we will convert this application to a start-up application to start when the system starts. Steps to create Birthday Reminder Application Take the lookup file and read from it. Whether the date and month is matched with the current date and month Send notification to the system with all of the names whose birthday is today. Send notification to the system with all of the names whose birthday is today. Stop importos, time #Take the birthday lookup file from home directory file_path = os.getenv('HOME') + '/birth_day_lookup.txt' defcheck_birthday(): lookup_file = open(file_path, 'r') #open the lookup file as read mode today = time.strftime('%d-%B') #get the todays date as dd-Month format bday_flag = 0 #loop through each entry in the birthday file, and check whether the day is present or not for entry inlookup_file: if today in entry: line = entry.split(' ') #cut the line on spaces to get name and surname bday_flag = 1 os.system('notify-send "Today is '+line[1]+' '+line[2]+'\'s Birthday"') ifbday_flag == 0: os.system('notify-send "No birthday for today is listed"') check_birthday() Step 1 − Convert the script file as executable file by using the chmod command sudochmod +x file_name.py Step 2 − Move the script file to /usr/bin directory. sudocp file_name.py /usr/bin Step 3 − Now search for the Startup Applications, and start it. After opening the application go to add, and give desired name, then the program name in the command field. And add as startup application.
[ { "code": null, "e": 1150, "s": 1062, "text": "In this section we will see how to create a birthday reminder application using Python." }, { "code": null, "e": 1368, "s": 1150, "text": "Create an application using Python, which can check whether there is any birthday on the current day or not. If it is the birthday of some listed person, send a notification to the System with the name of that person." }, { "code": null, "e": 1519, "s": 1368, "text": "We need a file, where we can store the date and month and the name of the person as a lookup file for this application. The file will look like this −" }, { "code": null, "e": 1616, "s": 1519, "text": "Here we will convert this application to a start-up application to start when the system starts." }, { "code": null, "e": 1662, "s": 1616, "text": "Steps to create Birthday Reminder Application" }, { "code": null, "e": 1701, "s": 1662, "text": "Take the lookup file and read from it." }, { "code": null, "e": 1853, "s": 1701, "text": "Whether the date and month is matched with the current date and month\n\nSend notification to the system with all of the names whose birthday is today.\n\n" }, { "code": null, "e": 1932, "s": 1853, "text": "Send notification to the system with all of the names whose birthday is today." }, { "code": null, "e": 1937, "s": 1932, "text": "Stop" }, { "code": null, "e": 2679, "s": 1937, "text": "importos, time\n#Take the birthday lookup file from home directory\nfile_path = os.getenv('HOME') + '/birth_day_lookup.txt'\ndefcheck_birthday():\n lookup_file = open(file_path, 'r') #open the lookup file as read mode\n today = time.strftime('%d-%B') #get the todays date as dd-Month format\n bday_flag = 0\n #loop through each entry in the birthday file, and check whether the day is present or not\n for entry inlookup_file:\n if today in entry:\n line = entry.split(' ') #cut the line on spaces to get name and surname\n bday_flag = 1\n os.system('notify-send \"Today is '+line[1]+' '+line[2]+'\\'s Birthday\"')\n ifbday_flag == 0:\n os.system('notify-send \"No birthday for today is listed\"')\ncheck_birthday()" }, { "code": null, "e": 2758, "s": 2679, "text": "Step 1 − Convert the script file as executable file by using the chmod command" }, { "code": null, "e": 2785, "s": 2758, "text": "sudochmod +x file_name.py\n" }, { "code": null, "e": 2838, "s": 2785, "text": "Step 2 − Move the script file to /usr/bin directory." }, { "code": null, "e": 2868, "s": 2838, "text": "sudocp file_name.py /usr/bin\n" }, { "code": null, "e": 2932, "s": 2868, "text": "Step 3 − Now search for the Startup Applications, and start it." }, { "code": null, "e": 3072, "s": 2932, "text": "After opening the application go to add, and give desired name, then the program name in the command field. And add as startup application." } ]
Difference Between Friend Function and Virtual Function in C++ - GeeksforGeeks
12 Mar, 2021 A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and include object/s as arguments. It is mostly used for overloading <<and>> for I/O. It can generally access any member of the class to which it is friend. Illustration: class GFG { private: { Public: { friend void check(); } void check(); Now coming onto the second function is a virtual function. So a virtual function is basically a member function of a class that is declared within the base class. In this, a virtual keyword is used to make member function of base class Virtual. It also supports polymorphism at both compile-time and run time. It also allows derived class to simply replace implementation that is provided or given by the base class. Illustration: class GFG { Public: Virtual return_type function_name(arguments) { ..... } }: class A { By far we are clear with discussing friend function and virtual function, now let us see the major differences between them even to grasp a good grip over it. Friend Function Virtual Function C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference Between == and .equals() Method in Java
[ { "code": null, "e": 24098, "s": 24070, "text": "\n12 Mar, 2021" }, { "code": null, "e": 24604, "s": 24098, "text": "A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and include object/s as arguments. It is mostly used for overloading <<and>> for I/O. It can generally access any member of the class to which it is friend. " }, { "code": null, "e": 24619, "s": 24604, "text": "Illustration: " }, { "code": null, "e": 24711, "s": 24619, "text": "class GFG \n{ \n private: \n { \n Public: \n { \n friend void check(); \n }\n \nvoid check(); " }, { "code": null, "e": 25130, "s": 24711, "text": "Now coming onto the second function is a virtual function. So a virtual function is basically a member function of a class that is declared within the base class. In this, a virtual keyword is used to make member function of base class Virtual. It also supports polymorphism at both compile-time and run time. It also allows derived class to simply replace implementation that is provided or given by the base class. " }, { "code": null, "e": 25146, "s": 25130, "text": "Illustration: " }, { "code": null, "e": 25296, "s": 25146, "text": "class GFG \n{ \nPublic: \n Virtual return_type function_name(arguments) \n { \n ..... \n } \n}: \n class A \n { " }, { "code": null, "e": 25455, "s": 25296, "text": "By far we are clear with discussing friend function and virtual function, now let us see the major differences between them even to grasp a good grip over it." }, { "code": null, "e": 25472, "s": 25455, "text": "Friend Function " }, { "code": null, "e": 25490, "s": 25472, "text": "Virtual Function " }, { "code": null, "e": 25494, "s": 25490, "text": "C++" }, { "code": null, "e": 25513, "s": 25494, "text": "Difference Between" }, { "code": null, "e": 25517, "s": 25513, "text": "CPP" }, { "code": null, "e": 25615, "s": 25517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25643, "s": 25615, "text": "Operator Overloading in C++" }, { "code": null, "e": 25663, "s": 25643, "text": "Polymorphism in C++" }, { "code": null, "e": 25687, "s": 25663, "text": "Sorting a vector in C++" }, { "code": null, "e": 25720, "s": 25687, "text": "Friend class and function in C++" }, { "code": null, "e": 25764, "s": 25720, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 25795, "s": 25764, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25835, "s": 25795, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25867, "s": 25835, "text": "Differences between TCP and UDP" }, { "code": null, "e": 25928, "s": 25867, "text": "Difference between var, let and const keywords in JavaScript" } ]
Java Program to convert positive int to negative and negative to positive
To convert positive int to negative and vice-versa, use the Bitwise Complement Operator. Let us first initialize a positive int − int positiveVal = 200; Now, let us convert it to negative − int negativeVal = (~(positiveVal - 1)); Now, let’s say we have the following negative int − int negativeVal = -300; The following will convert the negative to positive int − positiveVal = ~(negativeVal - 1); Live Demo public class Demo { public static void main(String[] args) throws java.lang.Exception { int positiveVal = 100; int negativeVal = (~(positiveVal - 1)); System.out.println("Result: Positive value converted to Negative = "+negativeVal); positiveVal = ~(negativeVal - 1); System.out.println("Actual Positive Value = "+positiveVal); negativeVal = -200; System.out.println("Actual Negative Value = "+negativeVal); positiveVal = ~(negativeVal - 1); System.out.println("Result: Negative value converted to Positive = "+positiveVal); } } Result: Positive value converted to Negative = -100 Actual Positive Value = 100 Actual Negative Value = -200 Result: Negative value converted to Positive = 200
[ { "code": null, "e": 1151, "s": 1062, "text": "To convert positive int to negative and vice-versa, use the Bitwise Complement Operator." }, { "code": null, "e": 1192, "s": 1151, "text": "Let us first initialize a positive int −" }, { "code": null, "e": 1215, "s": 1192, "text": "int positiveVal = 200;" }, { "code": null, "e": 1252, "s": 1215, "text": "Now, let us convert it to negative −" }, { "code": null, "e": 1292, "s": 1252, "text": "int negativeVal = (~(positiveVal - 1));" }, { "code": null, "e": 1344, "s": 1292, "text": "Now, let’s say we have the following negative int −" }, { "code": null, "e": 1368, "s": 1344, "text": "int negativeVal = -300;" }, { "code": null, "e": 1426, "s": 1368, "text": "The following will convert the negative to positive int −" }, { "code": null, "e": 1460, "s": 1426, "text": "positiveVal = ~(negativeVal - 1);" }, { "code": null, "e": 1471, "s": 1460, "text": " Live Demo" }, { "code": null, "e": 2060, "s": 1471, "text": "public class Demo {\n public static void main(String[] args) throws java.lang.Exception {\n int positiveVal = 100;\n int negativeVal = (~(positiveVal - 1));\n System.out.println(\"Result: Positive value converted to Negative = \"+negativeVal);\n positiveVal = ~(negativeVal - 1);\n System.out.println(\"Actual Positive Value = \"+positiveVal);\n negativeVal = -200;\n System.out.println(\"Actual Negative Value = \"+negativeVal);\n positiveVal = ~(negativeVal - 1);\n System.out.println(\"Result: Negative value converted to Positive = \"+positiveVal);\n }\n}" }, { "code": null, "e": 2220, "s": 2060, "text": "Result: Positive value converted to Negative = -100\nActual Positive Value = 100\nActual Negative Value = -200\nResult: Negative value converted to Positive = 200" } ]
How to get the index of selected option in Tkinter Combobox?
If you want to create a dropdown list of items and enable the items of list to be selected by the user, then you can use the Combobox widget. The Combobox widget allows you to create a dropdown list in which the list of items can be selected instantly. However, if you want to get the index of selected items in the combobox widget, then you can use the get() method. The get() method returns an integer of the selected item known as the index of the item. Let’s take an example to see how it works. In this example, we have created a list of days of weeks in a dropdown list and whenever the user selects a day from the dropdown list, it will print and display the index of selected item on a Label widget. To print the index, we can concatenate the string by typecasting the given index into string. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Create a function to clear the combobox def clear_cb(): cb.set('') # Define Days Tuple days= ('Sun','Mon','Tue','Wed','Thu','Fri','Sat') # Function to print the index of selected option in Combobox def callback(*arg): Label(win, text= "The value at index " + str(cb.current()) + " is" + " "+ str(var.get()), font= ('Helvetica 12')).pack() # Create a combobox widget var= StringVar() cb= ttk.Combobox(win, textvariable= var) cb['values']= days cb['state']= 'readonly' cb.pack(fill='x',padx= 5, pady=5) # Set the tracing for the given variable var.trace('w', callback) # Create a button to clear the selected combobox text value button= Button(win, text= "Clear", command= clear_cb) button.pack() win.mainloop() Running the above code will display a combobox widget with a list of days. Whenever you select a day from the list, it will print the index and the corresponding item on the label widget.
[ { "code": null, "e": 1519, "s": 1062, "text": "If you want to create a dropdown list of items and enable the items of list to be selected by the user, then you can use the Combobox widget. The Combobox widget allows you to create a dropdown list in which the list of items can be selected instantly. However, if you want to get the index of selected items in the combobox widget, then you can use the get() method. The get() method returns an integer of the selected item known as the index of the item." }, { "code": null, "e": 1864, "s": 1519, "text": "Let’s take an example to see how it works. In this example, we have created a list of days of weeks in a dropdown list and whenever the user selects a day from the dropdown list, it will print and display the index of selected item on a Label widget. To print the index, we can concatenate the string by typecasting the given index into string." }, { "code": null, "e": 2787, "s": 1864, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a function to clear the combobox\ndef clear_cb():\n cb.set('')\n \n# Define Days Tuple\ndays= ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')\n\n# Function to print the index of selected option in Combobox\ndef callback(*arg):\n Label(win, text= \"The value at index \" + str(cb.current()) + \" is\" + \" \"+ str(var.get()), font= ('Helvetica 12')).pack()\n \n# Create a combobox widget\nvar= StringVar()\ncb= ttk.Combobox(win, textvariable= var)\ncb['values']= days\ncb['state']= 'readonly'\ncb.pack(fill='x',padx= 5, pady=5)\n\n# Set the tracing for the given variable\nvar.trace('w', callback)\n\n# Create a button to clear the selected combobox text value\nbutton= Button(win, text= \"Clear\", command= clear_cb)\nbutton.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2975, "s": 2787, "text": "Running the above code will display a combobox widget with a list of days. Whenever you select a day from the list, it will print the index and the corresponding item on the label widget." } ]
Time & Work - Solved Examples
Q 1 - A can do a bit of work in 8 days, which B alone can do in 10 days in how long . In how long both cooperating can do it? A - 40/9 days B - 41/9 days C - 42/9 days D - 43/9 days Answer - A Explanation A's 1 day work= 1/8, B`s 1 day work = 1/10 ∴ (A+B) 1 day work = (1/8+1/10) = 9/40 Both cooperating can complete it in 40/9 days. Q 2 - A and B together can dive a trench in 12 days, which an alone can dive in 30 days. In how long B alone can burrow it? A - 18 days B - 19 days C - 20 days D - 21 days Answer - C Explanation (A+B)'s 1 day work = 1/12, A's 1 day work =1/30 ∴ B's 1 day work = (1/12-1/30) = 3/60 = 1/20 Henceforth, B alone can dive the trench in 20 days. Q 3 - A can do a bit of work in 25 days which B can complete in 20 days. Both together labor for 5 days and afterward A leaves off. How long will B take to complete the remaining work? A - 7 days B - 8 days C - 9 days D - 11 days Answer - D Explanation (A+B)'s 5 days work = 5(1/25+1/20) = (5*9/100) = 9/20 Remaining work = (1-9/20) = 11/20 1/20 work is finished by B in 1 day 11/20 work is finished by B in (1*20*11/20) = 11 days Q 4 - A and B can do a bit of work in 12 days. B and C can do it in 15 days while C and A can do it in 20 days. In how long will they complete it cooperating? Additionally, in how long can A alone do it? A - 10 days, 30 days. B - 15 days, 20 days. C - 20 days, 40 days. D - 10 days, 50 days. Answer - A Explanation (A+B)'s 1 day work = 1/12, (B+C)'s 1 day work = 1/15, (C+A)'S 1 day work = 1/20 Including: 2(A+B+C)'s 1 day work = (1/12+ 1/15+ 1/20)= 12/60 = 1/5 ∴ (A+B+C) `s 1 day work = (1/2 *1/5) = 1/10 ∴ working together they can complete the work in 10 days. A's 1 day work = (1/10-1/15) = 1/30, B`s 1 day work = (1/10-1/20) = 1/20 C's 1 day work = (1/10-1/12) = 1/60 ∴ A alone can take the necessary steps in 30 days. Q 5 - A can fabricate a divider in 30 days , while B alone can assemble it in 40 days, If they construct it together and get an installment of RS. 7000, what B's offer? A - 2000 B - 3000 C - 4000 D - 6500 Answer - B Explanation A's 1 days work = 1/30, B's 1 day work = 1/40, Proportion of their shares = 1/30:1/40 = 4:3 B's offer = (7000*3/7) = Rs. 3000 Q 6 - A can do a bit of work in 10 days while B alone can do it in 15 days. They cooperate for 5 days and whatever remains of the work is finished by C in 2 days. On the off chance that they get Rs. 4500 for the entire work, by what means if they partition the cash? A - Rs 1250, Rs 1200, Rs 550 B - Rs 2250, Rs 1500, Rs 750 C - Rs 1050, Rs 1000, Rs 500 D - Rs 650, Rs 700, Rs 500 Answer - B Explanation (A+B)'s 5 days work = 5(1/10+ 1/15)= (5* 1/6)= 5/6 Remaining work = (1-5/6) = 1/6 C's 2 days work = 1/6 (A's 5 day work): (B's 5 day work): (C's 2 days work) = 5/10: 5/15: 1/6 = 15: 10:5 = 3:2:1 A's offer = (4500*3/6) = Rs. 2250 B's offer = (4500*2/6) = Rs. 1500 C's share= (4500*1/6) = Rs. 750 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4018, "s": 3892, "text": "Q 1 - A can do a bit of work in 8 days, which B alone can do in 10 days in how long . In how long both cooperating can do it?" }, { "code": null, "e": 4032, "s": 4018, "text": "A - 40/9 days" }, { "code": null, "e": 4046, "s": 4032, "text": "B - 41/9 days" }, { "code": null, "e": 4060, "s": 4046, "text": "C - 42/9 days" }, { "code": null, "e": 4074, "s": 4060, "text": "D - 43/9 days" }, { "code": null, "e": 4085, "s": 4074, "text": "Answer - A" }, { "code": null, "e": 4097, "s": 4085, "text": "Explanation" }, { "code": null, "e": 4227, "s": 4097, "text": "A's 1 day work= 1/8, B`s 1 day work = 1/10\n∴ (A+B) 1 day work = (1/8+1/10) = 9/40\nBoth cooperating can complete it in 40/9 days.\n" }, { "code": null, "e": 4351, "s": 4227, "text": "Q 2 - A and B together can dive a trench in 12 days, which an alone can dive in 30 days. In how long B alone can burrow it?" }, { "code": null, "e": 4363, "s": 4351, "text": "A - 18 days" }, { "code": null, "e": 4375, "s": 4363, "text": "B - 19 days" }, { "code": null, "e": 4387, "s": 4375, "text": "C - 20 days" }, { "code": null, "e": 4399, "s": 4387, "text": "D - 21 days" }, { "code": null, "e": 4410, "s": 4399, "text": "Answer - C" }, { "code": null, "e": 4422, "s": 4410, "text": "Explanation" }, { "code": null, "e": 4571, "s": 4422, "text": "(A+B)'s 1 day work = 1/12, A's 1 day work =1/30 \n∴ B's 1 day work = (1/12-1/30) = 3/60 = 1/20 \nHenceforth, B alone can dive the trench in 20 days. \n" }, { "code": null, "e": 4756, "s": 4571, "text": "Q 3 - A can do a bit of work in 25 days which B can complete in 20 days. Both together labor for 5 days and afterward A leaves off. How long will B take to complete the remaining work?" }, { "code": null, "e": 4767, "s": 4756, "text": "A - 7 days" }, { "code": null, "e": 4778, "s": 4767, "text": "B - 8 days" }, { "code": null, "e": 4789, "s": 4778, "text": "C - 9 days" }, { "code": null, "e": 4801, "s": 4789, "text": "D - 11 days" }, { "code": null, "e": 4812, "s": 4801, "text": "Answer - D" }, { "code": null, "e": 4824, "s": 4812, "text": "Explanation" }, { "code": null, "e": 5006, "s": 4824, "text": "(A+B)'s 5 days work = 5(1/25+1/20) = (5*9/100) = 9/20 \nRemaining work = (1-9/20) = 11/20 \n1/20 work is finished by B in 1 day \n11/20 work is finished by B in (1*20*11/20) = 11 days\n" }, { "code": null, "e": 5210, "s": 5006, "text": "Q 4 - A and B can do a bit of work in 12 days. B and C can do it in 15 days while C and A can do it in 20 days. In how long will they complete it cooperating? Additionally, in how long can A alone do it?" }, { "code": null, "e": 5232, "s": 5210, "text": "A - 10 days, 30 days." }, { "code": null, "e": 5254, "s": 5232, "text": "B - 15 days, 20 days." }, { "code": null, "e": 5276, "s": 5254, "text": "C - 20 days, 40 days." }, { "code": null, "e": 5298, "s": 5276, "text": "D - 10 days, 50 days." }, { "code": null, "e": 5309, "s": 5298, "text": "Answer - A" }, { "code": null, "e": 5321, "s": 5309, "text": "Explanation" }, { "code": null, "e": 5738, "s": 5321, "text": "(A+B)'s 1 day work = 1/12, \n(B+C)'s 1 day work = 1/15,\n(C+A)'S 1 day work = 1/20 \nIncluding: 2(A+B+C)'s 1 day work = (1/12+ 1/15+ 1/20)= 12/60 = 1/5 \n∴ (A+B+C) `s 1 day work = (1/2 *1/5) = 1/10 \n∴ working together they can complete the work in 10 days. \nA's 1 day work = (1/10-1/15) = 1/30, B`s 1 day work = (1/10-1/20) = 1/20 \nC's 1 day work = (1/10-1/12) = 1/60 \n∴ A alone can take the necessary steps in 30 days.\n" }, { "code": null, "e": 5907, "s": 5738, "text": "Q 5 - A can fabricate a divider in 30 days , while B alone can assemble it in 40 days, If they construct it together and get an installment of RS. 7000, what B's offer?" }, { "code": null, "e": 5916, "s": 5907, "text": "A - 2000" }, { "code": null, "e": 5925, "s": 5916, "text": "B - 3000" }, { "code": null, "e": 5934, "s": 5925, "text": "C - 4000" }, { "code": null, "e": 5943, "s": 5934, "text": "D - 6500" }, { "code": null, "e": 5954, "s": 5943, "text": "Answer - B" }, { "code": null, "e": 5966, "s": 5954, "text": "Explanation" }, { "code": null, "e": 6093, "s": 5966, "text": "A's 1 days work = 1/30,\nB's 1 day work = 1/40,\nProportion of their shares = 1/30:1/40 = 4:3\nB's offer = (7000*3/7) = Rs. 3000\n" }, { "code": null, "e": 6360, "s": 6093, "text": "Q 6 - A can do a bit of work in 10 days while B alone can do it in 15 days. They cooperate for 5 days and whatever remains of the work is finished by C in 2 days. On the off chance that they get Rs. 4500 for the entire work, by what means if they partition the cash?" }, { "code": null, "e": 6390, "s": 6360, "text": "A - Rs 1250, Rs 1200, Rs 550" }, { "code": null, "e": 6419, "s": 6390, "text": "B - Rs 2250, Rs 1500, Rs 750" }, { "code": null, "e": 6448, "s": 6419, "text": "C - Rs 1050, Rs 1000, Rs 500" }, { "code": null, "e": 6475, "s": 6448, "text": "D - Rs 650, Rs 700, Rs 500" }, { "code": null, "e": 6486, "s": 6475, "text": "Answer - B" }, { "code": null, "e": 6498, "s": 6486, "text": "Explanation" }, { "code": null, "e": 6801, "s": 6498, "text": "(A+B)'s 5 days work = 5(1/10+ 1/15)= (5* 1/6)= 5/6 \nRemaining work = (1-5/6) = 1/6 \nC's 2 days work = 1/6 \n(A's 5 day work): (B's 5 day work): (C's 2 days work) \n= 5/10: 5/15: 1/6 \n= 15: 10:5 = 3:2:1 \nA's offer = (4500*3/6) = Rs. 2250\nB's offer = (4500*2/6) = Rs. 1500 \nC's share= (4500*1/6) = Rs. 750\n" }, { "code": null, "e": 6837, "s": 6801, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 6855, "s": 6837, "text": " Programming Line" }, { "code": null, "e": 6862, "s": 6855, "text": " Print" }, { "code": null, "e": 6873, "s": 6862, "text": " Add Notes" } ]
How to create our own Listener interface in android?
This example demonstrate about How to create our own Listener interface in android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/text" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:text = "click" android:textSize = "30sp" /> </LinearLayout> In the above code, we have taken text view to show listener data. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends FragmentActivity implements sampleInterFace { sampleInterFace interFace; TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); this.interFace = (sampleInterFace) this; interFace.sample("sairamkrishna Mammahe"); } @Override public void sample(String text) { textView.setText(text); } } interface sampleInterFace { public void sample(String 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": 1145, "s": 1062, "text": "This example demonstrate about How to create our own Listener interface in android" }, { "code": null, "e": 1274, "s": 1145, "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": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1820, "s": 1339, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:orientation = \"vertical\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:text = \"click\"\n android:textSize = \"30sp\" />\n</LinearLayout>" }, { "code": null, "e": 1886, "s": 1820, "text": "In the above code, we have taken text view to show listener data." }, { "code": null, "e": 1943, "s": 1886, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2692, "s": 1943, "text": "package com.example.myapplication;\nimport android.os.Bundle;\nimport android.support.v4.app.FragmentActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends FragmentActivity implements sampleInterFace {\n sampleInterFace interFace;\n TextView textView;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n this.interFace = (sampleInterFace) this;\n interFace.sample(\"sairamkrishna Mammahe\");\n }\n @Override\n public void sample(String text) {\n textView.setText(text);\n }\n}\ninterface sampleInterFace {\n public void sample(String text);\n}" }, { "code": null, "e": 3039, "s": 2692, "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 –" } ]
How to Use Selenium to Web-Scrape with Example | by Bryan Pfalzgraf | Towards Data Science
Selenium is a Python library and tool used for automating web browsers to do a number of tasks. One of such is web-scraping to extract useful data and information that may be otherwise unavailable. Here’s a step-by-step guide on how to use Selenium with the example being extracting NBA player salary data from the website https://hoopshype.com/salaries/players/. pip install selenium Once installed, you’re ready for the imports. from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport pandas as pd A webdriver is a vital ingredient to this process. It is what will actually be automatically opening up your browser to access your website of choice. This step is different based on which browser you use to explore the internet. I happen to use Google Chrome. Some say Chrome works best with Selenium, although it does also support Internet Explorer, Firefox, Safari, and Opera. For chrome you first need to download the webdriver at https://chromedriver.chromium.org/downloads. There are several different download options based on your version of Chrome. To locate what version of Chrome you have, click on the 3 vertical dots at the top right corner of your browser window, scroll down to help, and select “About Google Chrome”. There you will see your version. I have version 80.0.3987.149, shown in the screenshots below. Now you need to know where you saved your webdriver download on your local computer. Mine is just saved in my default downloads folder. You now can create a driver variable using the direct path of the location of your downloaded webdriver. driver = webdriver.Chrome('/Users/MyUsername/Downloads/chromedriver') Very simple yet very important step. You need your code to actually open the website you’re attempting to scrape. driver.get('https://hoopshype.com/salaries/players/') When run, this code snippet will open the browser to your desired website. In order to extract the information that you’re looking to scrape, you need to locate the element’s XPath. An XPath is a syntax used for finding any element on a webpage. To locate the element’s XPath, highlight the first in the list of what you’re looking for, right click, and select inspect; this opens up the developer tools. For my example, I first want to locate the NBA player names, so I first select Stephen Curry. In the developer tools, we now see the element “Stephen Curry” appears as such. <td class=”name”> <a href=”https://hoopshype.com/player/stephen-curry/salary/"> Stephen Curry </a> </td> This element can easily be translated to its XPath, but first, we need to remember that we aren’t just trying to locate this element, but all player names. Using the same process, I located the next element in the list, Russell Westbrook. <td class=”name”> <a href=”https://hoopshype.com/player/russell-westbrook/salary/"> Russell Westbrook </a> </td> The commonality between these two (and all other player names) is <td class=”name”>, so that is what we will be using to create a list of all player names. That translated into an XPath looks like //td[@class=”name”]. Breaking that down, all XPaths are preceded by the double slash, which we want in a td tag, with each class in that td tag needing to correspond to “name”. We now can create the list of player names with this Selenium function. players = driver.find_elements_by_xpath('//td[@class="name"]') And now to get the text of each player name into a list, we write this function. players_list = []for p in range(len(players)): players_list.append(players[p].text) Following this same process to acquire the player salaries... Stephen Curry’s 2019/20 Salary <td style=”color:black” class=”hh-salaries-sorted” data-value=”40231758"> $40,231,758 </td> Russel Westbrook’s 2019/20 Salary <td style=”color:black” class=”hh-salaries-sorted” data-value=”38506482"> $38,506,482 </td> While inspecting these elements and translating to XPath, we can ignore style and data-value, only worrying about the class. salaries = driver.find_elements_by_xpath('//td[@class="hh-salaries-sorted"]') And the list of salaries text... salaries_list = []for s in range(len(salaries)): salaries_list.append(salaries[s].text) Often, when using Selenium, you’ll be attempting to retrieve data that is located on multiple different pages from the same website. In my example, hoopshype.com has NBA salary data dating back to the 1990/91 season. As you can see, the difference between the URL of each season is just a matter of the years being included at the end. So the URL for the 2018/19 season is https://hoopshype.com/salaries/players/2018-2019/ and the URL for the 1990/91 season is https://hoopshype.com/salaries/players/1990-1991/. With that, we can create a function that loops through each year and accesses each URL individually and then puts all of the steps we’ve previously shown together for each year individually. I also pair each player with their salary for that season together, place into a temporary dataframe, add the year onto that temporary dataframe, and then add this temporary dataframe to a master dataframe that includes all of the data we’ve acquired. The final code is below!
[ { "code": null, "e": 535, "s": 171, "text": "Selenium is a Python library and tool used for automating web browsers to do a number of tasks. One of such is web-scraping to extract useful data and information that may be otherwise unavailable. Here’s a step-by-step guide on how to use Selenium with the example being extracting NBA player salary data from the website https://hoopshype.com/salaries/players/." }, { "code": null, "e": 556, "s": 535, "text": "pip install selenium" }, { "code": null, "e": 602, "s": 556, "text": "Once installed, you’re ready for the imports." }, { "code": null, "e": 699, "s": 602, "text": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport pandas as pd" }, { "code": null, "e": 1527, "s": 699, "text": "A webdriver is a vital ingredient to this process. It is what will actually be automatically opening up your browser to access your website of choice. This step is different based on which browser you use to explore the internet. I happen to use Google Chrome. Some say Chrome works best with Selenium, although it does also support Internet Explorer, Firefox, Safari, and Opera. For chrome you first need to download the webdriver at https://chromedriver.chromium.org/downloads. There are several different download options based on your version of Chrome. To locate what version of Chrome you have, click on the 3 vertical dots at the top right corner of your browser window, scroll down to help, and select “About Google Chrome”. There you will see your version. I have version 80.0.3987.149, shown in the screenshots below." }, { "code": null, "e": 1768, "s": 1527, "text": "Now you need to know where you saved your webdriver download on your local computer. Mine is just saved in my default downloads folder. You now can create a driver variable using the direct path of the location of your downloaded webdriver." }, { "code": null, "e": 1838, "s": 1768, "text": "driver = webdriver.Chrome('/Users/MyUsername/Downloads/chromedriver')" }, { "code": null, "e": 1952, "s": 1838, "text": "Very simple yet very important step. You need your code to actually open the website you’re attempting to scrape." }, { "code": null, "e": 2006, "s": 1952, "text": "driver.get('https://hoopshype.com/salaries/players/')" }, { "code": null, "e": 2081, "s": 2006, "text": "When run, this code snippet will open the browser to your desired website." }, { "code": null, "e": 2505, "s": 2081, "text": "In order to extract the information that you’re looking to scrape, you need to locate the element’s XPath. An XPath is a syntax used for finding any element on a webpage. To locate the element’s XPath, highlight the first in the list of what you’re looking for, right click, and select inspect; this opens up the developer tools. For my example, I first want to locate the NBA player names, so I first select Stephen Curry." }, { "code": null, "e": 2585, "s": 2505, "text": "In the developer tools, we now see the element “Stephen Curry” appears as such." }, { "code": null, "e": 2690, "s": 2585, "text": "<td class=”name”> <a href=”https://hoopshype.com/player/stephen-curry/salary/\"> Stephen Curry </a> </td>" }, { "code": null, "e": 2929, "s": 2690, "text": "This element can easily be translated to its XPath, but first, we need to remember that we aren’t just trying to locate this element, but all player names. Using the same process, I located the next element in the list, Russell Westbrook." }, { "code": null, "e": 3042, "s": 2929, "text": "<td class=”name”> <a href=”https://hoopshype.com/player/russell-westbrook/salary/\"> Russell Westbrook </a> </td>" }, { "code": null, "e": 3488, "s": 3042, "text": "The commonality between these two (and all other player names) is <td class=”name”>, so that is what we will be using to create a list of all player names. That translated into an XPath looks like //td[@class=”name”]. Breaking that down, all XPaths are preceded by the double slash, which we want in a td tag, with each class in that td tag needing to correspond to “name”. We now can create the list of player names with this Selenium function." }, { "code": null, "e": 3551, "s": 3488, "text": "players = driver.find_elements_by_xpath('//td[@class=\"name\"]')" }, { "code": null, "e": 3632, "s": 3551, "text": "And now to get the text of each player name into a list, we write this function." }, { "code": null, "e": 3719, "s": 3632, "text": "players_list = []for p in range(len(players)): players_list.append(players[p].text)" }, { "code": null, "e": 3781, "s": 3719, "text": "Following this same process to acquire the player salaries..." }, { "code": null, "e": 3812, "s": 3781, "text": "Stephen Curry’s 2019/20 Salary" }, { "code": null, "e": 3904, "s": 3812, "text": "<td style=”color:black” class=”hh-salaries-sorted” data-value=”40231758\"> $40,231,758 </td>" }, { "code": null, "e": 3938, "s": 3904, "text": "Russel Westbrook’s 2019/20 Salary" }, { "code": null, "e": 4030, "s": 3938, "text": "<td style=”color:black” class=”hh-salaries-sorted” data-value=”38506482\"> $38,506,482 </td>" }, { "code": null, "e": 4155, "s": 4030, "text": "While inspecting these elements and translating to XPath, we can ignore style and data-value, only worrying about the class." }, { "code": null, "e": 4233, "s": 4155, "text": "salaries = driver.find_elements_by_xpath('//td[@class=\"hh-salaries-sorted\"]')" }, { "code": null, "e": 4266, "s": 4233, "text": "And the list of salaries text..." }, { "code": null, "e": 4357, "s": 4266, "text": "salaries_list = []for s in range(len(salaries)): salaries_list.append(salaries[s].text)" }, { "code": null, "e": 4574, "s": 4357, "text": "Often, when using Selenium, you’ll be attempting to retrieve data that is located on multiple different pages from the same website. In my example, hoopshype.com has NBA salary data dating back to the 1990/91 season." } ]
Interactive Visualizations with Plotly | by Soner Yıldırım | Towards Data Science
Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). It allows to create interactive visualizations that can be displayed in Jupyter notebooks. It can be installed using pip or conda: $ pip install plotly==4.8.0$ conda install -c plotly plotly=4.8.0 There are basically two ways to create figures with plotly.py: Figures as dictionaries Figures as graph objects In this post, we will go through how to create many different kind of plots using graph objects. After installation, we can import graph objects: import plotly.graph_objects as go There are different ways to create graph object figures. One way is to use Figure constructor of graph objects. Let’s create a simple scatter plot: import numpy as npa=np.random.random(10)b=np.random.randint(10, size=10)fig = go.Figure(data=go.Scatter(x=a, y=b, mode='markers'))fig.show() We can also add additional traces on the same figure using add_trace: fig = go.Figure(data=go.Scatter(x=np.arange(9), y=10*np.random.randn(10),mode='markers', name='markers'))fig.add_trace(go.Scatter(x=np.arange(9), y=np.random.randn(10),mode='lines+markers', name='lines+markers'))fig.show() Another way to create figures is plotly express which is a high level API to produce graph object figures. We can import it with the following line of code: import plotly.express as px Let’s create a sample dataframe: import pandas as pddf = pd.DataFrame({'col_a':np.random.random(10)*5,'col_b':np.random.randint(10, size=10),'col_c':[4.5, 4.7, 4.8, 3.4, 3.7, 4., 5.1, 3.2, 4.4, 3.3],'col_d':['a','a','b','a','a','b','b','c','c','c']})df We can have an idea about the whole dataframe on one scatter plot: fig = px.scatter(df, x="col_a", y="col_b", color="col_d", size='col_c')fig.show() X axis represents “col_a” and y axis represents “col_b”. The size of the markers gives an idea about “col_c” whereas the color of markers represents the information in “col_d”. Thus, one scatter plot is able to tell us a lot about the dataset. Each dot (or marker) represent a row in the dataframe and we can hover on individual data points to see the values of all columns. This was a simple and random dataset. When we work with real datasets, the features of plotly interactive visulizations become more helpful. Plotly contains the famous iris dataset that we can access with one line of code: df_iris = px.data.iris()fig = px.scatter(df_iris, x="sepal_width", y="sepal_length", color="species",size='petal_length', hover_data=['petal_width'])fig.show() The scatter plot above tells us how different species are grouped together as well as the variances within species. It is also possible to represent different species in separate subplots. All we need to do is add facet_col or facet_row parameters. As the names suggest, facet_col creates subplots as columns and facet_row creates subplots as rows. fig = px.scatter(df_iris, x="sepal_width", y="sepal_length", color="species", facet_col="species", title="Species Subplots")fig.show() fig = px.scatter(df_iris, x="sepal_width", y="sepal_length", color="species", facet_row="species", title="Species Subplots")fig.show() After a figure is rendered, we can update the layout using update_layout(). Consider the following figure: We can update the font size of title with the following code: fig.update_layout(title_text="Sample Dataset - Updated", title_font_size=20) Another way to create subplots is to use make_subplots: from plotly.subplots import make_subplotsfig = make_subplots(rows=1, cols=2)fig.add_scatter(y=np.random.random(10), mode="markers", marker=dict(size=15, color="Blue"), name="A", row=1, col=1)fig.add_bar(y=np.random.randint(10, size=10), marker=dict(color="LightBlue"), name="B", row=1, col=2)fig.show() We specified the number of subplots and their positions using rows and cols parameters. Then we add the define the plots and specify the position. We can also specify the size and color of markers by passing a dictionary to marker parameter. The figure that is produced with the code segment above is: We have covered some basic components of plotly.py library. Of course, this is just a little of what can be done with plotly. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 404, "s": 172, "text": "Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js). It allows to create interactive visualizations that can be displayed in Jupyter notebooks. It can be installed using pip or conda:" }, { "code": null, "e": 470, "s": 404, "text": "$ pip install plotly==4.8.0$ conda install -c plotly plotly=4.8.0" }, { "code": null, "e": 533, "s": 470, "text": "There are basically two ways to create figures with plotly.py:" }, { "code": null, "e": 557, "s": 533, "text": "Figures as dictionaries" }, { "code": null, "e": 582, "s": 557, "text": "Figures as graph objects" }, { "code": null, "e": 728, "s": 582, "text": "In this post, we will go through how to create many different kind of plots using graph objects. After installation, we can import graph objects:" }, { "code": null, "e": 762, "s": 728, "text": "import plotly.graph_objects as go" }, { "code": null, "e": 910, "s": 762, "text": "There are different ways to create graph object figures. One way is to use Figure constructor of graph objects. Let’s create a simple scatter plot:" }, { "code": null, "e": 1051, "s": 910, "text": "import numpy as npa=np.random.random(10)b=np.random.randint(10, size=10)fig = go.Figure(data=go.Scatter(x=a, y=b, mode='markers'))fig.show()" }, { "code": null, "e": 1121, "s": 1051, "text": "We can also add additional traces on the same figure using add_trace:" }, { "code": null, "e": 1344, "s": 1121, "text": "fig = go.Figure(data=go.Scatter(x=np.arange(9), y=10*np.random.randn(10),mode='markers', name='markers'))fig.add_trace(go.Scatter(x=np.arange(9), y=np.random.randn(10),mode='lines+markers', name='lines+markers'))fig.show()" }, { "code": null, "e": 1501, "s": 1344, "text": "Another way to create figures is plotly express which is a high level API to produce graph object figures. We can import it with the following line of code:" }, { "code": null, "e": 1529, "s": 1501, "text": "import plotly.express as px" }, { "code": null, "e": 1562, "s": 1529, "text": "Let’s create a sample dataframe:" }, { "code": null, "e": 1782, "s": 1562, "text": "import pandas as pddf = pd.DataFrame({'col_a':np.random.random(10)*5,'col_b':np.random.randint(10, size=10),'col_c':[4.5, 4.7, 4.8, 3.4, 3.7, 4., 5.1, 3.2, 4.4, 3.3],'col_d':['a','a','b','a','a','b','b','c','c','c']})df" }, { "code": null, "e": 1849, "s": 1782, "text": "We can have an idea about the whole dataframe on one scatter plot:" }, { "code": null, "e": 1931, "s": 1849, "text": "fig = px.scatter(df, x=\"col_a\", y=\"col_b\", color=\"col_d\", size='col_c')fig.show()" }, { "code": null, "e": 2447, "s": 1931, "text": "X axis represents “col_a” and y axis represents “col_b”. The size of the markers gives an idea about “col_c” whereas the color of markers represents the information in “col_d”. Thus, one scatter plot is able to tell us a lot about the dataset. Each dot (or marker) represent a row in the dataframe and we can hover on individual data points to see the values of all columns. This was a simple and random dataset. When we work with real datasets, the features of plotly interactive visulizations become more helpful." }, { "code": null, "e": 2529, "s": 2447, "text": "Plotly contains the famous iris dataset that we can access with one line of code:" }, { "code": null, "e": 2689, "s": 2529, "text": "df_iris = px.data.iris()fig = px.scatter(df_iris, x=\"sepal_width\", y=\"sepal_length\", color=\"species\",size='petal_length', hover_data=['petal_width'])fig.show()" }, { "code": null, "e": 2805, "s": 2689, "text": "The scatter plot above tells us how different species are grouped together as well as the variances within species." }, { "code": null, "e": 3038, "s": 2805, "text": "It is also possible to represent different species in separate subplots. All we need to do is add facet_col or facet_row parameters. As the names suggest, facet_col creates subplots as columns and facet_row creates subplots as rows." }, { "code": null, "e": 3173, "s": 3038, "text": "fig = px.scatter(df_iris, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", facet_col=\"species\", title=\"Species Subplots\")fig.show()" }, { "code": null, "e": 3308, "s": 3173, "text": "fig = px.scatter(df_iris, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", facet_row=\"species\", title=\"Species Subplots\")fig.show()" }, { "code": null, "e": 3415, "s": 3308, "text": "After a figure is rendered, we can update the layout using update_layout(). Consider the following figure:" }, { "code": null, "e": 3477, "s": 3415, "text": "We can update the font size of title with the following code:" }, { "code": null, "e": 3571, "s": 3477, "text": "fig.update_layout(title_text=\"Sample Dataset - Updated\", title_font_size=20)" }, { "code": null, "e": 3627, "s": 3571, "text": "Another way to create subplots is to use make_subplots:" }, { "code": null, "e": 3982, "s": 3627, "text": "from plotly.subplots import make_subplotsfig = make_subplots(rows=1, cols=2)fig.add_scatter(y=np.random.random(10), mode=\"markers\", marker=dict(size=15, color=\"Blue\"), name=\"A\", row=1, col=1)fig.add_bar(y=np.random.randint(10, size=10), marker=dict(color=\"LightBlue\"), name=\"B\", row=1, col=2)fig.show()" }, { "code": null, "e": 4284, "s": 3982, "text": "We specified the number of subplots and their positions using rows and cols parameters. Then we add the define the plots and specify the position. We can also specify the size and color of markers by passing a dictionary to marker parameter. The figure that is produced with the code segment above is:" }, { "code": null, "e": 4844, "s": 4284, "text": "We have covered some basic components of plotly.py library. Of course, this is just a little of what can be done with plotly. There are many other plot types that we can dynamically create with plotly. Its syntax is easy to understand as well. I will try to cover more complex plots in the upcoming posts. You can also check the plotly documentation which I think is well-documented with many different examples. Just like any other topic, the best way to get familiar with plotly is to practice. Thus, I suggest creating lots of plots to sharpen your skills." } ]
Machine Learning: GridSearchCV & RandomizedSearchCV | by Papa Moryba Kouate | Towards Data Science
Introduction In this article, I’d like to speak about how we can improve the performance of our machine learning model by tuning the parameters. Obviously it is important to know the meaning of the parameters that we want to adjust in order to improve our model. For this reason, before to speak about GridSearchCV and RandomizedSearchCV, I will start by explaining some parameters like C and gamma. Part I: An overview of some parameters in SVC In the Logistic Regression and the Support Vector Classifier, the parameter that determines the strength of the regularization is called C. For a high C, we will have a less regularization and that means we are trying to fit the training set as best as possible. Instead, with low values of the parameter C, the algorithm tries to adjust to the “majority” of data points and increase the generalization of the model. There is another important parameter called gamma. But before to talk about it, I think it is important to understand a little bit the limitation of linear models. Linear models can be quite limiting in low-dimensional spaces, as lines and hyperplanes have limited flexibility. One way to make a linear model more flexible is by adding more features, for example, by adding interactions or polynomials of the input features. A linear model for classification is only able to separate points using a line, and that is not always the better choice. So, the solution could be to represent the points in a three-dimensional space and not in a two-dimensional space. In fact, in three-dimensional space, we can create a plane that divides and classifies the points of our dataset in a more precise way. There are two ways to map your data into a higher-dimensional space: the polynomial kernel, which computes all possible polynomials up to a certain degree of the original features; and the radial basis function(RBF) kernel, also known as the Gaussian kernel which measures the distance between data points. Here, the task of gamma is to control the width of the Gaussian Kernel. Part II: GridSearchCV As I showed in my previous article, Cross-Validation permits us to evaluate and improve our model. But there is another interesting technique to improve and evaluate our model, this technique is called Grid Search. Grid Search is an effective method for adjusting the parameters in supervised learning and improve the generalization performance of a model. With Grid Search, we try all possible combinations of the parameters of interest and find the best ones. Scikit-learn provides the GridSeaechCV class. Obviously we first need to specify the parameters we want to search and then GridSearchCV will perform all the necessary model fits. For example, we can create the below dictionary that presents all the parameters that we want to search for our model. parameters = {‘C’: [0.001, 0.01, 0.1, 1, 10, 100], ‘gamma’: [0.001, 0.01, 0.1, 1, 10, 100]} Then we can instantiate the GridSearchCV class with the model SVC and apply 6 experiments with cross-validation. Of course, we need also to split our data into a training and test set, to avoid overfitting the parameters. from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_splitfrom sklearn.svm import SVC search = GridSearchCV(SVC(), parameters, cv=5)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) Now we can fit the search object that we have created with our training data. search.fit(X_train, y_train) So the GridSearchCV object searches for the best parameters and automatically fits a new model on the whole training dataset. Part III: RandomizedSearchCV RandomizedSearchCV is very useful when we have many parameters to try and the training time is very long. For this example, I use a random-forest classifier, so I suppose you already know how this kind of algorithm works. The first step is to write the parameters that we want to consider and from these parameters select the best ones. param = {‘max_depth: [6,9, None], ‘n_estimators’:[50, 70, 100, 150], 'max_features': randint(1,6), 'criterion' : ['gini', 'entropy'], 'bootstrap':[True, False], 'mln_samples_leaf': randint(1,4)} Now we can create our RandomizedSearchCV object and fit the data. Finally, we can find the best parameters and the best scores. from sklearn.model_selection import RandomSearchCVfrom sklearn.ensemble import RandomForestClassifierrnd_search = RandomizedSearchCV(RandomForestClassifier(), param, n_iter =10, cv=9)rnd_search.fit(X,y)rnd_search.best_params_rnd_search.best_score_ Conclusion So, Grid Search is good when we work with a small number of hyperparameters. However, if the number of parameters to consider is particularly high and the magnitudes of influence are imbalanced, the better choice is to use the Random Search. Thanks for reading this. There are some other ways you can keep in touch with me and follow my work: Subscribe to my newsletter. You can also get in touch via my Telegram group, Data Science for Beginners.
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 317, "s": 185, "text": "In this article, I’d like to speak about how we can improve the performance of our machine learning model by tuning the parameters." }, { "code": null, "e": 572, "s": 317, "text": "Obviously it is important to know the meaning of the parameters that we want to adjust in order to improve our model. For this reason, before to speak about GridSearchCV and RandomizedSearchCV, I will start by explaining some parameters like C and gamma." }, { "code": null, "e": 618, "s": 572, "text": "Part I: An overview of some parameters in SVC" }, { "code": null, "e": 758, "s": 618, "text": "In the Logistic Regression and the Support Vector Classifier, the parameter that determines the strength of the regularization is called C." }, { "code": null, "e": 1035, "s": 758, "text": "For a high C, we will have a less regularization and that means we are trying to fit the training set as best as possible. Instead, with low values of the parameter C, the algorithm tries to adjust to the “majority” of data points and increase the generalization of the model." }, { "code": null, "e": 1199, "s": 1035, "text": "There is another important parameter called gamma. But before to talk about it, I think it is important to understand a little bit the limitation of linear models." }, { "code": null, "e": 1460, "s": 1199, "text": "Linear models can be quite limiting in low-dimensional spaces, as lines and hyperplanes have limited flexibility. One way to make a linear model more flexible is by adding more features, for example, by adding interactions or polynomials of the input features." }, { "code": null, "e": 1833, "s": 1460, "text": "A linear model for classification is only able to separate points using a line, and that is not always the better choice. So, the solution could be to represent the points in a three-dimensional space and not in a two-dimensional space. In fact, in three-dimensional space, we can create a plane that divides and classifies the points of our dataset in a more precise way." }, { "code": null, "e": 2212, "s": 1833, "text": "There are two ways to map your data into a higher-dimensional space: the polynomial kernel, which computes all possible polynomials up to a certain degree of the original features; and the radial basis function(RBF) kernel, also known as the Gaussian kernel which measures the distance between data points. Here, the task of gamma is to control the width of the Gaussian Kernel." }, { "code": null, "e": 2234, "s": 2212, "text": "Part II: GridSearchCV" }, { "code": null, "e": 2449, "s": 2234, "text": "As I showed in my previous article, Cross-Validation permits us to evaluate and improve our model. But there is another interesting technique to improve and evaluate our model, this technique is called Grid Search." }, { "code": null, "e": 2696, "s": 2449, "text": "Grid Search is an effective method for adjusting the parameters in supervised learning and improve the generalization performance of a model. With Grid Search, we try all possible combinations of the parameters of interest and find the best ones." }, { "code": null, "e": 2994, "s": 2696, "text": "Scikit-learn provides the GridSeaechCV class. Obviously we first need to specify the parameters we want to search and then GridSearchCV will perform all the necessary model fits. For example, we can create the below dictionary that presents all the parameters that we want to search for our model." }, { "code": null, "e": 3086, "s": 2994, "text": "parameters = {‘C’: [0.001, 0.01, 0.1, 1, 10, 100], ‘gamma’: [0.001, 0.01, 0.1, 1, 10, 100]}" }, { "code": null, "e": 3308, "s": 3086, "text": "Then we can instantiate the GridSearchCV class with the model SVC and apply 6 experiments with cross-validation. Of course, we need also to split our data into a training and test set, to avoid overfitting the parameters." }, { "code": null, "e": 3557, "s": 3308, "text": "from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_splitfrom sklearn.svm import SVC search = GridSearchCV(SVC(), parameters, cv=5)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)" }, { "code": null, "e": 3635, "s": 3557, "text": "Now we can fit the search object that we have created with our training data." }, { "code": null, "e": 3664, "s": 3635, "text": "search.fit(X_train, y_train)" }, { "code": null, "e": 3790, "s": 3664, "text": "So the GridSearchCV object searches for the best parameters and automatically fits a new model on the whole training dataset." }, { "code": null, "e": 3819, "s": 3790, "text": "Part III: RandomizedSearchCV" }, { "code": null, "e": 4041, "s": 3819, "text": "RandomizedSearchCV is very useful when we have many parameters to try and the training time is very long. For this example, I use a random-forest classifier, so I suppose you already know how this kind of algorithm works." }, { "code": null, "e": 4156, "s": 4041, "text": "The first step is to write the parameters that we want to consider and from these parameters select the best ones." }, { "code": null, "e": 4397, "s": 4156, "text": "param = {‘max_depth: [6,9, None], ‘n_estimators’:[50, 70, 100, 150], 'max_features': randint(1,6), 'criterion' : ['gini', 'entropy'], 'bootstrap':[True, False], 'mln_samples_leaf': randint(1,4)}" }, { "code": null, "e": 4525, "s": 4397, "text": "Now we can create our RandomizedSearchCV object and fit the data. Finally, we can find the best parameters and the best scores." }, { "code": null, "e": 4773, "s": 4525, "text": "from sklearn.model_selection import RandomSearchCVfrom sklearn.ensemble import RandomForestClassifierrnd_search = RandomizedSearchCV(RandomForestClassifier(), param, n_iter =10, cv=9)rnd_search.fit(X,y)rnd_search.best_params_rnd_search.best_score_" }, { "code": null, "e": 4784, "s": 4773, "text": "Conclusion" }, { "code": null, "e": 5026, "s": 4784, "text": "So, Grid Search is good when we work with a small number of hyperparameters. However, if the number of parameters to consider is particularly high and the magnitudes of influence are imbalanced, the better choice is to use the Random Search." }, { "code": null, "e": 5127, "s": 5026, "text": "Thanks for reading this. There are some other ways you can keep in touch with me and follow my work:" }, { "code": null, "e": 5155, "s": 5127, "text": "Subscribe to my newsletter." } ]
Minimum halls required for class scheduling - GeeksforGeeks
25 May, 2021 Given N lecture timings, with their start time and end time (both inclusive), the task is to find the minimum number of halls required to hold all the classes such that a single hall can be used for only one lecture at a given time. Note that the maximum end time can be 105.Examples: Input: lectures[][] = {{0, 5}, {1, 2}, {1, 10}} Output: 3 All lectures must be held in different halls because at time instance 1 all lectures are ongoing.Input: lectures[][] = {{0, 5}, {1, 2}, {6, 10}} Output: 2 Approach: Assuming that time T starts with 0. The task is to find the maximum number of lectures that are ongoing at a particular instance of time. This will give the minimum number of halls required to schedule all the lectures. To find the number of lectures ongoing at any instance of time. Maintain a prefix_sum[] which will store the number of lectures ongoing at any instance of time t. For any lecture with timings between [s, t], do prefix_sum[s]++ and prefix_sum[t + 1]–. Afterward, the cumulative sum of this prefix array will give the count of lectures going on at any instance of time. The maximum value for any time instant t in the array is the minimum number of halls required. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 100001 // Function to return the minimum// number of halls requiredint minHalls(int lectures[][2], int n){ // Array to store the number of // lectures ongoing at time t int prefix_sum[MAX] = { 0 }; // For every lecture increment start // point s decrement (end point + 1) for (int i = 0; i < n; i++) { prefix_sum[lectures[i][0]]++; prefix_sum[lectures[i][1] + 1]--; } int ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (int i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = max(ans, prefix_sum[i]); } return ans;} // Driver codeint main(){ int lectures[][2] = { { 0, 5 }, { 1, 2 }, { 1, 10 } }; int n = sizeof(lectures) / sizeof(lectures[0]); cout << minHalls(lectures, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{static int MAX = 100001; // Function to return the minimum// number of halls requiredstatic int minHalls(int lectures[][], int n){ // Array to store the number of // lectures ongoing at time t int []prefix_sum = new int[MAX]; // For every lecture increment start // point s decrement (end point + 1) for (int i = 0; i < n; i++) { prefix_sum[lectures[i][0]]++; prefix_sum[lectures[i][1] + 1]--; } int ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (int i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = Math.max(ans, prefix_sum[i]); } return ans;} // Driver codepublic static void main(String[] args){ int lectures[][] = {{ 0, 5 }, { 1, 2 }, { 1, 10 }}; int n = lectures.length; System.out.println(minHalls(lectures, n));}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approachMAX = 100001 # Function to return the minimum# number of halls requireddef minHalls(lectures, n) : # Array to store the number of # lectures ongoing at time t prefix_sum = [0] * MAX; # For every lecture increment start # point s decrement (end point + 1) for i in range(n) : prefix_sum[lectures[i][0]] += 1; prefix_sum[lectures[i][1] + 1] -= 1; ans = prefix_sum[0]; # Perform prefix sum and update # the ans to maximum for i in range(1, MAX) : prefix_sum[i] += prefix_sum[i - 1]; ans = max(ans, prefix_sum[i]); return ans; # Driver codeif __name__ == "__main__" : lectures = [[ 0, 5 ], [ 1, 2 ], [ 1, 10 ]]; n = len(lectures); print(minHalls(lectures, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{static int MAX = 100001; // Function to return the minimum// number of halls requiredstatic int minHalls(int [,]lectures, int n){ // Array to store the number of // lectures ongoing at time t int []prefix_sum = new int[MAX]; // For every lecture increment start // point s decrement (end point + 1) for (int i = 0; i < n; i++) { prefix_sum[lectures[i,0]]++; prefix_sum[lectures[i,1] + 1]--; } int ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (int i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = Math.Max(ans, prefix_sum[i]); } return ans;} // Driver codepublic static void Main(String[] args){ int [,]lectures = {{ 0, 5 }, { 1, 2 }, { 1, 10 }}; int n = lectures.GetLength(0); Console.WriteLine(minHalls(lectures, n));}} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach const MAX = 100001; // Function to return the minimum// number of halls requiredfunction minHalls(lectures, n){ // Array to store the number of // lectures ongoing at time t let prefix_sum = new Uint8Array(MAX); // For every lecture increment start // point s decrement (end point + 1) for (let i = 0; i < n; i++) { prefix_sum[lectures[i][0]]++; prefix_sum[lectures[i][1] + 1]--; } let ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (let i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = Math.max(ans, prefix_sum[i]); } return ans;} // Driver code let lectures = [ [ 0, 5 ], [ 1, 2 ], [ 1, 10 ] ]; let n = lectures.length; document.write(minHalls(lectures, n)); // This code is contributed by Surbhi Tyagi. </script> 3 ankthon princiraj1992 29AjayKumar surbhityagi15 prefix-sum Arrays Dynamic Programming Greedy prefix-sum Arrays Dynamic Programming Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 24431, "s": 24403, "text": "\n25 May, 2021" }, { "code": null, "e": 24718, "s": 24431, "text": "Given N lecture timings, with their start time and end time (both inclusive), the task is to find the minimum number of halls required to hold all the classes such that a single hall can be used for only one lecture at a given time. Note that the maximum end time can be 105.Examples: " }, { "code": null, "e": 24933, "s": 24718, "text": "Input: lectures[][] = {{0, 5}, {1, 2}, {1, 10}} Output: 3 All lectures must be held in different halls because at time instance 1 all lectures are ongoing.Input: lectures[][] = {{0, 5}, {1, 2}, {6, 10}} Output: 2 " }, { "code": null, "e": 24947, "s": 24935, "text": "Approach: " }, { "code": null, "e": 25167, "s": 24947, "text": "Assuming that time T starts with 0. The task is to find the maximum number of lectures that are ongoing at a particular instance of time. This will give the minimum number of halls required to schedule all the lectures." }, { "code": null, "e": 25418, "s": 25167, "text": "To find the number of lectures ongoing at any instance of time. Maintain a prefix_sum[] which will store the number of lectures ongoing at any instance of time t. For any lecture with timings between [s, t], do prefix_sum[s]++ and prefix_sum[t + 1]–." }, { "code": null, "e": 25535, "s": 25418, "text": "Afterward, the cumulative sum of this prefix array will give the count of lectures going on at any instance of time." }, { "code": null, "e": 25630, "s": 25535, "text": "The maximum value for any time instant t in the array is the minimum number of halls required." }, { "code": null, "e": 25683, "s": 25630, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25687, "s": 25683, "text": "C++" }, { "code": null, "e": 25692, "s": 25687, "text": "Java" }, { "code": null, "e": 25700, "s": 25692, "text": "Python3" }, { "code": null, "e": 25703, "s": 25700, "text": "C#" }, { "code": null, "e": 25714, "s": 25703, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAX 100001 // Function to return the minimum// number of halls requiredint minHalls(int lectures[][2], int n){ // Array to store the number of // lectures ongoing at time t int prefix_sum[MAX] = { 0 }; // For every lecture increment start // point s decrement (end point + 1) for (int i = 0; i < n; i++) { prefix_sum[lectures[i][0]]++; prefix_sum[lectures[i][1] + 1]--; } int ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (int i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = max(ans, prefix_sum[i]); } return ans;} // Driver codeint main(){ int lectures[][2] = { { 0, 5 }, { 1, 2 }, { 1, 10 } }; int n = sizeof(lectures) / sizeof(lectures[0]); cout << minHalls(lectures, n); return 0;}", "e": 26677, "s": 25714, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{static int MAX = 100001; // Function to return the minimum// number of halls requiredstatic int minHalls(int lectures[][], int n){ // Array to store the number of // lectures ongoing at time t int []prefix_sum = new int[MAX]; // For every lecture increment start // point s decrement (end point + 1) for (int i = 0; i < n; i++) { prefix_sum[lectures[i][0]]++; prefix_sum[lectures[i][1] + 1]--; } int ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (int i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = Math.max(ans, prefix_sum[i]); } return ans;} // Driver codepublic static void main(String[] args){ int lectures[][] = {{ 0, 5 }, { 1, 2 }, { 1, 10 }}; int n = lectures.length; System.out.println(minHalls(lectures, n));}} // This code is contributed by PrinciRaj1992", "e": 27694, "s": 26677, "text": null }, { "code": "# Python3 implementation of the approachMAX = 100001 # Function to return the minimum# number of halls requireddef minHalls(lectures, n) : # Array to store the number of # lectures ongoing at time t prefix_sum = [0] * MAX; # For every lecture increment start # point s decrement (end point + 1) for i in range(n) : prefix_sum[lectures[i][0]] += 1; prefix_sum[lectures[i][1] + 1] -= 1; ans = prefix_sum[0]; # Perform prefix sum and update # the ans to maximum for i in range(1, MAX) : prefix_sum[i] += prefix_sum[i - 1]; ans = max(ans, prefix_sum[i]); return ans; # Driver codeif __name__ == \"__main__\" : lectures = [[ 0, 5 ], [ 1, 2 ], [ 1, 10 ]]; n = len(lectures); print(minHalls(lectures, n)); # This code is contributed by AnkitRai01", "e": 28580, "s": 27694, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{static int MAX = 100001; // Function to return the minimum// number of halls requiredstatic int minHalls(int [,]lectures, int n){ // Array to store the number of // lectures ongoing at time t int []prefix_sum = new int[MAX]; // For every lecture increment start // point s decrement (end point + 1) for (int i = 0; i < n; i++) { prefix_sum[lectures[i,0]]++; prefix_sum[lectures[i,1] + 1]--; } int ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (int i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = Math.Max(ans, prefix_sum[i]); } return ans;} // Driver codepublic static void Main(String[] args){ int [,]lectures = {{ 0, 5 }, { 1, 2 }, { 1, 10 }}; int n = lectures.GetLength(0); Console.WriteLine(minHalls(lectures, n));}} // This code is contributed by 29AjayKumar", "e": 29590, "s": 28580, "text": null }, { "code": "<script> // JavaScript implementation of the approach const MAX = 100001; // Function to return the minimum// number of halls requiredfunction minHalls(lectures, n){ // Array to store the number of // lectures ongoing at time t let prefix_sum = new Uint8Array(MAX); // For every lecture increment start // point s decrement (end point + 1) for (let i = 0; i < n; i++) { prefix_sum[lectures[i][0]]++; prefix_sum[lectures[i][1] + 1]--; } let ans = prefix_sum[0]; // Perform prefix sum and update // the ans to maximum for (let i = 1; i < MAX; i++) { prefix_sum[i] += prefix_sum[i - 1]; ans = Math.max(ans, prefix_sum[i]); } return ans;} // Driver code let lectures = [ [ 0, 5 ], [ 1, 2 ], [ 1, 10 ] ]; let n = lectures.length; document.write(minHalls(lectures, n)); // This code is contributed by Surbhi Tyagi. </script>", "e": 30539, "s": 29590, "text": null }, { "code": null, "e": 30541, "s": 30539, "text": "3" }, { "code": null, "e": 30551, "s": 30543, "text": "ankthon" }, { "code": null, "e": 30565, "s": 30551, "text": "princiraj1992" }, { "code": null, "e": 30577, "s": 30565, "text": "29AjayKumar" }, { "code": null, "e": 30591, "s": 30577, "text": "surbhityagi15" }, { "code": null, "e": 30602, "s": 30591, "text": "prefix-sum" }, { "code": null, "e": 30609, "s": 30602, "text": "Arrays" }, { "code": null, "e": 30629, "s": 30609, "text": "Dynamic Programming" }, { "code": null, "e": 30636, "s": 30629, "text": "Greedy" }, { "code": null, "e": 30647, "s": 30636, "text": "prefix-sum" }, { "code": null, "e": 30654, "s": 30647, "text": "Arrays" }, { "code": null, "e": 30674, "s": 30654, "text": "Dynamic Programming" }, { "code": null, "e": 30681, "s": 30674, "text": "Greedy" }, { "code": null, "e": 30779, "s": 30681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30788, "s": 30779, "text": "Comments" }, { "code": null, "e": 30801, "s": 30788, "text": "Old Comments" }, { "code": null, "e": 30822, "s": 30801, "text": "Next Greater Element" }, { "code": null, "e": 30847, "s": 30822, "text": "Window Sliding Technique" }, { "code": null, "e": 30874, "s": 30847, "text": "Count pairs with given sum" }, { "code": null, "e": 30923, "s": 30874, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30961, "s": 30923, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30990, "s": 30961, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 31020, "s": 30990, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31054, "s": 31020, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 31085, "s": 31054, "text": "Bellman–Ford Algorithm | DP-23" } ]
A comprehensive guide to downloading stock prices in Python | by Eryk Lewinson | Towards Data Science
The goal of this short article is to show how easy it is to download stock prices (and stock-related data) in Python. In this article I present two approaches, both using Yahoo Finance as the data source. There are many alternatives out there (Quandl, Intrinion, AlphaVantage, Tiingo, IEX Cloud, etc.), however, Yahoo Finance can be considered the most popular as it is the easiest one to access (free and no registration required). The first approach uses a library called yfinance and it is definitely the easiest approach that I am aware of. The second one, withyahoofinancials, is a bit more complicated, however, for the extra effort we put into downloading the data, we receive a wider selection of stock-related data. Let’s get right into it! We need to load the following libraries: import pandas as pdimport yfinance as yffrom yahoofinancials import YahooFinancials You can pip install the libraries you are missing :) yfinance is a very convenient library, which is my go-to library for downloading stock prices. It was previously known as fix_yahoo_finance. The short history of the library is that is started as a fix to the popular pandas_datareader library. With time, Yahoo Finance changed the API and the connected functionalities were deprecated. That is when fix_yahoo_finance was introduced to once again make downloading data from Yahoo Finance possible. It worked as both a patch to pandas_datareader, and as a standalone library. Without further ado, below I show how to quickly download the stock prices of Tesla: Running the code results in the following table: By default, the function downloads daily data, but we can specify the interval as one of the following: 1m, 5m, 15m, 30m, 60m, 1h, 1d, 1wk, 1mo, and more. The command for downloading data can easily be simplified to one line: tsla_df = yf.download('TSLA') However, I wanted to show how to use the arguments of the function. I provided the start and end date of the considered timeframe and disabled the progress bar (for such a small volume of data it makes no sense to display it). We can download the stock prices of multiple assets at once, by providing a list (such as [‘TSLA', ‘FB', ‘MSFT']) as the tickers argument. Additionally, we can set auto_adjust = True , so all the presented prices are adjusted for potential corporate actions, such as splits. Aside from the yf.download function, we can use the Ticker() module. Below I present a short example of downloading the entire history of Tesla’s stock prices: Running the code generates the following plot: The advantage of using the Ticker module is that we can exploit the multiple methods connected to it. The methods we can use include: info — prints out a JSON containing a lot of interesting information, such as the company’s full name, business summary, the industry in which it operates, on which exchange it is listed (also the country, time zone) and many more. It is also worth mentioning that the JSON includes some financial metrics such as the beta coefficient. recommendations — contains a historical list of recommendations made by analysts actions — displays actions such as dividends and splits major_holders — as the name suggests, shows the major holders institutional_holders — shows the institutional holders, such as on the following image: calendar — shows the incoming events, such as earnings. I wrote a separate article on the easiest approach to downloading the entire earnings calendar from Yahoo! Finance. For more information on the available methods, be sure to check out the GitHub repository of yfinance. The second library I wanted to mention in this article is yahoofinancials. While I find it a bit more demanding to work with this library, it provides a lot of information that is not available in yfinance. Let’s start with downloading Tesla’s historical stock prices: We first instantiated an object of the YahooFinancials class by passing Tesla’s ticker. Having done so, we can use a variety of methods to extract useful information. We started with historical stock prices. The usage of the method is pretty self-explanatory. One thing to note is that the result is a JSON. That is why I had to run a series of operations to extract the relevant information and convert the JSON into a pandas DataFrame. Running that snippet results in: The process of obtaining the historical stock prices was a bit longer than in the case of yfinance. Now it is time to show where the yahoofinancials shines. I briefly describe the most important methods: get_stock_quote_type_data — returns a lot of general information about the stock, similar to yfinance‘s info. Using the method returns the following: get_key_statistics_data / get_summary_data — these two methods return many of the statistics (such as the beta, price-to-book ratio, etc.) get_stock_earnings_data — returns information on earnings (yearly and quarterly) as well as the next date when the company will report the earnings: get_financial_stmts — a useful method for getting information on the financial statements of the company I presented a case of using the library for downloading information on a single company. However, we can easily provide a list of companies, and the methods will return appropriate JSONs containing the requested information for each company. Let’s see an example of downloading the adjusted close prices for multiple companies: Getting the data into the pandas DataFrame required a bit more of an effort, however, the code can easily be reused (with slight modifications also for different methods of the YahooFinancials class). In this article, I showed how to easily download historical stock prices from Yahoo Finance. I started with a one-liner using the yfinance library and then gradually dived deeper into extracting more information on the stock (and the company). Using the mentioned libraries, we can download pretty much all the information available at Yahoo Finance. You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. 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! I recently published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website.
[ { "code": null, "e": 605, "s": 172, "text": "The goal of this short article is to show how easy it is to download stock prices (and stock-related data) in Python. In this article I present two approaches, both using Yahoo Finance as the data source. There are many alternatives out there (Quandl, Intrinion, AlphaVantage, Tiingo, IEX Cloud, etc.), however, Yahoo Finance can be considered the most popular as it is the easiest one to access (free and no registration required)." }, { "code": null, "e": 897, "s": 605, "text": "The first approach uses a library called yfinance and it is definitely the easiest approach that I am aware of. The second one, withyahoofinancials, is a bit more complicated, however, for the extra effort we put into downloading the data, we receive a wider selection of stock-related data." }, { "code": null, "e": 922, "s": 897, "text": "Let’s get right into it!" }, { "code": null, "e": 963, "s": 922, "text": "We need to load the following libraries:" }, { "code": null, "e": 1047, "s": 963, "text": "import pandas as pdimport yfinance as yffrom yahoofinancials import YahooFinancials" }, { "code": null, "e": 1100, "s": 1047, "text": "You can pip install the libraries you are missing :)" }, { "code": null, "e": 1624, "s": 1100, "text": "yfinance is a very convenient library, which is my go-to library for downloading stock prices. It was previously known as fix_yahoo_finance. The short history of the library is that is started as a fix to the popular pandas_datareader library. With time, Yahoo Finance changed the API and the connected functionalities were deprecated. That is when fix_yahoo_finance was introduced to once again make downloading data from Yahoo Finance possible. It worked as both a patch to pandas_datareader, and as a standalone library." }, { "code": null, "e": 1709, "s": 1624, "text": "Without further ado, below I show how to quickly download the stock prices of Tesla:" }, { "code": null, "e": 1758, "s": 1709, "text": "Running the code results in the following table:" }, { "code": null, "e": 1984, "s": 1758, "text": "By default, the function downloads daily data, but we can specify the interval as one of the following: 1m, 5m, 15m, 30m, 60m, 1h, 1d, 1wk, 1mo, and more. The command for downloading data can easily be simplified to one line:" }, { "code": null, "e": 2014, "s": 1984, "text": "tsla_df = yf.download('TSLA')" }, { "code": null, "e": 2516, "s": 2014, "text": "However, I wanted to show how to use the arguments of the function. I provided the start and end date of the considered timeframe and disabled the progress bar (for such a small volume of data it makes no sense to display it). We can download the stock prices of multiple assets at once, by providing a list (such as [‘TSLA', ‘FB', ‘MSFT']) as the tickers argument. Additionally, we can set auto_adjust = True , so all the presented prices are adjusted for potential corporate actions, such as splits." }, { "code": null, "e": 2676, "s": 2516, "text": "Aside from the yf.download function, we can use the Ticker() module. Below I present a short example of downloading the entire history of Tesla’s stock prices:" }, { "code": null, "e": 2723, "s": 2676, "text": "Running the code generates the following plot:" }, { "code": null, "e": 2857, "s": 2723, "text": "The advantage of using the Ticker module is that we can exploit the multiple methods connected to it. The methods we can use include:" }, { "code": null, "e": 3193, "s": 2857, "text": "info — prints out a JSON containing a lot of interesting information, such as the company’s full name, business summary, the industry in which it operates, on which exchange it is listed (also the country, time zone) and many more. It is also worth mentioning that the JSON includes some financial metrics such as the beta coefficient." }, { "code": null, "e": 3274, "s": 3193, "text": "recommendations — contains a historical list of recommendations made by analysts" }, { "code": null, "e": 3330, "s": 3274, "text": "actions — displays actions such as dividends and splits" }, { "code": null, "e": 3392, "s": 3330, "text": "major_holders — as the name suggests, shows the major holders" }, { "code": null, "e": 3481, "s": 3392, "text": "institutional_holders — shows the institutional holders, such as on the following image:" }, { "code": null, "e": 3653, "s": 3481, "text": "calendar — shows the incoming events, such as earnings. I wrote a separate article on the easiest approach to downloading the entire earnings calendar from Yahoo! Finance." }, { "code": null, "e": 3756, "s": 3653, "text": "For more information on the available methods, be sure to check out the GitHub repository of yfinance." }, { "code": null, "e": 4025, "s": 3756, "text": "The second library I wanted to mention in this article is yahoofinancials. While I find it a bit more demanding to work with this library, it provides a lot of information that is not available in yfinance. Let’s start with downloading Tesla’s historical stock prices:" }, { "code": null, "e": 4496, "s": 4025, "text": "We first instantiated an object of the YahooFinancials class by passing Tesla’s ticker. Having done so, we can use a variety of methods to extract useful information. We started with historical stock prices. The usage of the method is pretty self-explanatory. One thing to note is that the result is a JSON. That is why I had to run a series of operations to extract the relevant information and convert the JSON into a pandas DataFrame. Running that snippet results in:" }, { "code": null, "e": 4700, "s": 4496, "text": "The process of obtaining the historical stock prices was a bit longer than in the case of yfinance. Now it is time to show where the yahoofinancials shines. I briefly describe the most important methods:" }, { "code": null, "e": 4850, "s": 4700, "text": "get_stock_quote_type_data — returns a lot of general information about the stock, similar to yfinance‘s info. Using the method returns the following:" }, { "code": null, "e": 4989, "s": 4850, "text": "get_key_statistics_data / get_summary_data — these two methods return many of the statistics (such as the beta, price-to-book ratio, etc.)" }, { "code": null, "e": 5138, "s": 4989, "text": "get_stock_earnings_data — returns information on earnings (yearly and quarterly) as well as the next date when the company will report the earnings:" }, { "code": null, "e": 5243, "s": 5138, "text": "get_financial_stmts — a useful method for getting information on the financial statements of the company" }, { "code": null, "e": 5571, "s": 5243, "text": "I presented a case of using the library for downloading information on a single company. However, we can easily provide a list of companies, and the methods will return appropriate JSONs containing the requested information for each company. Let’s see an example of downloading the adjusted close prices for multiple companies:" }, { "code": null, "e": 5772, "s": 5571, "text": "Getting the data into the pandas DataFrame required a bit more of an effort, however, the code can easily be reused (with slight modifications also for different methods of the YahooFinancials class)." }, { "code": null, "e": 6123, "s": 5772, "text": "In this article, I showed how to easily download historical stock prices from Yahoo Finance. I started with a one-liner using the yfinance library and then gradually dived deeper into extracting more information on the stock (and the company). Using the mentioned libraries, we can download pretty much all the information available at Yahoo Finance." }, { "code": null, "e": 6285, "s": 6123, "text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments." }, { "code": null, "e": 6499, "s": 6285, "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!" } ]
Building a Real-Time Object Recognition App with Tensorflow and OpenCV | by Dat Tran | Towards Data Science
In this article, I will walk through the steps how you can easily build your own real-time object recognition application with Tensorflow’s (TF) new Object Detection API and OpenCV in Python 3 (specifically 3.5). The focus will be on the challenges that I faced when building it. You can find the full code on my repo. And here is also the app in action: Google has just released their new TensorFlow Object Detection API. The first release contains: some pre-trained models (especially with a focus on light-weight models, so that they can run on mobile devices) a Jupyter notebook example with one of the released models some very handy scripts that can be used for re-training of the models, for example, on your own dataset. I wanted to lay my hands on this new cool stuff and had some time to build a simple real-time object recognition demo. First, I pulled the TensorFlow models repo and then had a looked at the notebook that they released as well. It basically walked through the all steps of using a pre-trained model. In their example, they used the “SSD with Mobilenet” model but you can also download several other pre-trained models on what they call the “Tensorflow detection model zoo”. Those models are, by the way, trained on the COCO dataset and vary depending on the model speed (slow, medium and fast) and model performance (mAP — mean average precision). What I did next was to run the example. The example is actually well documented. Essentially this is what it does: Import the required packages like TensorFlow, PIL etc.Define some variables e.g. number of class, name of the model etc.Download the frozen model (.pb — protobuf) and load it into memoryLoading some helper code e.g. an index to label translatorThe detection code itself on two test images Import the required packages like TensorFlow, PIL etc. Define some variables e.g. number of class, name of the model etc. Download the frozen model (.pb — protobuf) and load it into memory Loading some helper code e.g. an index to label translator The detection code itself on two test images Note: Before running the example, be aware to have a look at the setup note. In particular, the protobuf compilation section is important: # From tensorflow/models/research/protoc object_detection/protos/*.proto --python_out=. Without running this command, the example won’t work. I then took their code and modified it accordingly: Remove the model download part PIL is not needed as the video streams in OpenCV are already in numpy arrays (PIL is also a very big overhead specifically when using it for reading in the images aka video streams) No “with” statement for the TensorFlow session as this is a huge overhead especially when every time the session needs to be started after each stream Then, I used OpenCV to connect it with my webcam. There are many examples out there that explain you how you can do it, even the official documentation. So, I won’t dig deeper into it. The more interesting part is the optimization that I did to increase the performance of the application. In my case I looked at good fps — frame per seconds. Generally, plain vanilla/naive implementation of many OpenCV examples are not really optimal, for example some of the functions in OpenCV are heavily I/O bounded. So I had to come up with various solutions to encounter this: Reading of frames from the web camera causes a lot of I/O. My idea was to move this part completely to a different Python process with the multiprocessing library. This somehow didn’t work. There were some explanations on Stackoverflow why it wouldn’t work but I did’t dig deeper into this. Fortunately, I found a very nice example from Adrian Rosebrock on his website “pyimagesearch” using threading instead which improved my fps a lot. By the way, if you want to know the difference between multiprocessing and threading, on Stackoverflow there is a good explanation for this. Loading the frozen model into memory is a big overhead every time the application starts. And I already used one TF session for each run but still this is very slow. So what did I do to solve this problem? The solution is quite simple. In this case, I used the multiprocessing library to move the heavy workload of the object detection part into multiple processes. The initial start of the application will be slow as each of those processes need to load the model into memory and start the TF session but after this we will benefit from parallelism😁 asciinema.org Reducing the width and height of the frames in the video stream also improved fps a lot. Note: If you are on Mac OSX like me and you’re using OpenCV 3.1, there might be a chance that OpenCV’s VideoCapture crashes after a while. There is already an issue filed. Switching back to OpenCV 3.0 solved the issue though. Give me a ❤️ if you liked this post:) Pull the code and try it out yourself. And definitely have a look at the Tensorflow Object Detection API. It’s pretty neat and simple from the first look so far. The next thing I want to try is to train my own dataset with the API and also use the pre-trained models for other applications that I have on my mind. I’m also not fully satisfied with the performance of the application. The fps rate is still not optimal. There are still many bottlenecks in OpenCV that I can’t influence but there are alternatives that I can try out like using WebRTC. This is however web-based. Moreover, I’m thinking to use asynchronous method calls (async) to improve my fps rate. Stay tuned! Follow me on twitter: @datitran
[ { "code": null, "e": 491, "s": 172, "text": "In this article, I will walk through the steps how you can easily build your own real-time object recognition application with Tensorflow’s (TF) new Object Detection API and OpenCV in Python 3 (specifically 3.5). The focus will be on the challenges that I faced when building it. You can find the full code on my repo." }, { "code": null, "e": 527, "s": 491, "text": "And here is also the app in action:" }, { "code": null, "e": 623, "s": 527, "text": "Google has just released their new TensorFlow Object Detection API. The first release contains:" }, { "code": null, "e": 736, "s": 623, "text": "some pre-trained models (especially with a focus on light-weight models, so that they can run on mobile devices)" }, { "code": null, "e": 795, "s": 736, "text": "a Jupyter notebook example with one of the released models" }, { "code": null, "e": 901, "s": 795, "text": "some very handy scripts that can be used for re-training of the models, for example, on your own dataset." }, { "code": null, "e": 1020, "s": 901, "text": "I wanted to lay my hands on this new cool stuff and had some time to build a simple real-time object recognition demo." }, { "code": null, "e": 1549, "s": 1020, "text": "First, I pulled the TensorFlow models repo and then had a looked at the notebook that they released as well. It basically walked through the all steps of using a pre-trained model. In their example, they used the “SSD with Mobilenet” model but you can also download several other pre-trained models on what they call the “Tensorflow detection model zoo”. Those models are, by the way, trained on the COCO dataset and vary depending on the model speed (slow, medium and fast) and model performance (mAP — mean average precision)." }, { "code": null, "e": 1664, "s": 1549, "text": "What I did next was to run the example. The example is actually well documented. Essentially this is what it does:" }, { "code": null, "e": 1953, "s": 1664, "text": "Import the required packages like TensorFlow, PIL etc.Define some variables e.g. number of class, name of the model etc.Download the frozen model (.pb — protobuf) and load it into memoryLoading some helper code e.g. an index to label translatorThe detection code itself on two test images" }, { "code": null, "e": 2008, "s": 1953, "text": "Import the required packages like TensorFlow, PIL etc." }, { "code": null, "e": 2075, "s": 2008, "text": "Define some variables e.g. number of class, name of the model etc." }, { "code": null, "e": 2142, "s": 2075, "text": "Download the frozen model (.pb — protobuf) and load it into memory" }, { "code": null, "e": 2201, "s": 2142, "text": "Loading some helper code e.g. an index to label translator" }, { "code": null, "e": 2246, "s": 2201, "text": "The detection code itself on two test images" }, { "code": null, "e": 2385, "s": 2246, "text": "Note: Before running the example, be aware to have a look at the setup note. In particular, the protobuf compilation section is important:" }, { "code": null, "e": 2473, "s": 2385, "text": "# From tensorflow/models/research/protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 2527, "s": 2473, "text": "Without running this command, the example won’t work." }, { "code": null, "e": 2579, "s": 2527, "text": "I then took their code and modified it accordingly:" }, { "code": null, "e": 2610, "s": 2579, "text": "Remove the model download part" }, { "code": null, "e": 2792, "s": 2610, "text": "PIL is not needed as the video streams in OpenCV are already in numpy arrays (PIL is also a very big overhead specifically when using it for reading in the images aka video streams)" }, { "code": null, "e": 2943, "s": 2792, "text": "No “with” statement for the TensorFlow session as this is a huge overhead especially when every time the session needs to be started after each stream" }, { "code": null, "e": 3286, "s": 2943, "text": "Then, I used OpenCV to connect it with my webcam. There are many examples out there that explain you how you can do it, even the official documentation. So, I won’t dig deeper into it. The more interesting part is the optimization that I did to increase the performance of the application. In my case I looked at good fps — frame per seconds." }, { "code": null, "e": 3511, "s": 3286, "text": "Generally, plain vanilla/naive implementation of many OpenCV examples are not really optimal, for example some of the functions in OpenCV are heavily I/O bounded. So I had to come up with various solutions to encounter this:" }, { "code": null, "e": 4090, "s": 3511, "text": "Reading of frames from the web camera causes a lot of I/O. My idea was to move this part completely to a different Python process with the multiprocessing library. This somehow didn’t work. There were some explanations on Stackoverflow why it wouldn’t work but I did’t dig deeper into this. Fortunately, I found a very nice example from Adrian Rosebrock on his website “pyimagesearch” using threading instead which improved my fps a lot. By the way, if you want to know the difference between multiprocessing and threading, on Stackoverflow there is a good explanation for this." }, { "code": null, "e": 4642, "s": 4090, "text": "Loading the frozen model into memory is a big overhead every time the application starts. And I already used one TF session for each run but still this is very slow. So what did I do to solve this problem? The solution is quite simple. In this case, I used the multiprocessing library to move the heavy workload of the object detection part into multiple processes. The initial start of the application will be slow as each of those processes need to load the model into memory and start the TF session but after this we will benefit from parallelism😁" }, { "code": null, "e": 4656, "s": 4642, "text": "asciinema.org" }, { "code": null, "e": 4745, "s": 4656, "text": "Reducing the width and height of the frames in the video stream also improved fps a lot." }, { "code": null, "e": 4971, "s": 4745, "text": "Note: If you are on Mac OSX like me and you’re using OpenCV 3.1, there might be a chance that OpenCV’s VideoCapture crashes after a while. There is already an issue filed. Switching back to OpenCV 3.0 solved the issue though." }, { "code": null, "e": 5686, "s": 4971, "text": "Give me a ❤️ if you liked this post:) Pull the code and try it out yourself. And definitely have a look at the Tensorflow Object Detection API. It’s pretty neat and simple from the first look so far. The next thing I want to try is to train my own dataset with the API and also use the pre-trained models for other applications that I have on my mind. I’m also not fully satisfied with the performance of the application. The fps rate is still not optimal. There are still many bottlenecks in OpenCV that I can’t influence but there are alternatives that I can try out like using WebRTC. This is however web-based. Moreover, I’m thinking to use asynchronous method calls (async) to improve my fps rate. Stay tuned!" } ]
How to take screenshots using python? - GeeksforGeeks
17 May, 2021 Python is a widely used general-purpose language. It allows performing a variety of tasks. One of them can be taking a screenshot. It provides a module named pyautogui which can be used to take the screenshot. This module along with NumPy and OpenCV provides the way to manipulate and save the images (screenshot in this case) YouTubeGeeksforGeeks500K subscribersHow to Take Screenshot Using Python? | 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 / 13:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Wk2aaHz3Dv0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> pyautogui takes pictures as a PIL(python image library) which supports opening, manipulating, and saving many different image file formats. Then we need to convert the image to NumPy array, so that it can be converted from RGB to BGR because when the image file is read with the OpenCV using imread(), the order of colors should be BGR (blue, green, red). Numpy: To install Numpy type the below command in the terminal.pip install numpy pip install numpy pyautogui: To install pyautogui type the below command in the terminal.pip install pyautogui pip install pyautogui OpenCV: To install OpenCV type the below command in the terminal.pip install opencv-python pip install opencv-python Below is the implementation. # Python program to take# screenshots import numpy as npimport cv2import pyautogui # take screenshot using pyautoguiimage = pyautogui.screenshot() # since the pyautogui takes as a # PIL(pillow) and in RGB we need to # convert it to numpy array and BGR # so we can write it to the diskimage = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # writing it to the disk using opencvcv2.imwrite("image1.png", image) Output: python-modules Python-OpenCV Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24323, "s": 24295, "text": "\n17 May, 2021" }, { "code": null, "e": 24650, "s": 24323, "text": "Python is a widely used general-purpose language. It allows performing a variety of tasks. One of them can be taking a screenshot. It provides a module named pyautogui which can be used to take the screenshot. This module along with NumPy and OpenCV provides the way to manipulate and save the images (screenshot in this case)" }, { "code": null, "e": 25486, "s": 24650, "text": "YouTubeGeeksforGeeks500K subscribersHow to Take Screenshot Using Python? | 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 / 13:04•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Wk2aaHz3Dv0\" 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": 25842, "s": 25486, "text": "pyautogui takes pictures as a PIL(python image library) which supports opening, manipulating, and saving many different image file formats. Then we need to convert the image to NumPy array, so that it can be converted from RGB to BGR because when the image file is read with the OpenCV using imread(), the order of colors should be BGR (blue, green, red)." }, { "code": null, "e": 25924, "s": 25842, "text": "Numpy: To install Numpy type the below command in the terminal.pip install numpy\n" }, { "code": null, "e": 25943, "s": 25924, "text": "pip install numpy\n" }, { "code": null, "e": 26037, "s": 25943, "text": "pyautogui: To install pyautogui type the below command in the terminal.pip install pyautogui\n" }, { "code": null, "e": 26060, "s": 26037, "text": "pip install pyautogui\n" }, { "code": null, "e": 26152, "s": 26060, "text": "OpenCV: To install OpenCV type the below command in the terminal.pip install opencv-python\n" }, { "code": null, "e": 26179, "s": 26152, "text": "pip install opencv-python\n" }, { "code": null, "e": 26208, "s": 26179, "text": "Below is the implementation." }, { "code": "# Python program to take# screenshots import numpy as npimport cv2import pyautogui # take screenshot using pyautoguiimage = pyautogui.screenshot() # since the pyautogui takes as a # PIL(pillow) and in RGB we need to # convert it to numpy array and BGR # so we can write it to the diskimage = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # writing it to the disk using opencvcv2.imwrite(\"image1.png\", image)", "e": 26650, "s": 26208, "text": null }, { "code": null, "e": 26658, "s": 26650, "text": "Output:" }, { "code": null, "e": 26673, "s": 26658, "text": "python-modules" }, { "code": null, "e": 26687, "s": 26673, "text": "Python-OpenCV" }, { "code": null, "e": 26711, "s": 26687, "text": "Technical Scripter 2019" }, { "code": null, "e": 26718, "s": 26711, "text": "Python" }, { "code": null, "e": 26737, "s": 26718, "text": "Technical Scripter" }, { "code": null, "e": 26835, "s": 26737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26844, "s": 26835, "text": "Comments" }, { "code": null, "e": 26857, "s": 26844, "text": "Old Comments" }, { "code": null, "e": 26875, "s": 26857, "text": "Python Dictionary" }, { "code": null, "e": 26910, "s": 26875, "text": "Read a file line by line in Python" }, { "code": null, "e": 26932, "s": 26910, "text": "Enumerate() in Python" }, { "code": null, "e": 26964, "s": 26932, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26994, "s": 26964, "text": "Iterate over a list in Python" }, { "code": null, "e": 27036, "s": 26994, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27062, "s": 27036, "text": "Python String | replace()" }, { "code": null, "e": 27105, "s": 27062, "text": "Python program to convert a list to string" }, { "code": null, "e": 27149, "s": 27105, "text": "Reading and Writing to text files in Python" } ]
Python program to check if the given number is Happy Number
When it is required to check if a given number is a happy number, the ‘%’ operator, the ‘//’ operator and the ‘+’ operator can be used. A Happy number is the one that ends up as 1, when it is replaced by the sum of square of every digit in the number. Below is a demonstration for the same − Live Demo def check_happy_num(my_num): remaining = sum_val = 0 while(my_num > 0): remaining = my_num%10 sum_val = sum_val + (remaining*remaining) my_num = my_num//10 return sum_val; my_num = 86 my_result = my_num while(my_result != 1 and my_result != 4): my_result = check_happy_num(my_result); print("The number is being checked") if(my_result == 1): print(str(my_num) + " is a happy number"); elif(my_result == 4): print(str(my_num) + " isn't a happy number"); The number is being checked 86 is a happy number A method named ‘check_happy_num’ is defined, that takes a number as parameter. It checks to see if the number is greater than 0. A sum variable is assigned to 0. It divides the number by 10 and gets the remainder, and assigns it to a value. This remainder is multipled with itself and added to a ‘sum’ variable. This occurs on all digits of the number. This sum is returned as output. The number is defined, and a copy of it is made. It is checked to see if it is a happy number by calling the function previously defined. Relevant message is displayed on the console.
[ { "code": null, "e": 1198, "s": 1062, "text": "When it is required to check if a given number is a happy number, the ‘%’ operator, the ‘//’ operator and the ‘+’ operator can be used." }, { "code": null, "e": 1314, "s": 1198, "text": "A Happy number is the one that ends up as 1, when it is replaced by the sum of square of every digit in the number." }, { "code": null, "e": 1354, "s": 1314, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1365, "s": 1354, "text": " Live Demo" }, { "code": null, "e": 1854, "s": 1365, "text": "def check_happy_num(my_num):\n remaining = sum_val = 0\n while(my_num > 0):\n remaining = my_num%10\n sum_val = sum_val + (remaining*remaining)\n my_num = my_num//10\n return sum_val;\nmy_num = 86\nmy_result = my_num\nwhile(my_result != 1 and my_result != 4):\n my_result = check_happy_num(my_result);\nprint(\"The number is being checked\")\nif(my_result == 1):\n print(str(my_num) + \" is a happy number\");\nelif(my_result == 4):\n print(str(my_num) + \" isn't a happy number\");" }, { "code": null, "e": 1903, "s": 1854, "text": "The number is being checked\n86 is a happy number" }, { "code": null, "e": 1982, "s": 1903, "text": "A method named ‘check_happy_num’ is defined, that takes a number as parameter." }, { "code": null, "e": 2032, "s": 1982, "text": "It checks to see if the number is greater than 0." }, { "code": null, "e": 2065, "s": 2032, "text": "A sum variable is assigned to 0." }, { "code": null, "e": 2144, "s": 2065, "text": "It divides the number by 10 and gets the remainder, and assigns it to a value." }, { "code": null, "e": 2215, "s": 2144, "text": "This remainder is multipled with itself and added to a ‘sum’ variable." }, { "code": null, "e": 2256, "s": 2215, "text": "This occurs on all digits of the number." }, { "code": null, "e": 2288, "s": 2256, "text": "This sum is returned as output." }, { "code": null, "e": 2337, "s": 2288, "text": "The number is defined, and a copy of it is made." }, { "code": null, "e": 2426, "s": 2337, "text": "It is checked to see if it is a happy number by calling the function previously defined." }, { "code": null, "e": 2472, "s": 2426, "text": "Relevant message is displayed on the console." } ]
Non capturing groups Java regular expressions:
Using capturing groups you can treat multiple characters as a single unit. You just need to place the characters to be grouped inside a set of parentheses. For example − (.*)(\\d+)(.*) If you are trying to match multiple groups the match results of each group is captured. You can get the results a group by passing its respective group number to the group() method. 1,2, 3 etc.. (from right to left) group 0 indicates the whole match. Live Demo import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapturingGroups { public static void main( String args[] ) { System.out.println("Enter input text"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "(.*)(\\d+)(.*)"; //Create a Pattern object Pattern pattern = Pattern.compile(regex); //Now create matcher object. Matcher matcher = pattern.matcher(input); if (matcher.find( )) { System.out.println("Found value: " + matcher.group(0) ); System.out.println("Found value: " + matcher.group(1) ); System.out.println("Found value: " + matcher.group(2) ); System.out.println("Found value: " + matcher.group(3) ); } else { System.out.println("NO MATCH"); } } } Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: 4 Found value: (digits) in middle The non-capturing group provides the same functionality of a capturing group but it does not captures the result For example, if you need to match a URL or a phone number from a text using groups, since the starting part of the desired sub strings is same you need not capture the results of certain groups in such cases you can use non capturing groups. A non-capturing group starts with (?: and ends with ). Live Demo import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CapturingGroups { public static void main( String args[] ) { System.out.println("Enter input text"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "(.*)(?:\\d+)(.*)"; //Create a Pattern object Pattern pattern = Pattern.compile(regex); //Now create matcher object. Matcher matcher = pattern.matcher(input); if (matcher.find( )) { System.out.println("Found value: " + matcher.group(0) ); System.out.println("Found value: " + matcher.group(1) ); System.out.println("Found value: " + matcher.group(2) ); } else { System.out.println("NO MATCH"); } } } Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: (digits) in middle Note: The non-capturing group will not be included in the group count.
[ { "code": null, "e": 1232, "s": 1062, "text": "Using capturing groups you can treat multiple characters as a single unit. You just need to place the characters to be grouped inside a set of parentheses. For example −" }, { "code": null, "e": 1247, "s": 1232, "text": "(.*)(\\\\d+)(.*)" }, { "code": null, "e": 1498, "s": 1247, "text": "If you are trying to match multiple groups the match results of each group is captured. You can get the results a group by passing its respective group number to the group() method. 1,2, 3 etc.. (from right to left) group 0 indicates the whole match." }, { "code": null, "e": 1509, "s": 1498, "text": " Live Demo" }, { "code": null, "e": 2370, "s": 1509, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class CapturingGroups {\n public static void main( String args[] ) {\n System.out.println(\"Enter input text\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n String regex = \"(.*)(\\\\d+)(.*)\";\n //Create a Pattern object\n Pattern pattern = Pattern.compile(regex);\n //Now create matcher object.\n Matcher matcher = pattern.matcher(input);\n if (matcher.find( )) {\n System.out.println(\"Found value: \" + matcher.group(0) );\n System.out.println(\"Found value: \" + matcher.group(1) );\n System.out.println(\"Found value: \" + matcher.group(2) );\n System.out.println(\"Found value: \" + matcher.group(3) );\n } else {\n System.out.println(\"NO MATCH\");\n }\n }\n}" }, { "code": null, "e": 2563, "s": 2370, "text": "Enter input text\nsample data with 1234 (digits) in middle\nFound value: sample data with 1234 (digits) in middle\nFound value: sample data with 123\nFound value: 4\nFound value: (digits) in middle" }, { "code": null, "e": 2676, "s": 2563, "text": "The non-capturing group provides the same functionality of a capturing group but it does not captures the result" }, { "code": null, "e": 2973, "s": 2676, "text": "For example, if you need to match a URL or a phone number from a text using groups, since the starting part of the desired sub strings is same you need not capture the results of certain groups in such cases you can use non capturing groups. A non-capturing group starts with (?: and ends with )." }, { "code": null, "e": 2984, "s": 2973, "text": " Live Demo" }, { "code": null, "e": 3778, "s": 2984, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class CapturingGroups {\n public static void main( String args[] ) {\n System.out.println(\"Enter input text\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n String regex = \"(.*)(?:\\\\d+)(.*)\";\n //Create a Pattern object\n Pattern pattern = Pattern.compile(regex);\n //Now create matcher object.\n Matcher matcher = pattern.matcher(input);\n if (matcher.find( )) {\n System.out.println(\"Found value: \" + matcher.group(0) );\n System.out.println(\"Found value: \" + matcher.group(1) );\n System.out.println(\"Found value: \" + matcher.group(2) );\n } else {\n System.out.println(\"NO MATCH\");\n }\n }\n}" }, { "code": null, "e": 3956, "s": 3778, "text": "Enter input text\nsample data with 1234 (digits) in middle\nFound value: sample data with 1234 (digits) in middle\nFound value: sample data with 123\nFound value: (digits) in middle" }, { "code": null, "e": 4027, "s": 3956, "text": "Note: The non-capturing group will not be included in the group count." } ]
How to Deal with Missing Data in Python | by Chaitanya Baweja | Towards Data Science
Last year I was working on a project that dealt with Twitter data. We had around a billion tweets in our database. I needed to clean our data so that we can run some machine learning models on it. Here is a snapshot of the Dataset: Weird Unicode characters (emojis), random missing values with changing identifiers, etc. I still have nightmares about that project. But, that’s how real-world datasets are. You get missing values, random characters, wrong data types, etc. According to some statistics, data scientists end up spending 80% of their time organizing and cleaning data. A common occurrence in a data-set is missing values. This can happen due to multiple reasons like unrecorded observations or data corruption. In this tutorial, we will walk through many different ways of handling missing values in Python using the Pandas library. Pandas library provides a variety of functions for marking these corrupt values. We will study how we can remove or impute these values. All the examples in this tutorial were tested on a Jupyter notebook running Python 3.7. We will be using NumPy and Pandas in this tutorial. There is an accompanying Jupyter notebook for this tutorial here. I would highly recommend setting up a virtual environment with all the required libraries for testing. Here is how you can do it. $ virtualenv missing_data$ source ./missing_data/bin/activate$ pip3 install pandas numpy We will be working with a small Employee Dataset for this tutorial. Download the dataset in CSV format from my Github repo and store it in your current working directory: employees.csv Let us import this dataset into Python and take a look at it. Output: We read the CSV file into a Pandas DataFrame. The .head() method returns the first five rows of the DataFrame. The dataset has 1000 observations with six variables as given below: There are two types of missing values in every dataset: Visible errors: blank cells, special symbols like NA (Not Available), NaN (Not a Number), etc.Obscure errors: non-corrupt but invalid values. For example, a negative salary or a number for a name. Visible errors: blank cells, special symbols like NA (Not Available), NaN (Not a Number), etc. Obscure errors: non-corrupt but invalid values. For example, a negative salary or a number for a name. Note: The name rule might need some modification for Elon’s son X Æ A-12. The employee dataset has multiple missing values. Let us take a closer look: You would notice values like NA, NaN, ? and also blank cells. These represent missing values in our dataset. Let us print the first 10 rows of the ‘Salary’ column. print(df['Salary'].head(10)) We depict both a snapshot from our dataset and the output of the above statement in the images below. Pandas automatically marks blank values or values with NA as NaN (missing values). Pandas also assigns an index value to each row. Values containing NaN are ignored from operations like mean, sum, etc. While this works for NA and blank lines, Pandas fails to identify other symbols like na, ?, n.a., n/a. This can be seen in the ‘Gender’ column: As earlier, Pandas takes care of the blank value and converts it to NaN. But it is unable to do so for the n.a. in the 6th row. With multiple users manually feeding data into a database, this is a common issue. We can pass all of these symbols in the .read_csv() method as a list to allow Pandas to recognize them as corrupt values. Take a look: Till now, our missing values had unique identifiers which, made them pretty easy to catch. But what happens when we get an invalid data type. For example, if we are expecting a numeric value but, the user inputs a string like ‘No’ for salary. Technically, this is also a missing value. I have designed a function that allows me to check for invalid data types in a column. Suppose I wish to ensure that all values in the ‘Salary’ column are of type int. I will use the following: After this, values in the salary column will be of type int with NaN wherever invalid entries occurred. In Pandas, we have two functions for marking missing values: isnull(): mark all NaN values in the dataset as True notnull(): mark all NaN values in the dataset as False. Look at the code below: # NaN values are marked Trueprint(df[‘Gender’].isnull().head(10))# NaN values are marked False print(df[‘Gender’].notnull().head(10)) We can use the outputs of the isnull and notnull functions for filtering. Let us print all rows for which Gender is not missing. # notnull will return False for all NaN valuesnull_filter = df['Gender'].notnull()# prints only those rows where null_filter is Trueprint(df[null_filter]) isnull and notnull can also be used to summarize missing values. print(df.isnull().values.any())# OutputTrue print(df.isnull().sum())# OutputFirst Name 70Gender 149Salary 5Bonus % 4Senior Management 71Team 48 Now that we have marked all missing values in our dataset as NaN, we need to decide how do we wish to handle them. The most elementary strategy is to remove all rows that contain missing values or, in extreme cases, entire columns that contain missing values. Pandas library provides the dropna() function that can be used to drop either columns or rows with missing data. In the example below, we use dropna() to remove all rows with missing data: # drop all rows with NaN valuesdf.dropna(axis=0,inplace=True) inplace=True causes all changes to happen in the same data frame rather than returning a new one. To drop columns, we need to set axis = 1. We can also use the how parameter. how = 'any’: at least one value must be null. how = 'all’: all values must be null. Some code examples using the how parameter: Removing rows is a good option when missing values are rare. But this is not always practical. We need to replace these NaNs with intelligent guesses. There are many options to pick from when replacing a missing value: A single pre-decided constant value, such as 0. Taking value from another randomly selected sample. Mean, median, or mode for the column. Interpolate value using a predictive model. In order to fill missing values in a datasets, Pandas library provides us with fillna(), replace() and interpolate() functions. Let us look at these functions one by one using examples. We will use fillna() to replace missing values in the ‘Salary’ column with 0. df['Salary'].fillna(0, inplace=True)# To check changes call# print(df['Salary'].head(10)) We can also do the same for categorical variables like ‘Gender’. df['Gender'].fillna('No Gender', inplace=True) This is a common approach when filling missing values in image data. We use method = 'pad’ for taking values from the previous row. df['Salary'].fillna(method='pad', inplace=True) We use method = 'bfill’ for taking values from the next row. df['Salary'].fillna(method='bfill', inplace=True) A common sensible approach. # using mediandf['Salary'].fillna(df['Salary'].median(), inplace=True)#using meandf['Salary'].fillna(int(df['Salary'].mean()), inplace=True) Note: Information about other options for fillna is available here. The replace method is a more generic form of the fillna method. Here, we specify both the value to be replaced and the replacement value. # will replace NaN value in Salary with value 0 df['Salary'].replace(to_replace = np.nan, value = 0,inplace=True) interpolate() function is used to fill NaN values using various interpolation techniques. Read more about the interpolation methods here. Let us interpolate the missing values using the Linear Interpolation method. df['Salary'].interpolate(method='linear', direction = 'forward', inplace=True) print(df['Salary'].head(10)) Whether we like it or not, real world data is messy. Data cleaning is a major part of every data science project. In this tutorial, we went over techniques to detect, mark and replace missing values. Often data is missing due to random reasons like data corruption, signal errors, etc. But some times, there is a deeper reason for this missing data. While we discussed replacement using mean, median, interpolation, etc, missing values usually have a more complex statistical relationship with our data. I would recommend going through this guide for more details. I hope that after reading this tutorial, you spend less time cleaning data and more time exploring and modeling. Happy to answer all your queries in the comments below. Python Pandas — Missing Data DataCamp Course: Dealing with Missing Data in Python Machine Learning Mastery — How to Handle Missing Data with Python Chaitanya Baweja aspires to solve real world problems with engineering solutions. Follow his journey on Twitter and Linkedin.
[ { "code": null, "e": 369, "s": 172, "text": "Last year I was working on a project that dealt with Twitter data. We had around a billion tweets in our database. I needed to clean our data so that we can run some machine learning models on it." }, { "code": null, "e": 404, "s": 369, "text": "Here is a snapshot of the Dataset:" }, { "code": null, "e": 537, "s": 404, "text": "Weird Unicode characters (emojis), random missing values with changing identifiers, etc. I still have nightmares about that project." }, { "code": null, "e": 754, "s": 537, "text": "But, that’s how real-world datasets are. You get missing values, random characters, wrong data types, etc. According to some statistics, data scientists end up spending 80% of their time organizing and cleaning data." }, { "code": null, "e": 896, "s": 754, "text": "A common occurrence in a data-set is missing values. This can happen due to multiple reasons like unrecorded observations or data corruption." }, { "code": null, "e": 1018, "s": 896, "text": "In this tutorial, we will walk through many different ways of handling missing values in Python using the Pandas library." }, { "code": null, "e": 1155, "s": 1018, "text": "Pandas library provides a variety of functions for marking these corrupt values. We will study how we can remove or impute these values." }, { "code": null, "e": 1295, "s": 1155, "text": "All the examples in this tutorial were tested on a Jupyter notebook running Python 3.7. We will be using NumPy and Pandas in this tutorial." }, { "code": null, "e": 1361, "s": 1295, "text": "There is an accompanying Jupyter notebook for this tutorial here." }, { "code": null, "e": 1491, "s": 1361, "text": "I would highly recommend setting up a virtual environment with all the required libraries for testing. Here is how you can do it." }, { "code": null, "e": 1580, "s": 1491, "text": "$ virtualenv missing_data$ source ./missing_data/bin/activate$ pip3 install pandas numpy" }, { "code": null, "e": 1648, "s": 1580, "text": "We will be working with a small Employee Dataset for this tutorial." }, { "code": null, "e": 1765, "s": 1648, "text": "Download the dataset in CSV format from my Github repo and store it in your current working directory: employees.csv" }, { "code": null, "e": 1827, "s": 1765, "text": "Let us import this dataset into Python and take a look at it." }, { "code": null, "e": 1835, "s": 1827, "text": "Output:" }, { "code": null, "e": 1946, "s": 1835, "text": "We read the CSV file into a Pandas DataFrame. The .head() method returns the first five rows of the DataFrame." }, { "code": null, "e": 2015, "s": 1946, "text": "The dataset has 1000 observations with six variables as given below:" }, { "code": null, "e": 2071, "s": 2015, "text": "There are two types of missing values in every dataset:" }, { "code": null, "e": 2268, "s": 2071, "text": "Visible errors: blank cells, special symbols like NA (Not Available), NaN (Not a Number), etc.Obscure errors: non-corrupt but invalid values. For example, a negative salary or a number for a name." }, { "code": null, "e": 2363, "s": 2268, "text": "Visible errors: blank cells, special symbols like NA (Not Available), NaN (Not a Number), etc." }, { "code": null, "e": 2466, "s": 2363, "text": "Obscure errors: non-corrupt but invalid values. For example, a negative salary or a number for a name." }, { "code": null, "e": 2540, "s": 2466, "text": "Note: The name rule might need some modification for Elon’s son X Æ A-12." }, { "code": null, "e": 2617, "s": 2540, "text": "The employee dataset has multiple missing values. Let us take a closer look:" }, { "code": null, "e": 2726, "s": 2617, "text": "You would notice values like NA, NaN, ? and also blank cells. These represent missing values in our dataset." }, { "code": null, "e": 2781, "s": 2726, "text": "Let us print the first 10 rows of the ‘Salary’ column." }, { "code": null, "e": 2810, "s": 2781, "text": "print(df['Salary'].head(10))" }, { "code": null, "e": 2912, "s": 2810, "text": "We depict both a snapshot from our dataset and the output of the above statement in the images below." }, { "code": null, "e": 2995, "s": 2912, "text": "Pandas automatically marks blank values or values with NA as NaN (missing values)." }, { "code": null, "e": 3114, "s": 2995, "text": "Pandas also assigns an index value to each row. Values containing NaN are ignored from operations like mean, sum, etc." }, { "code": null, "e": 3258, "s": 3114, "text": "While this works for NA and blank lines, Pandas fails to identify other symbols like na, ?, n.a., n/a. This can be seen in the ‘Gender’ column:" }, { "code": null, "e": 3386, "s": 3258, "text": "As earlier, Pandas takes care of the blank value and converts it to NaN. But it is unable to do so for the n.a. in the 6th row." }, { "code": null, "e": 3604, "s": 3386, "text": "With multiple users manually feeding data into a database, this is a common issue. We can pass all of these symbols in the .read_csv() method as a list to allow Pandas to recognize them as corrupt values. Take a look:" }, { "code": null, "e": 3746, "s": 3604, "text": "Till now, our missing values had unique identifiers which, made them pretty easy to catch. But what happens when we get an invalid data type." }, { "code": null, "e": 3890, "s": 3746, "text": "For example, if we are expecting a numeric value but, the user inputs a string like ‘No’ for salary. Technically, this is also a missing value." }, { "code": null, "e": 4084, "s": 3890, "text": "I have designed a function that allows me to check for invalid data types in a column. Suppose I wish to ensure that all values in the ‘Salary’ column are of type int. I will use the following:" }, { "code": null, "e": 4188, "s": 4084, "text": "After this, values in the salary column will be of type int with NaN wherever invalid entries occurred." }, { "code": null, "e": 4249, "s": 4188, "text": "In Pandas, we have two functions for marking missing values:" }, { "code": null, "e": 4302, "s": 4249, "text": "isnull(): mark all NaN values in the dataset as True" }, { "code": null, "e": 4358, "s": 4302, "text": "notnull(): mark all NaN values in the dataset as False." }, { "code": null, "e": 4382, "s": 4358, "text": "Look at the code below:" }, { "code": null, "e": 4516, "s": 4382, "text": "# NaN values are marked Trueprint(df[‘Gender’].isnull().head(10))# NaN values are marked False print(df[‘Gender’].notnull().head(10))" }, { "code": null, "e": 4590, "s": 4516, "text": "We can use the outputs of the isnull and notnull functions for filtering." }, { "code": null, "e": 4645, "s": 4590, "text": "Let us print all rows for which Gender is not missing." }, { "code": null, "e": 4800, "s": 4645, "text": "# notnull will return False for all NaN valuesnull_filter = df['Gender'].notnull()# prints only those rows where null_filter is Trueprint(df[null_filter])" }, { "code": null, "e": 4865, "s": 4800, "text": "isnull and notnull can also be used to summarize missing values." }, { "code": null, "e": 4909, "s": 4865, "text": "print(df.isnull().values.any())# OutputTrue" }, { "code": null, "e": 5086, "s": 4909, "text": "print(df.isnull().sum())# OutputFirst Name 70Gender 149Salary 5Bonus % 4Senior Management 71Team 48" }, { "code": null, "e": 5201, "s": 5086, "text": "Now that we have marked all missing values in our dataset as NaN, we need to decide how do we wish to handle them." }, { "code": null, "e": 5346, "s": 5201, "text": "The most elementary strategy is to remove all rows that contain missing values or, in extreme cases, entire columns that contain missing values." }, { "code": null, "e": 5459, "s": 5346, "text": "Pandas library provides the dropna() function that can be used to drop either columns or rows with missing data." }, { "code": null, "e": 5535, "s": 5459, "text": "In the example below, we use dropna() to remove all rows with missing data:" }, { "code": null, "e": 5597, "s": 5535, "text": "# drop all rows with NaN valuesdf.dropna(axis=0,inplace=True)" }, { "code": null, "e": 5695, "s": 5597, "text": "inplace=True causes all changes to happen in the same data frame rather than returning a new one." }, { "code": null, "e": 5737, "s": 5695, "text": "To drop columns, we need to set axis = 1." }, { "code": null, "e": 5772, "s": 5737, "text": "We can also use the how parameter." }, { "code": null, "e": 5818, "s": 5772, "text": "how = 'any’: at least one value must be null." }, { "code": null, "e": 5856, "s": 5818, "text": "how = 'all’: all values must be null." }, { "code": null, "e": 5900, "s": 5856, "text": "Some code examples using the how parameter:" }, { "code": null, "e": 6051, "s": 5900, "text": "Removing rows is a good option when missing values are rare. But this is not always practical. We need to replace these NaNs with intelligent guesses." }, { "code": null, "e": 6119, "s": 6051, "text": "There are many options to pick from when replacing a missing value:" }, { "code": null, "e": 6167, "s": 6119, "text": "A single pre-decided constant value, such as 0." }, { "code": null, "e": 6219, "s": 6167, "text": "Taking value from another randomly selected sample." }, { "code": null, "e": 6257, "s": 6219, "text": "Mean, median, or mode for the column." }, { "code": null, "e": 6301, "s": 6257, "text": "Interpolate value using a predictive model." }, { "code": null, "e": 6429, "s": 6301, "text": "In order to fill missing values in a datasets, Pandas library provides us with fillna(), replace() and interpolate() functions." }, { "code": null, "e": 6487, "s": 6429, "text": "Let us look at these functions one by one using examples." }, { "code": null, "e": 6565, "s": 6487, "text": "We will use fillna() to replace missing values in the ‘Salary’ column with 0." }, { "code": null, "e": 6655, "s": 6565, "text": "df['Salary'].fillna(0, inplace=True)# To check changes call# print(df['Salary'].head(10))" }, { "code": null, "e": 6720, "s": 6655, "text": "We can also do the same for categorical variables like ‘Gender’." }, { "code": null, "e": 6767, "s": 6720, "text": "df['Gender'].fillna('No Gender', inplace=True)" }, { "code": null, "e": 6899, "s": 6767, "text": "This is a common approach when filling missing values in image data. We use method = 'pad’ for taking values from the previous row." }, { "code": null, "e": 6947, "s": 6899, "text": "df['Salary'].fillna(method='pad', inplace=True)" }, { "code": null, "e": 7008, "s": 6947, "text": "We use method = 'bfill’ for taking values from the next row." }, { "code": null, "e": 7058, "s": 7008, "text": "df['Salary'].fillna(method='bfill', inplace=True)" }, { "code": null, "e": 7086, "s": 7058, "text": "A common sensible approach." }, { "code": null, "e": 7227, "s": 7086, "text": "# using mediandf['Salary'].fillna(df['Salary'].median(), inplace=True)#using meandf['Salary'].fillna(int(df['Salary'].mean()), inplace=True)" }, { "code": null, "e": 7295, "s": 7227, "text": "Note: Information about other options for fillna is available here." }, { "code": null, "e": 7433, "s": 7295, "text": "The replace method is a more generic form of the fillna method. Here, we specify both the value to be replaced and the replacement value." }, { "code": null, "e": 7548, "s": 7433, "text": "# will replace NaN value in Salary with value 0 df['Salary'].replace(to_replace = np.nan, value = 0,inplace=True)" }, { "code": null, "e": 7686, "s": 7548, "text": "interpolate() function is used to fill NaN values using various interpolation techniques. Read more about the interpolation methods here." }, { "code": null, "e": 7763, "s": 7686, "text": "Let us interpolate the missing values using the Linear Interpolation method." }, { "code": null, "e": 7871, "s": 7763, "text": "df['Salary'].interpolate(method='linear', direction = 'forward', inplace=True) print(df['Salary'].head(10))" }, { "code": null, "e": 7985, "s": 7871, "text": "Whether we like it or not, real world data is messy. Data cleaning is a major part of every data science project." }, { "code": null, "e": 8071, "s": 7985, "text": "In this tutorial, we went over techniques to detect, mark and replace missing values." }, { "code": null, "e": 8221, "s": 8071, "text": "Often data is missing due to random reasons like data corruption, signal errors, etc. But some times, there is a deeper reason for this missing data." }, { "code": null, "e": 8436, "s": 8221, "text": "While we discussed replacement using mean, median, interpolation, etc, missing values usually have a more complex statistical relationship with our data. I would recommend going through this guide for more details." }, { "code": null, "e": 8605, "s": 8436, "text": "I hope that after reading this tutorial, you spend less time cleaning data and more time exploring and modeling. Happy to answer all your queries in the comments below." }, { "code": null, "e": 8634, "s": 8605, "text": "Python Pandas — Missing Data" }, { "code": null, "e": 8687, "s": 8634, "text": "DataCamp Course: Dealing with Missing Data in Python" }, { "code": null, "e": 8753, "s": 8687, "text": "Machine Learning Mastery — How to Handle Missing Data with Python" } ]
Adding Collisions Using pygame.Rect.colliderect in Pygame - GeeksforGeeks
24 Sep, 2021 Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding or not. Syntax: pygame.Rect.colliderect(rect1, rect2) Parameters: It will take two rects as its parameters. Returns: Returns true if any portion of either rectangle overlap. Python3 # Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new rect for first objectplayer_rect = Rect(200, 500, 50, 50) # Creating a new rect for second objectplayer_rect2 = Rect(200, 0, 50, 50) # Creating variable for gravitygravity = 4 # Creating a boolean variable that# we will use to run the while looprun = True # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 60fps clock.tick(60) # Adding gravity in player_rect2 player_rect2.bottom += gravity # Checking if player is colliding # with platform or not using the # colliderect() method. # It will return a boolean value collide = pygame.Rect.colliderect(player_rect, p layer_rect2) # If the objects are colliding # then changing the y coordinate if collide: player_rect2.bottom = player_rect.top # Drawing player rect pygame.draw.rect(window, (0, 255, 0), player_rect) # Drawing player rect2 pygame.draw.rect(window, (0, 0, 255), player_rect2) # Updating the display surface pygame.display.update() # Filling the window with white color window.fill((255, 255, 255)) Output: Python3 # Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new rect for first objectplayer_rect = Rect(200, 500, 50, 50) # Creating a new rect for second objectplayer_rect2 = Rect(200, 0, 50, 50) # Creating a boolean variable that# we will use to run the while looprun = True # Speed for the objectsspeed_a = 8speed_b = -7 # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 60fps clock.tick(60) # Adding speed in player rects player_rect.bottom += speed_a player_rect2.top += speed_b # Checking if player is colliding # with platform or not using the # colliderect() method. # It will return a boolean value collide = pygame.Rect.colliderect(player_rect, player_rect2) # If the objects are colliding # then changing the speed direction if collide: speed_a *= -1 speed_b *= -1 # Changing the direction if the objects # goes outside the window if player_rect.top<0 or player_rect.bottom > 600: speed_a *= -1 if player_rect2.bottom > 600 or player_rect2.top<0: speed_b *= -1 # Drawing player rect pygame.draw.rect(window, (0, 255, 0), player_rect) # Drawing player rect2 pygame.draw.rect(window, (0, 0, 255), player_rect2) # Updating the display surface pygame.display.update() # Filling the window with white color window.fill((255, 255, 255)) Output: sweetyty simranarora5sos Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24546, "s": 24518, "text": "\n24 Sep, 2021" }, { "code": null, "e": 24609, "s": 24546, "text": "Prerequisite: Drawing shapes in Pygame, Introduction to pygame" }, { "code": null, "e": 24726, "s": 24609, "text": "In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python." }, { "code": null, "e": 24903, "s": 24726, "text": "We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding or not." }, { "code": null, "e": 24949, "s": 24903, "text": "Syntax: pygame.Rect.colliderect(rect1, rect2)" }, { "code": null, "e": 25003, "s": 24949, "text": "Parameters: It will take two rects as its parameters." }, { "code": null, "e": 25069, "s": 25003, "text": "Returns: Returns true if any portion of either rectangle overlap." }, { "code": null, "e": 25077, "s": 25069, "text": "Python3" }, { "code": "# Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new rect for first objectplayer_rect = Rect(200, 500, 50, 50) # Creating a new rect for second objectplayer_rect2 = Rect(200, 0, 50, 50) # Creating variable for gravitygravity = 4 # Creating a boolean variable that# we will use to run the while looprun = True # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 60fps clock.tick(60) # Adding gravity in player_rect2 player_rect2.bottom += gravity # Checking if player is colliding # with platform or not using the # colliderect() method. # It will return a boolean value collide = pygame.Rect.colliderect(player_rect, p layer_rect2) # If the objects are colliding # then changing the y coordinate if collide: player_rect2.bottom = player_rect.top # Drawing player rect pygame.draw.rect(window, (0, 255, 0), player_rect) # Drawing player rect2 pygame.draw.rect(window, (0, 0, 255), player_rect2) # Updating the display surface pygame.display.update() # Filling the window with white color window.fill((255, 255, 255))", "e": 26586, "s": 25077, "text": null }, { "code": null, "e": 26594, "s": 26586, "text": "Output:" }, { "code": null, "e": 26602, "s": 26594, "text": "Python3" }, { "code": "# Importing the pygame moduleimport pygamefrom pygame.locals import * # Initiate pygame and give permission# to use pygame's functionalitypygame.init() # Create a display surface object# of specific dimensionwindow = pygame.display.set_mode((600, 600)) # Creating a new clock object to# track the amount of timeclock = pygame.time.Clock() # Creating a new rect for first objectplayer_rect = Rect(200, 500, 50, 50) # Creating a new rect for second objectplayer_rect2 = Rect(200, 0, 50, 50) # Creating a boolean variable that# we will use to run the while looprun = True # Speed for the objectsspeed_a = 8speed_b = -7 # Creating an infinite loop# to run our gamewhile run: # Setting the framerate to 60fps clock.tick(60) # Adding speed in player rects player_rect.bottom += speed_a player_rect2.top += speed_b # Checking if player is colliding # with platform or not using the # colliderect() method. # It will return a boolean value collide = pygame.Rect.colliderect(player_rect, player_rect2) # If the objects are colliding # then changing the speed direction if collide: speed_a *= -1 speed_b *= -1 # Changing the direction if the objects # goes outside the window if player_rect.top<0 or player_rect.bottom > 600: speed_a *= -1 if player_rect2.bottom > 600 or player_rect2.top<0: speed_b *= -1 # Drawing player rect pygame.draw.rect(window, (0, 255, 0), player_rect) # Drawing player rect2 pygame.draw.rect(window, (0, 0, 255), player_rect2) # Updating the display surface pygame.display.update() # Filling the window with white color window.fill((255, 255, 255))", "e": 28370, "s": 26602, "text": null }, { "code": null, "e": 28378, "s": 28370, "text": "Output:" }, { "code": null, "e": 28387, "s": 28378, "text": "sweetyty" }, { "code": null, "e": 28403, "s": 28387, "text": "simranarora5sos" }, { "code": null, "e": 28417, "s": 28403, "text": "Python-PyGame" }, { "code": null, "e": 28424, "s": 28417, "text": "Python" }, { "code": null, "e": 28522, "s": 28424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28531, "s": 28522, "text": "Comments" }, { "code": null, "e": 28544, "s": 28531, "text": "Old Comments" }, { "code": null, "e": 28562, "s": 28544, "text": "Python Dictionary" }, { "code": null, "e": 28594, "s": 28562, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28629, "s": 28594, "text": "Read a file line by line in Python" }, { "code": null, "e": 28651, "s": 28629, "text": "Enumerate() in Python" }, { "code": null, "e": 28681, "s": 28651, "text": "Iterate over a list in Python" }, { "code": null, "e": 28723, "s": 28681, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28766, "s": 28723, "text": "Python program to convert a list to string" }, { "code": null, "e": 28803, "s": 28766, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28829, "s": 28803, "text": "Python String | replace()" } ]
Print all n-digit strictly increasing numbers in C++
In this problem, we are given a number N and we have to print all n-digit numbers whose digits are strickly increasing from MSB to LSB i.e. the number at LSB (left) should be smaller than the number at right. Let’s take an example to understand the problem − Input − n = 2 Output − 01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89. Explanation − as you can see all the numbers at the left are smaller than the numbers at the right of them. To solve this problem, we will start from the MSB (left side) with numbers one by one and then generate numbers according to the condition. The next position will contain digits from i+1 to 9, i is the digit at the current position. The code to implement code logic − Live Demo #include <iostream> using namespace std; void printIncresingNumbers(int start, string out, int n) { if (n == 0){ cout<<out<<" "; return; } for (int i = start; i <= 9; i++){ string str = out + to_string(i); printIncresingNumbers(i + 1, str, n - 1); } } int main() { int n = 3; cout<<"All "<<n<<" digit strictly increasing numbers are :\n"; printIncresingNumbers(0, "", n); return 0; } All 3 digit strictly increasing numbers are − 012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568 569 578 579 589 678 679 689 789
[ { "code": null, "e": 1271, "s": 1062, "text": "In this problem, we are given a number N and we have to print all n-digit numbers whose digits are strickly increasing from MSB to LSB i.e. the number at LSB (left) should be smaller than the number at right." }, { "code": null, "e": 1321, "s": 1271, "text": "Let’s take an example to understand the problem −" }, { "code": null, "e": 1335, "s": 1321, "text": "Input − n = 2" }, { "code": null, "e": 1344, "s": 1335, "text": "Output −" }, { "code": null, "e": 1481, "s": 1344, "text": "01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 \n29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89." }, { "code": null, "e": 1589, "s": 1481, "text": "Explanation − as you can see all the numbers at the left are smaller than the numbers at the right of them." }, { "code": null, "e": 1822, "s": 1589, "text": "To solve this problem, we will start from the MSB (left side) with numbers one by one and then generate numbers according to the condition. The next position will contain digits from i+1 to 9, i is the digit at the current position." }, { "code": null, "e": 1857, "s": 1822, "text": "The code to implement code logic −" }, { "code": null, "e": 1868, "s": 1857, "text": " Live Demo" }, { "code": null, "e": 2300, "s": 1868, "text": "#include <iostream>\nusing namespace std;\nvoid printIncresingNumbers(int start, string out, int n) {\n if (n == 0){\n cout<<out<<\" \";\n return;\n }\n for (int i = start; i <= 9; i++){\n string str = out + to_string(i);\n printIncresingNumbers(i + 1, str, n - 1);\n }\n}\nint main() {\n int n = 3;\n cout<<\"All \"<<n<<\" digit strictly increasing numbers are :\\n\";\n printIncresingNumbers(0, \"\", n);\n return 0;\n}" }, { "code": null, "e": 2832, "s": 2300, "text": "All 3 digit strictly increasing numbers are −\n012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 \n037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 \n123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 \n156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 \n247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 \n356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 \n479 489 567 568 569 578 579 589 678 679 689 789" } ]
C Program on two-dimensional array initialized at run time
Calculate the sum and product of all elements in an array by using the run-time compilation. A two-dimensional array is used in situations where a table of values have to be stored (or) in matrices applications The syntax is as follows − datatype array_ name [rowsize] [column size]; For example, int a[5] [5]; Number of elements in array = rowsize *columnsize = 5*5 = 25 Following is the C program to calculate the sum and product of all elements in an array by using the run-time compilation − Live Demo #include<stdio.h> void main(){ //Declaring the array - run time// int A[2][3],B[2][3],i,j,sum[i][j],product[i][j]; //Reading elements into the array's A and B using for loop// printf("Enter elements into the array A: \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("A[%d][%d] :",i,j); scanf("%d",&A[i][j]); } printf("\n"); } for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("B[%d][%d] :",i,j); scanf("%d",&B[i][j]); } printf("\n"); } //Calculating sum and printing output// printf("Sum array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ sum[i][j]=A[i][j]+B[i][j]; printf("%d\t",sum[i][j]); } printf("\n"); } //Calculating product and printing output// printf("Product array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ product[i][j]=A[i][j]*B[i][j]; printf("%d\t",product[i][j]); } printf("\n"); } } When the above program is executed, it produces the following result − Enter elements into the array A: A[0][0] :12 A[0][1] :23 A[0][2] :03 A[1][0] :25 A[1][1] :34 A[1][2] :01 B[0][0] :03 B[0][1] :46 B[0][2] :23 B[1][0] :01 B[1][1] :24 B[1][2] :32 Sum array is: 15 69 26 26 58 33 Product array is: 36 1058 69 25 816 32
[ { "code": null, "e": 1155, "s": 1062, "text": "Calculate the sum and product of all elements in an array by using the run-time compilation." }, { "code": null, "e": 1273, "s": 1155, "text": "A two-dimensional array is used in situations where a table of values have to be stored (or) in matrices applications" }, { "code": null, "e": 1300, "s": 1273, "text": "The syntax is as follows −" }, { "code": null, "e": 1346, "s": 1300, "text": "datatype array_ name [rowsize] [column size];" }, { "code": null, "e": 1373, "s": 1346, "text": "For example, int a[5] [5];" }, { "code": null, "e": 1434, "s": 1373, "text": "Number of elements in array = rowsize *columnsize = 5*5 = 25" }, { "code": null, "e": 1558, "s": 1434, "text": "Following is the C program to calculate the sum and product of all elements in an array by using the run-time compilation −" }, { "code": null, "e": 1569, "s": 1558, "text": " Live Demo" }, { "code": null, "e": 2560, "s": 1569, "text": "#include<stdio.h>\nvoid main(){\n //Declaring the array - run time//\n int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];\n //Reading elements into the array's A and B using for loop//\n printf(\"Enter elements into the array A: \\n\");\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n printf(\"A[%d][%d] :\",i,j);\n scanf(\"%d\",&A[i][j]);\n }\n printf(\"\\n\");\n }\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n printf(\"B[%d][%d] :\",i,j);\n scanf(\"%d\",&B[i][j]);\n }\n printf(\"\\n\");\n }\n //Calculating sum and printing output//\n printf(\"Sum array is : \\n\");\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n sum[i][j]=A[i][j]+B[i][j];\n printf(\"%d\\t\",sum[i][j]);\n }\n printf(\"\\n\");\n }\n //Calculating product and printing output//\n printf(\"Product array is : \\n\");\n for(i=0;i<2;i++){\n for(j=0;j<3;j++){\n product[i][j]=A[i][j]*B[i][j];\n printf(\"%d\\t\",product[i][j]);\n }\n printf(\"\\n\");\n }\n}" }, { "code": null, "e": 2631, "s": 2560, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2906, "s": 2631, "text": "Enter elements into the array A:\nA[0][0] :12\nA[0][1] :23\nA[0][2] :03\n\nA[1][0] :25\nA[1][1] :34\nA[1][2] :01\n\nB[0][0] :03\nB[0][1] :46\nB[0][2] :23\n\nB[1][0] :01\nB[1][1] :24\nB[1][2] :32\n\nSum array is:\n15 69 26\n26 58 33\nProduct array is:\n36 1058 69\n25 816 32" } ]
Interactive basketball data visualizations with Plotly | by JP Hwang | Towards Data Science
This post is mostly about visualisation. It is only going to include very cursory basketball info — basically, if you know what it is, you’re going to be fine. I have been tinkering with basketball data analysis & visualisation recently, using matplotlib for plotting. It is powerful, but Plotly is my usual visualisation package of choice. In my opinion, Plotly achieves the right balance of power and customisability, written in sensible, intuitive syntax with great documentation and development rate. So I recently migrated my basketball visualisation scripts to Plotly, with great results. In this article, I would like to share some of that, including examples using both Plotly and Plotly Express. I included the code for this in my GitLab repo here (basketball_plots directory), so please feel free to download it and play with it / improve upon it. As this article is mainly about visualization, I will include my pre-processed data outputs in my repo for all 30 teams & league average. I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky, though. You’ll need plotly. Install it (in your virtual environment) with a simple pip install plotly. Professional basketball players in the NBA take shots from right at the rim, to past the three-point line, which is about 24 feet away from it. I wanted to understand how the distance affects accuracy of shots, and how often players shoot from each distance, and see if there is a pattern. This is a relatively straightforward exercise, so let’s use Plotly Express. Plotly Express is a fairly new package, and is all about producing charts more quickly and efficiently, so you can focus on the data exploration. (You can read more about it here) I have a database of all shot locations for an entire season (2018–2019 season) of shots, which is about 220,000 shots. The database includes locations of each shot, and whether it was successful (made) or not. Using this data, I produced a summary (league_shots_by_dist.csv), which includes shots grouped by distance in 1-foot bins (up to 32 feet), and columns for shots_made, shots_counts, shots_acc and avg_dist. So let’s explore this data — simply load the data with: import pandas as pdgrouped_shots_df = pd.read_csv('srcdata/league_shots_by_dist.csv') And then after importing the package, running just the two lines of code below will magically open an interactive scatter chart on your browser. import plotly.express as pxfig = px.scatter(grouped_shots_df, x="avg_dist", y="shots_accuracy")fig.show() To see how often players shoot from each distance, let’s add the frequency data: simply pass shots_counts value to the ‘size' parameter, and specify a maximum bubble size. fig = px.scatter(grouped_shots_df, x="avg_dist", y="shots_accuracy", size="shots_counts", size_max=25)fig.show() That’s intersting. The frequency (bubble size) decreases, and then picks back up again. Why is that? Well, we know that as we get farther, some of these are two point shots, some are three pointers, and some are a mix of the two. So let’s try colouring the variables by the shot type. fig = px.scatter(grouped_shots_df, x="avg_dist", y="shots_accuracy", size="shots_counts", color='shot_type', size_max=25)fig.show() Ah, there it is. It looks like the shot frequency increases as players try to take advantage of the three point line. Edit: here’s a live demo Try moving your mouse over each point — you will be pleasantly rewarded with a text tooltip! You didn’t even have to set anything up. Moving your cursor and looking at the individual points, the data tells us that shot accuracy doesn’t change greatly past 5 to 10 feet from the basket. By shooting threes, the players are trading off about a 15% decrease in shot accuracy for a 50% more reward of a three pointer. It makes sense that three pointers are more popular than these ‘mid-range’ two pointers. That’s not exactly a groundbreaking conclusion, but it’s still neat to be able to see it for ourselves. But more importantly, wasn’t that insanely simple? We created the last chart with just two lines of code! As long as you have a ‘tidy’ dateframe that has been pre-processed, Plotly Express allows fast visualisations like this, which you can work from. It’s a fantastic tool for data exploration. Let’s move onto another chart, called hexbin charts. I’ve discussed it elsewhere, but hexbin charts allow area-based visualisation of data, by dividing an entire area into hexagon-sized grids and displaying data by their colour (and also sometimes size) like so. While Plotly does not natively provide functions to compile hexbin data from coordinate-based data points, it does not matter for us because a) matplotlib does (read about the Polycollection that is returned by matplotlib here, if you are interested), and b) I will be providing the dataset for use here. Okay, so let’s move straight onto visualisation of the hexbin data: I have saved the data in a dictionary format. Simply load the data with: import picklewith open('srcdata/league_hexbin_stats.pickle', 'rb') as f: league_hexbin_stats = pickle.load(f) The dictionary contains these keys (see for yourself with print(league_hexbin_stats.keys()): ['xlocs', 'ylocs', 'shots_by_hex', 'freq_by_hex', 'accs_by_hex', 'shot_ev_by_hex', 'gridsize', 'n_shots'] The important ones are: x & y location data xlocs, ylocs, frequency data freq_by_hex and accuracy data accs_by_hex. Each of these include data from each hexagon, except for accuracy data, which I have averaged into “zones” to smooth out local variations. You’ll know what I mean when you see the plots. Note: The X/Y data are as captured originally, according to the standard coordinate system. I base everything else from it. Basically, the centre of the rim is at (0, 0) and 1 in X & Y coordinates appears to be 1/10th of a foot. Let’s plot those. This time we will use plotly.graph_objects, for the extra flexibility it gives us. It leads to writing slightly longer code, but don’t worry — it’s still not very long, and it will be totally worth it. Let’s go through this. The first few lines are obvious — I am just giving a few values new names, so that I can reuse the plotting code more easily. go.Figure() creates and returns a new figure, which we assign to fig. Then we add a new scatter plot, with markers mode (i.e. no lines), and we specify parameters for those markers, including passing arrays/lists to be our sizes and colours. The sizeref parameter gives a reference size to scale the rest of the sizes — I basically just play with this to get the right size, and sizemode refers to how the sizing works — whether the size should vary by area, or diameter. The convention is that ‘area’ should be used, as changing the diameter according to the variable would change the area by the square of that value, and would exaggerate the differences. We also specify the marker symbol as a hexagon (it is a hexbin plot, after all), and add a line on the outside of the hexagon for visual impact. Looks... almost like a shot chart (or a message from our alien overlords), although obviously problematic. Where is the court, and why is the ratio funny? It’s impossible to know what the colours mean. The mouseover tooltips just show me the X-Y coordinates, which is not very helpful. Let’s get to fixing those: Luckily, Plotly provides a set of handy commands to draw whatever you want. By using the method fig.update_figure, and passing a list to the shapes parameter, it’s pretty easy to draw whatever you would like. I based the court dimensions on this handy wikipedia figure, and the court was created with a mix of rectangles, circles and lines. I won’t go through the mundane details, but here are a couple of things you might find interesting: One thing that I had trouble figuring out was drawing SVG arcs, but this post on the plotly forum helped me out. It turns out plotly.js does not natively support arcs! Plotly allows me to fix the x & y ratio — I have disabled zoom here, but if it wasn’t, you can fix the y-axis to the x-axis using: yaxis=dict(scaleanchor=”x”, scaleratio=1). Running the same command as above, but simply inserting draw_plotly_court(fig) between fig = go.Figure(), and fig.add_trace(..., we get: Although much improved, we can’t make much of the data. The colour scale , and the size scale are both not great. To remedy these, we’ll: ‘Clip’ the frequency values — by manually limiting values to mymax_freq value, with a list comprehension. Introduce a different colour scale. I wanted to use a ‘sequential’ scale, as this shows changing positive values. This page shows all of the standard palettes that comes with Plotly. I chose ‘YlOrRd’. Specify a max/min value for the colours, and Add a legend on the plot. I chose to specify just the top/bottom tick values, and add the characters + and - to indicate that they are clipped. Running the below code, you should be able to generate this chart. If you move your mouse over the chart, you’ll tooltips even in areas where the frequency value in my hexbin data is zero (see bottom right image). Also, the tooltip data isn’t currently very useful — it’s just X&Y coordinates. What can we do? First of all, let’s just not have values at all where the frequencies are zero. I wrote a simple function filt_hexbins to filter the hexbin data, so that if the frequency data is zero, it just deletes those values from all arrays of the same length. And for the tooltip, we simply pass a text list to the parameter text. Also change the hoverinfo parameter value to text, and you’re good to go! The text string can include basic HTML like <i>, <b> or <br> tags, so try them out also. Putting it together, we get this code, and this chart, with the improved, informative, tooltip. This means that you can move your mouse over any value (or scatter plot) and get any number of different information back out! Nifty. For completeness, let’s look at one last example where we will compare data of a team against the league average data. This example will also allow us to look at diverging colour scales as well, which are very handy. We’ll also add a bitmap of a team logo to the figure to complete the look. Load the data, just as we have done previously, but this time loading the file for the Hoston Rockets. teamname = 'HOU'with open('srcdata/hou_hexbin_stats.pickle', 'rb') as f: team_hexbin_stats = pickle.load(f) For this plot, we’re going to keep the original team data for everything except the shot accuracy. We will convert the shot accuracy data to be relative, meaning we’ll compare it against the league average. To do this, we use: from copy import deepcopyrel_hexbin_stats = deepcopy(team_hexbin_stats)base_hexbin_stats = deepcopy(league_hexbin_stats)rel_hexbin_stats['accs_by_hex'] = rel_hexbin_stats['accs_by_hex'] - base_hexbin_stats['accs_by_hex'] You might be wondering why I’m using deepcopy. The reason is that due to the way python works, if I had simply copied team_hexbin_stats to rel_hexbin_stats, any modifications to the values in rel_hexbin_stats would have also applied to the original dictionary also (read more here). I could have just modified team_hexbin_stats, since we will not be using it again in this tutorial, but it’s just bad practice and can lead to confusion. Using the modified rel_hexbin_stats, we can go on with rest of the processing — you know the drill by now. The only changes are to the colourmap, to a diverging map of RdYlBu_r (reversed as I want red to be ‘good), and change the scale to be from -10% to 10% as we show relative percentages. Lastly, let’s add the team logo. Basketball-reference has a handy, standardised URI structure for the team logos, so I simply refer to those with the ‘teamname’ variable. And then, it’s a simple matter of adding the images you desire with the .add_layout_image method, specifying its size, placement and layer order. The entire code for this version looks like this: And look at these shot charts — glorious! I can’t embed an interactive version here, but I’m pretty happy with how they turned out. (Edit: here’s a live demo (for TOR) — also for GSW, HOU, SAS and NYK) As you can see, it’s really quite straightforward to plot spatial data using Plotly. What’s more, between Plotly Express and Plotly, you have a range of options that are sure to meet your requirements, whether they be quick & dirty data exploration, or in-depth, customised visualisations for your client. Try it out for yourself, I’ve plotted the Finals’ teams, but you can have a look at your own teams in the repo. I include data for all the teams in it. I think you’ll be impressed by how easy Plotly makes visualisation, while being incredibly powerful and flexible. That’s all from me — I hope you found it useful, and hit me up if you have any questions or comments! I’m not sure what the best way to structure python files for a tutorial like this is, but I’ve just written everything in one file, so you can just comment / uncomment as you’d like and follow along. If you liked this, say 👋 / follow on twitter, or follow for updates. I also wrote last week about producing interactive maps with Plotly.
[ { "code": null, "e": 332, "s": 172, "text": "This post is mostly about visualisation. It is only going to include very cursory basketball info — basically, if you know what it is, you’re going to be fine." }, { "code": null, "e": 513, "s": 332, "text": "I have been tinkering with basketball data analysis & visualisation recently, using matplotlib for plotting. It is powerful, but Plotly is my usual visualisation package of choice." }, { "code": null, "e": 677, "s": 513, "text": "In my opinion, Plotly achieves the right balance of power and customisability, written in sensible, intuitive syntax with great documentation and development rate." }, { "code": null, "e": 877, "s": 677, "text": "So I recently migrated my basketball visualisation scripts to Plotly, with great results. In this article, I would like to share some of that, including examples using both Plotly and Plotly Express." }, { "code": null, "e": 1030, "s": 877, "text": "I included the code for this in my GitLab repo here (basketball_plots directory), so please feel free to download it and play with it / improve upon it." }, { "code": null, "e": 1168, "s": 1030, "text": "As this article is mainly about visualization, I will include my pre-processed data outputs in my repo for all 30 teams & league average." }, { "code": null, "e": 1284, "s": 1168, "text": "I assume you’re familiar with python. Even if you’re relatively new, this tutorial shouldn’t be too tricky, though." }, { "code": null, "e": 1379, "s": 1284, "text": "You’ll need plotly. Install it (in your virtual environment) with a simple pip install plotly." }, { "code": null, "e": 1669, "s": 1379, "text": "Professional basketball players in the NBA take shots from right at the rim, to past the three-point line, which is about 24 feet away from it. I wanted to understand how the distance affects accuracy of shots, and how often players shoot from each distance, and see if there is a pattern." }, { "code": null, "e": 1925, "s": 1669, "text": "This is a relatively straightforward exercise, so let’s use Plotly Express. Plotly Express is a fairly new package, and is all about producing charts more quickly and efficiently, so you can focus on the data exploration. (You can read more about it here)" }, { "code": null, "e": 2136, "s": 1925, "text": "I have a database of all shot locations for an entire season (2018–2019 season) of shots, which is about 220,000 shots. The database includes locations of each shot, and whether it was successful (made) or not." }, { "code": null, "e": 2341, "s": 2136, "text": "Using this data, I produced a summary (league_shots_by_dist.csv), which includes shots grouped by distance in 1-foot bins (up to 32 feet), and columns for shots_made, shots_counts, shots_acc and avg_dist." }, { "code": null, "e": 2397, "s": 2341, "text": "So let’s explore this data — simply load the data with:" }, { "code": null, "e": 2483, "s": 2397, "text": "import pandas as pdgrouped_shots_df = pd.read_csv('srcdata/league_shots_by_dist.csv')" }, { "code": null, "e": 2628, "s": 2483, "text": "And then after importing the package, running just the two lines of code below will magically open an interactive scatter chart on your browser." }, { "code": null, "e": 2734, "s": 2628, "text": "import plotly.express as pxfig = px.scatter(grouped_shots_df, x=\"avg_dist\", y=\"shots_accuracy\")fig.show()" }, { "code": null, "e": 2906, "s": 2734, "text": "To see how often players shoot from each distance, let’s add the frequency data: simply pass shots_counts value to the ‘size' parameter, and specify a maximum bubble size." }, { "code": null, "e": 3019, "s": 2906, "text": "fig = px.scatter(grouped_shots_df, x=\"avg_dist\", y=\"shots_accuracy\", size=\"shots_counts\", size_max=25)fig.show()" }, { "code": null, "e": 3304, "s": 3019, "text": "That’s intersting. The frequency (bubble size) decreases, and then picks back up again. Why is that? Well, we know that as we get farther, some of these are two point shots, some are three pointers, and some are a mix of the two. So let’s try colouring the variables by the shot type." }, { "code": null, "e": 3436, "s": 3304, "text": "fig = px.scatter(grouped_shots_df, x=\"avg_dist\", y=\"shots_accuracy\", size=\"shots_counts\", color='shot_type', size_max=25)fig.show()" }, { "code": null, "e": 3554, "s": 3436, "text": "Ah, there it is. It looks like the shot frequency increases as players try to take advantage of the three point line." }, { "code": null, "e": 3579, "s": 3554, "text": "Edit: here’s a live demo" }, { "code": null, "e": 3713, "s": 3579, "text": "Try moving your mouse over each point — you will be pleasantly rewarded with a text tooltip! You didn’t even have to set anything up." }, { "code": null, "e": 4082, "s": 3713, "text": "Moving your cursor and looking at the individual points, the data tells us that shot accuracy doesn’t change greatly past 5 to 10 feet from the basket. By shooting threes, the players are trading off about a 15% decrease in shot accuracy for a 50% more reward of a three pointer. It makes sense that three pointers are more popular than these ‘mid-range’ two pointers." }, { "code": null, "e": 4186, "s": 4082, "text": "That’s not exactly a groundbreaking conclusion, but it’s still neat to be able to see it for ourselves." }, { "code": null, "e": 4292, "s": 4186, "text": "But more importantly, wasn’t that insanely simple? We created the last chart with just two lines of code!" }, { "code": null, "e": 4482, "s": 4292, "text": "As long as you have a ‘tidy’ dateframe that has been pre-processed, Plotly Express allows fast visualisations like this, which you can work from. It’s a fantastic tool for data exploration." }, { "code": null, "e": 4745, "s": 4482, "text": "Let’s move onto another chart, called hexbin charts. I’ve discussed it elsewhere, but hexbin charts allow area-based visualisation of data, by dividing an entire area into hexagon-sized grids and displaying data by their colour (and also sometimes size) like so." }, { "code": null, "e": 5050, "s": 4745, "text": "While Plotly does not natively provide functions to compile hexbin data from coordinate-based data points, it does not matter for us because a) matplotlib does (read about the Polycollection that is returned by matplotlib here, if you are interested), and b) I will be providing the dataset for use here." }, { "code": null, "e": 5118, "s": 5050, "text": "Okay, so let’s move straight onto visualisation of the hexbin data:" }, { "code": null, "e": 5191, "s": 5118, "text": "I have saved the data in a dictionary format. Simply load the data with:" }, { "code": null, "e": 5304, "s": 5191, "text": "import picklewith open('srcdata/league_hexbin_stats.pickle', 'rb') as f: league_hexbin_stats = pickle.load(f)" }, { "code": null, "e": 5397, "s": 5304, "text": "The dictionary contains these keys (see for yourself with print(league_hexbin_stats.keys()):" }, { "code": null, "e": 5503, "s": 5397, "text": "['xlocs', 'ylocs', 'shots_by_hex', 'freq_by_hex', 'accs_by_hex', 'shot_ev_by_hex', 'gridsize', 'n_shots']" }, { "code": null, "e": 5806, "s": 5503, "text": "The important ones are: x & y location data xlocs, ylocs, frequency data freq_by_hex and accuracy data accs_by_hex. Each of these include data from each hexagon, except for accuracy data, which I have averaged into “zones” to smooth out local variations. You’ll know what I mean when you see the plots." }, { "code": null, "e": 6035, "s": 5806, "text": "Note: The X/Y data are as captured originally, according to the standard coordinate system. I base everything else from it. Basically, the centre of the rim is at (0, 0) and 1 in X & Y coordinates appears to be 1/10th of a foot." }, { "code": null, "e": 6255, "s": 6035, "text": "Let’s plot those. This time we will use plotly.graph_objects, for the extra flexibility it gives us. It leads to writing slightly longer code, but don’t worry — it’s still not very long, and it will be totally worth it." }, { "code": null, "e": 6474, "s": 6255, "text": "Let’s go through this. The first few lines are obvious — I am just giving a few values new names, so that I can reuse the plotting code more easily. go.Figure() creates and returns a new figure, which we assign to fig." }, { "code": null, "e": 6646, "s": 6474, "text": "Then we add a new scatter plot, with markers mode (i.e. no lines), and we specify parameters for those markers, including passing arrays/lists to be our sizes and colours." }, { "code": null, "e": 6876, "s": 6646, "text": "The sizeref parameter gives a reference size to scale the rest of the sizes — I basically just play with this to get the right size, and sizemode refers to how the sizing works — whether the size should vary by area, or diameter." }, { "code": null, "e": 7062, "s": 6876, "text": "The convention is that ‘area’ should be used, as changing the diameter according to the variable would change the area by the square of that value, and would exaggerate the differences." }, { "code": null, "e": 7207, "s": 7062, "text": "We also specify the marker symbol as a hexagon (it is a hexbin plot, after all), and add a line on the outside of the hexagon for visual impact." }, { "code": null, "e": 7493, "s": 7207, "text": "Looks... almost like a shot chart (or a message from our alien overlords), although obviously problematic. Where is the court, and why is the ratio funny? It’s impossible to know what the colours mean. The mouseover tooltips just show me the X-Y coordinates, which is not very helpful." }, { "code": null, "e": 7520, "s": 7493, "text": "Let’s get to fixing those:" }, { "code": null, "e": 7729, "s": 7520, "text": "Luckily, Plotly provides a set of handy commands to draw whatever you want. By using the method fig.update_figure, and passing a list to the shapes parameter, it’s pretty easy to draw whatever you would like." }, { "code": null, "e": 7961, "s": 7729, "text": "I based the court dimensions on this handy wikipedia figure, and the court was created with a mix of rectangles, circles and lines. I won’t go through the mundane details, but here are a couple of things you might find interesting:" }, { "code": null, "e": 8129, "s": 7961, "text": "One thing that I had trouble figuring out was drawing SVG arcs, but this post on the plotly forum helped me out. It turns out plotly.js does not natively support arcs!" }, { "code": null, "e": 8303, "s": 8129, "text": "Plotly allows me to fix the x & y ratio — I have disabled zoom here, but if it wasn’t, you can fix the y-axis to the x-axis using: yaxis=dict(scaleanchor=”x”, scaleratio=1)." }, { "code": null, "e": 8440, "s": 8303, "text": "Running the same command as above, but simply inserting draw_plotly_court(fig) between fig = go.Figure(), and fig.add_trace(..., we get:" }, { "code": null, "e": 8554, "s": 8440, "text": "Although much improved, we can’t make much of the data. The colour scale , and the size scale are both not great." }, { "code": null, "e": 8578, "s": 8554, "text": "To remedy these, we’ll:" }, { "code": null, "e": 8684, "s": 8578, "text": "‘Clip’ the frequency values — by manually limiting values to mymax_freq value, with a list comprehension." }, { "code": null, "e": 8885, "s": 8684, "text": "Introduce a different colour scale. I wanted to use a ‘sequential’ scale, as this shows changing positive values. This page shows all of the standard palettes that comes with Plotly. I chose ‘YlOrRd’." }, { "code": null, "e": 8930, "s": 8885, "text": "Specify a max/min value for the colours, and" }, { "code": null, "e": 9074, "s": 8930, "text": "Add a legend on the plot. I chose to specify just the top/bottom tick values, and add the characters + and - to indicate that they are clipped." }, { "code": null, "e": 9141, "s": 9074, "text": "Running the below code, you should be able to generate this chart." }, { "code": null, "e": 9384, "s": 9141, "text": "If you move your mouse over the chart, you’ll tooltips even in areas where the frequency value in my hexbin data is zero (see bottom right image). Also, the tooltip data isn’t currently very useful — it’s just X&Y coordinates. What can we do?" }, { "code": null, "e": 9464, "s": 9384, "text": "First of all, let’s just not have values at all where the frequencies are zero." }, { "code": null, "e": 9634, "s": 9464, "text": "I wrote a simple function filt_hexbins to filter the hexbin data, so that if the frequency data is zero, it just deletes those values from all arrays of the same length." }, { "code": null, "e": 9868, "s": 9634, "text": "And for the tooltip, we simply pass a text list to the parameter text. Also change the hoverinfo parameter value to text, and you’re good to go! The text string can include basic HTML like <i>, <b> or <br> tags, so try them out also." }, { "code": null, "e": 10098, "s": 9868, "text": "Putting it together, we get this code, and this chart, with the improved, informative, tooltip. This means that you can move your mouse over any value (or scatter plot) and get any number of different information back out! Nifty." }, { "code": null, "e": 10315, "s": 10098, "text": "For completeness, let’s look at one last example where we will compare data of a team against the league average data. This example will also allow us to look at diverging colour scales as well, which are very handy." }, { "code": null, "e": 10390, "s": 10315, "text": "We’ll also add a bitmap of a team logo to the figure to complete the look." }, { "code": null, "e": 10493, "s": 10390, "text": "Load the data, just as we have done previously, but this time loading the file for the Hoston Rockets." }, { "code": null, "e": 10604, "s": 10493, "text": "teamname = 'HOU'with open('srcdata/hou_hexbin_stats.pickle', 'rb') as f: team_hexbin_stats = pickle.load(f)" }, { "code": null, "e": 10811, "s": 10604, "text": "For this plot, we’re going to keep the original team data for everything except the shot accuracy. We will convert the shot accuracy data to be relative, meaning we’ll compare it against the league average." }, { "code": null, "e": 10831, "s": 10811, "text": "To do this, we use:" }, { "code": null, "e": 11052, "s": 10831, "text": "from copy import deepcopyrel_hexbin_stats = deepcopy(team_hexbin_stats)base_hexbin_stats = deepcopy(league_hexbin_stats)rel_hexbin_stats['accs_by_hex'] = rel_hexbin_stats['accs_by_hex'] - base_hexbin_stats['accs_by_hex']" }, { "code": null, "e": 11335, "s": 11052, "text": "You might be wondering why I’m using deepcopy. The reason is that due to the way python works, if I had simply copied team_hexbin_stats to rel_hexbin_stats, any modifications to the values in rel_hexbin_stats would have also applied to the original dictionary also (read more here)." }, { "code": null, "e": 11489, "s": 11335, "text": "I could have just modified team_hexbin_stats, since we will not be using it again in this tutorial, but it’s just bad practice and can lead to confusion." }, { "code": null, "e": 11781, "s": 11489, "text": "Using the modified rel_hexbin_stats, we can go on with rest of the processing — you know the drill by now. The only changes are to the colourmap, to a diverging map of RdYlBu_r (reversed as I want red to be ‘good), and change the scale to be from -10% to 10% as we show relative percentages." }, { "code": null, "e": 12098, "s": 11781, "text": "Lastly, let’s add the team logo. Basketball-reference has a handy, standardised URI structure for the team logos, so I simply refer to those with the ‘teamname’ variable. And then, it’s a simple matter of adding the images you desire with the .add_layout_image method, specifying its size, placement and layer order." }, { "code": null, "e": 12148, "s": 12098, "text": "The entire code for this version looks like this:" }, { "code": null, "e": 12280, "s": 12148, "text": "And look at these shot charts — glorious! I can’t embed an interactive version here, but I’m pretty happy with how they turned out." }, { "code": null, "e": 12350, "s": 12280, "text": "(Edit: here’s a live demo (for TOR) — also for GSW, HOU, SAS and NYK)" }, { "code": null, "e": 12656, "s": 12350, "text": "As you can see, it’s really quite straightforward to plot spatial data using Plotly. What’s more, between Plotly Express and Plotly, you have a range of options that are sure to meet your requirements, whether they be quick & dirty data exploration, or in-depth, customised visualisations for your client." }, { "code": null, "e": 12922, "s": 12656, "text": "Try it out for yourself, I’ve plotted the Finals’ teams, but you can have a look at your own teams in the repo. I include data for all the teams in it. I think you’ll be impressed by how easy Plotly makes visualisation, while being incredibly powerful and flexible." }, { "code": null, "e": 13024, "s": 12922, "text": "That’s all from me — I hope you found it useful, and hit me up if you have any questions or comments!" }, { "code": null, "e": 13224, "s": 13024, "text": "I’m not sure what the best way to structure python files for a tutorial like this is, but I’ve just written everything in one file, so you can just comment / uncomment as you’d like and follow along." } ]
Filter table with Bootstrap
To filter a table in Bootstrap, you can try to run the following code − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Students Rank</h2> <input class = "form-control" id = "demo" type = "text" placeholder = "Seach here,.."> <br> <table class = "table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Marks</th> <th>Rank</th> </tr> </thead> <tbody id = "test"> <tr> <td>Amit</td> <td>94</td> <td>1</td> </tr> <tr> <td>Tom</td> <td>90</td> <td>2</td> </tr> <tr> <td>Steve</td> <td>88</td> <td>3</td> </tr> <tr> <td>Chris</td> <td>80</td> <td>4</td> </tr> <tr> <td>Corey</td> <td>79</td> <td>5</td> </tr> <tr> <td>Glenn</td> <td>75</td> <td>6</td> </tr> </tbody> </table> </div> <script> $(document).ready(function(){ $("#demo").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#test tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); </script> </body> </html>
[ { "code": null, "e": 1134, "s": 1062, "text": "To filter a table in Bootstrap, you can try to run the following code −" }, { "code": null, "e": 1144, "s": 1134, "text": "Live Demo" }, { "code": null, "e": 3087, "s": 1144, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Students Rank</h2>\n <input class = \"form-control\" id = \"demo\" type = \"text\" placeholder = \"Seach here,..\">\n <br>\n <table class = \"table table-bordered table-striped\">\n <thead>\n <tr>\n <th>Name</th>\n <th>Marks</th>\n <th>Rank</th>\n </tr>\n </thead>\n <tbody id = \"test\">\n <tr>\n <td>Amit</td>\n <td>94</td>\n <td>1</td>\n </tr>\n <tr>\n <td>Tom</td>\n <td>90</td>\n <td>2</td>\n </tr>\n <tr>\n <td>Steve</td>\n <td>88</td>\n <td>3</td>\n </tr>\n <tr>\n <td>Chris</td>\n <td>80</td>\n <td>4</td>\n </tr>\n <tr>\n <td>Corey</td>\n <td>79</td>\n <td>5</td>\n </tr>\n <tr>\n <td>Glenn</td>\n <td>75</td>\n <td>6</td>\n </tr>\n </tbody>\n </table>\n </div>\n <script>\n $(document).ready(function(){\n $(\"#demo\").on(\"keyup\", function() {\n var value = $(this).val().toLowerCase();\n $(\"#test tr\").filter(function() {\n $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)\n });\n });\n });\n </script>\n </body>\n</html>" } ]
C++ program to find the sum of the series 1 + 1/2^2 + 1/3^3 + .....+ 1/n^n
In this tutorial, we will be discussing a program to find the sum of the given series 1 + 1/2^2 + 1/3^3 + .....+ 1/n^n. For this, we will be given with the value of n and our task is to add up every term starting from the first one to find the sum of the given series. #include <iostream> #include <math.h> using namespace std; //calculating the sum of the series double calc_sum(int n) { int i; double sum = 0.0, ser; for (i = 1; i <= n; i++) ser = 1/ pow(i, i); sum += ser; return sum; } int main() { int n = 5; double res = calc_sum(n); cout << res << endl; return 0; } 0.00032
[ { "code": null, "e": 1182, "s": 1062, "text": "In this tutorial, we will be discussing a program to find the sum of the given series 1 + 1/2^2 + 1/3^3 + .....+ 1/n^n." }, { "code": null, "e": 1331, "s": 1182, "text": "For this, we will be given with the value of n and our task is to add up every term starting from the first one to find the sum of the given series." }, { "code": null, "e": 1665, "s": 1331, "text": "#include <iostream>\n#include <math.h>\nusing namespace std;\n//calculating the sum of the series\ndouble calc_sum(int n) {\n int i;\n double sum = 0.0, ser;\n for (i = 1; i <= n; i++)\n ser = 1/ pow(i, i);\n sum += ser;\n return sum;\n}\nint main() {\n int n = 5;\n double res = calc_sum(n);\n cout << res << endl;\n return 0;\n}" }, { "code": null, "e": 1673, "s": 1665, "text": "0.00032" } ]
Explain insertion of elements in linked list using C language
Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. They are defined as a collection of nodes. Here, nodes have two parts, which are data and link. The representation of data, link and linked lists is given below − There are three types of operations on linked lists in C language, which are as follows − Insertion Deletion Traversing Consider an example, wherein we insert node 5 in between node 2 and node 3. Now, insert node 5 at the beginning. Insert node 5 at the end. Insert node 5 at the end. Note: We cannot insert node 5 before node 2 as the nodes are not named. We can insert node 5 before 2, if its position is given. Following is the C program for inserting an element in linked list − Live Demo #include <stdio.h> #include <stdlib.h> struct node{ int val; struct node *next; }; void print_list(struct node *head){ printf("H->"); while(head){ printf("%d->", head->val); head = head->next; } printf("......\n\n"); } void insert_front(struct node **head, int value){ struct node * new_node = NULL; new_node = (struct node *)malloc(sizeof(struct node)); if (new_node == NULL){ printf(" Out of memory"); } new_node->val = value; new_node->next = *head; *head = new_node; } void insert_end(struct node **head, int value){ struct node * new_node = NULL; struct node * last = NULL; new_node = (struct node *)malloc(sizeof(struct node)); if (new_node == NULL){ printf(" Out of memory"); } new_node->val = value; new_node->next = NULL; if( *head == NULL){ *head = new_node; return; } last = *head; while(last->next) last = last->next; last->next = new_node; } void insert_after(struct node *head, int value, int after){ struct node * new_node = NULL; struct node *tmp = head; while(tmp) { if(tmp->val == after) { /*found the node*/ new_node = (struct node *)malloc(sizeof(struct node)); if (new_node == NULL) { printf("Out of memory"); } new_node->val = value; new_node->next = tmp->next; tmp->next = new_node; return; } tmp = tmp->next; } } void insert_before(struct node **head, int value, int before){ struct node * new_node = NULL; struct node * tmp = *head; new_node = (struct node *)malloc(sizeof(struct node)); if (new_node == NULL){ printf("Out of memory"); return; } new_node->val = value; if((*head)->val == before){ new_node->next = *head; *head = new_node; return; } while(tmp && tmp->next) { if(tmp->next->val == before) { new_node->next = tmp->next; tmp->next = new_node; return; } tmp = tmp->next; } /*Before node not found*/ free(new_node); } void main(){ int count = 0, i, val, after, before; struct node * head = NULL; printf("Enter no: of elements: "); scanf("%d", &count); for (i = 0; i < count; i++){ printf("Enter %dth element: ", i); scanf("%d", &val); insert_front(&head, val); } printf("starting list: "); print_list(head); printf("enter front element: "); scanf("%d", &val); insert_front(&head, val); printf("items after insertion: "); print_list(head); printf("enter last element: "); scanf("%d", &val); insert_end(&head, val); printf("items after insertion: "); print_list(head); printf("Enter an ele to insert in the list: "); scanf("%d", &val); printf("Insert after: "); scanf("%d", &after); insert_after(head, val, after); printf("List after insertion: "); print_list(head); printf("Enter an ele to insert in the list: "); scanf("%d", &val); printf("Insert before: "); scanf("%d", &before); insert_before(&head, val, before); printf("List after insertion: "); print_list(head); } When the above program is executed, it produces the following result − Enter no: of elements: 4 Enter 0th element: 1 Enter 1th element: 2 Enter 2th element: 3 Enter 3th element: 4 starting list: H->4->3->2->1->...... enter front element: 5 items after insertion: H->5->4->3->2->1->...... enter last element: 0 items after insertion: H->5->4->3->2->1->0->...... Enter an ele to insert in the list: 6 Insert after: 0 List after insertion: H->5->4->3->2->1->0->6->...... Enter an ele to insert in the list: 7 Insert before: 5 List after insertion: H->7->5->4->3->2->1->0->6->......
[ { "code": null, "e": 1307, "s": 1062, "text": "Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. They are defined as a collection of nodes. Here, nodes have two parts, which are data and link. The representation of data, link and linked lists is given below −" }, { "code": null, "e": 1397, "s": 1307, "text": "There are three types of operations on linked lists in C language, which are as follows −" }, { "code": null, "e": 1407, "s": 1397, "text": "Insertion" }, { "code": null, "e": 1416, "s": 1407, "text": "Deletion" }, { "code": null, "e": 1427, "s": 1416, "text": "Traversing" }, { "code": null, "e": 1503, "s": 1427, "text": "Consider an example, wherein we insert node 5 in between node 2 and node 3." }, { "code": null, "e": 1540, "s": 1503, "text": "Now, insert node 5 at the beginning." }, { "code": null, "e": 1566, "s": 1540, "text": "Insert node 5 at the end." }, { "code": null, "e": 1592, "s": 1566, "text": "Insert node 5 at the end." }, { "code": null, "e": 1598, "s": 1592, "text": "Note:" }, { "code": null, "e": 1664, "s": 1598, "text": "We cannot insert node 5 before node 2 as the nodes are not named." }, { "code": null, "e": 1721, "s": 1664, "text": "We can insert node 5 before 2, if its position is given." }, { "code": null, "e": 1790, "s": 1721, "text": "Following is the C program for inserting an element in linked list −" }, { "code": null, "e": 1801, "s": 1790, "text": " Live Demo" }, { "code": null, "e": 4948, "s": 1801, "text": "#include <stdio.h>\n#include <stdlib.h>\nstruct node{\n int val;\n struct node *next;\n};\nvoid print_list(struct node *head){\n printf(\"H->\");\n while(head){\n printf(\"%d->\", head->val);\n head = head->next;\n }\n printf(\"......\\n\\n\");\n}\nvoid insert_front(struct node **head, int value){\n struct node * new_node = NULL;\n new_node = (struct node *)malloc(sizeof(struct node));\n if (new_node == NULL){\n printf(\" Out of memory\");\n }\n new_node->val = value;\n new_node->next = *head;\n *head = new_node;\n}\nvoid insert_end(struct node **head, int value){\n struct node * new_node = NULL;\n struct node * last = NULL;\n new_node = (struct node *)malloc(sizeof(struct node));\n if (new_node == NULL){\n printf(\" Out of memory\");\n }\n new_node->val = value;\n new_node->next = NULL;\n if( *head == NULL){\n *head = new_node;\n return;\n }\n last = *head;\n while(last->next) last = last->next;\n last->next = new_node;\n}\nvoid insert_after(struct node *head, int value, int after){\n struct node * new_node = NULL;\n struct node *tmp = head;\n while(tmp) {\n if(tmp->val == after) { /*found the node*/\n new_node = (struct node *)malloc(sizeof(struct node));\n if (new_node == NULL) {\n printf(\"Out of memory\");\n }\n new_node->val = value;\n new_node->next = tmp->next;\n tmp->next = new_node;\n return;\n }\n tmp = tmp->next;\n }\n}\nvoid insert_before(struct node **head, int value, int before){\n struct node * new_node = NULL;\n struct node * tmp = *head;\n new_node = (struct node *)malloc(sizeof(struct node));\n if (new_node == NULL){\n printf(\"Out of memory\");\n return;\n }\n new_node->val = value;\n if((*head)->val == before){\n new_node->next = *head;\n *head = new_node;\n return;\n }\n while(tmp && tmp->next) {\n if(tmp->next->val == before) {\n new_node->next = tmp->next;\n tmp->next = new_node;\n return;\n }\n tmp = tmp->next;\n }\n /*Before node not found*/\n free(new_node);\n}\nvoid main(){\n int count = 0, i, val, after, before;\n struct node * head = NULL;\n printf(\"Enter no: of elements: \");\n scanf(\"%d\", &count);\n for (i = 0; i < count; i++){\n printf(\"Enter %dth element: \", i);\n scanf(\"%d\", &val);\n insert_front(&head, val);\n }\n printf(\"starting list: \");\n print_list(head);\n printf(\"enter front element: \");\n scanf(\"%d\", &val);\n insert_front(&head, val);\n printf(\"items after insertion: \");\n print_list(head);\n printf(\"enter last element: \");\n scanf(\"%d\", &val);\n insert_end(&head, val);\n printf(\"items after insertion: \");\n print_list(head);\n printf(\"Enter an ele to insert in the list: \");\n scanf(\"%d\", &val);\n printf(\"Insert after: \");\n scanf(\"%d\", &after);\n insert_after(head, val, after);\n printf(\"List after insertion: \");\n print_list(head);\n printf(\"Enter an ele to insert in the list: \");\n scanf(\"%d\", &val);\n printf(\"Insert before: \");\n scanf(\"%d\", &before);\n insert_before(&head, val, before);\n printf(\"List after insertion: \");\n print_list(head);\n}" }, { "code": null, "e": 5019, "s": 4948, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 5527, "s": 5019, "text": "Enter no: of elements: 4\nEnter 0th element: 1\nEnter 1th element: 2\nEnter 2th element: 3\nEnter 3th element: 4\nstarting list: H->4->3->2->1->......\nenter front element: 5\nitems after insertion: H->5->4->3->2->1->......\nenter last element: 0\nitems after insertion: H->5->4->3->2->1->0->......\nEnter an ele to insert in the list: 6\nInsert after: 0\nList after insertion: H->5->4->3->2->1->0->6->......\nEnter an ele to insert in the list: 7\nInsert before: 5\nList after insertion: H->7->5->4->3->2->1->0->6->......" } ]
An Introduction to PyTorch Lightning | by Harsh Maheshwari | Towards Data Science
Word on the street is that PyTorch lightning is a much better version of normal PyTorch. But what could it possibly have that it brought such consensus in our world? Well, it helps researchers scale the model with multi-GPU training, Fp-16 training, and TPU enabled training by changing just one argument. YESSSS you read that right. By changing just one argument, you can do all of these amazing things. Remember how we used to write a multi-GPU training code and had to learn about different training architectures PyTorch supports and then implement them ourselves. Thankfully, no more of that! PyTorch Lightning will change the way we write code and will help us code all these tasks in just a second. To cover all the changes I have structured this blog in the following way-: Overall Comparison between PyTorch and PyTorch Lightning for the difference in implementation Comparing each module like the model, loss function, etc. for PyTorch and PyTorch lightning Multi GPU Training TPU Training FP16 Training Early Stopping LR Finder The code chunks with the same color represent the implementation of the same module. For example, the model definition in both the framework is colored light green. The first thing to notice, PyTorch lightning has incorporated train_dataloader, configure_optimizers, training_step in the class Net itself. Also, note that the whole training loop that we write in PyTorch transfers to just a few lines in PyTorch lightning. In general, a deep learning code has the following components Model Data Loss Optimizer Train and Test Loop Logging Let’ understand the difference between PyTorch and PyTorch lightning with regards to the above-mentioned components. As we noticed above, the model architecture and definition is the same except that in Pytorch Lightning all the other function definitions are also in the same class. There could be two ways to define the data loader in Pytorch Lightning. You can define the train_dataloder and val_dataloader function within the Net class, as it was done earlier(in the first example) You can define your own train_dataloader and val_dataloader as in PyTorch, to trainer.fit as shown below. Using the above method, you can define data loaders for PyTorch as well as PyTorch lightning. The main difference between them is that the trainer.fit() in Pytorch Lightning takes all the data loaders as arguments. trainer.fit(net, train_dataloader, val_dataloader)trainer.test(net, test_dataloader) For n-class classification, we want to compute the cross-entropy loss. Cross-entropy is the same as NegativeLogLikelihood(log_softmax), so we will use that instead. Let’s use the Adam Optimizer. The self.parameters() passed here, include all the learnable parameters defined in the model. In PyTorch, we have to Define the training loop Load the data Pass the data through the model Compute loss Do zero_grad Backpropagate the loss function. However, in PyTorch lightning, we have to just Define the training_step and validation_step, where we define how we want the data to pass through the model Compute the loss We don’t even have to specify model.train() and model.eval(). Tensorboard is one of the most common loggers used by us researchers. So as you notice above in PyTorch lightning, in the last line of function training_step and validation_step, self.log() is mentioned, this is used to log the training loss. This creates a folder named lightning_logs and saves all the logs and epochs there. The model definition process is similar with two main differences. 1) All other functions are also defined with the model class itself for PyTorch lightning. 2) The nn.Module in Pytorch is overridden in PyTorch lightning by nn.LightningModule. Data Loader can be defined in the same way. For PyTorch lightning, we have to pass train_loader, and val_loader at the time of train.fit() Optimizer and loss can be defined the same way, but they need to be present as a function in the main class for PyTorch lightning. The training and validation loop are pre-defined in PyTorch lightning. We have to define training_step and validation_step, i.e., given a data point/batch, how would we like to pass the data through that model. A function for logging is pre-defined and can be directly called in Pytorch Lightning. Now that we know the difference between these two, let’s understand why we started this comparison in the first place. To make the code scalable and reduce our engineering efforts let’s look at the features of interest. We can do that using the code below. trainer = Trainer(gpus=8, distributed_backend='dp') You can define the number of GPUs you want to use for distributed training, and the backend you want to use. Here I have defined ‘dp’ which is Distributed Parallel. You can also define it as ‘ddp’, i.e. Distributed Data-Parallel. We can do that using the code below. trainer = Trainer(tpu_cores=[5]) This code means that the model will train on a TPU core with ID 5. We can also define how many cores we need to use by enabling multi-TPU training using a single argument. This is my favourite. FP16 helps to speed up the training process without compromising much on performance. trainer = Trainer(precision=16) This is used to stop the training when you don’t see any further improvement in model performance while training the model. How do we keep check if the model performance is improving or not? We can use validation loss or accuracy for that purpose. from pytorch_lightning.callbacks.early_stopping import EarlyStoppingdef validation_step(...): self.log('val_loss', loss)trainer = Trainer(callbacks=[EarlyStopping(monitor='val_loss', patience=3)]) In the above example, the trainer will track the validation accuracy. If there is no improvement in performance from the past 3 epochs (value of patience), then it will stop training and hence prevent overfitting. Learning rate is one of the most important hyperparameters, and it’s crucial to set the initial learning rate properly. Otherwise, it might happen that while training the model, the model converges to a local optimum that does not provide the best performance. net = LightningMNISTClassifier()# finds learning rate automatically# sets hparams.lr or hparams.learning_rate to that learning ratetrainer = Trainer(auto_lr_find=True)trainer.tune(net) To find optimal learning rate, you have to make the argument auto_lr_find True, and then tune the trainer (using trainer.tune()), this will help you find the learning rate. After that, you can call trainer.fit() for training the model. Just by adding a few arguments, Pytorch Lightning helps us enjoy a lot of functionality, and each one of them is very crucial for us. Now that you have a basic idea, start practicing PyTorch lightning by writing your first neural network and exploring different functionality that the library offers. If you want to learn cool applications of deep learning check out our blog on speech processing with deep learning here. Become a Medium member to unlock and read many other stories on medium. Follow us on Medium for reading more such blog posts.
[ { "code": null, "e": 478, "s": 172, "text": "Word on the street is that PyTorch lightning is a much better version of normal PyTorch. But what could it possibly have that it brought such consensus in our world? Well, it helps researchers scale the model with multi-GPU training, Fp-16 training, and TPU enabled training by changing just one argument." }, { "code": null, "e": 878, "s": 478, "text": "YESSSS you read that right. By changing just one argument, you can do all of these amazing things. Remember how we used to write a multi-GPU training code and had to learn about different training architectures PyTorch supports and then implement them ourselves. Thankfully, no more of that! PyTorch Lightning will change the way we write code and will help us code all these tasks in just a second." }, { "code": null, "e": 954, "s": 878, "text": "To cover all the changes I have structured this blog in the following way-:" }, { "code": null, "e": 1048, "s": 954, "text": "Overall Comparison between PyTorch and PyTorch Lightning for the difference in implementation" }, { "code": null, "e": 1140, "s": 1048, "text": "Comparing each module like the model, loss function, etc. for PyTorch and PyTorch lightning" }, { "code": null, "e": 1159, "s": 1140, "text": "Multi GPU Training" }, { "code": null, "e": 1172, "s": 1159, "text": "TPU Training" }, { "code": null, "e": 1186, "s": 1172, "text": "FP16 Training" }, { "code": null, "e": 1201, "s": 1186, "text": "Early Stopping" }, { "code": null, "e": 1211, "s": 1201, "text": "LR Finder" }, { "code": null, "e": 1376, "s": 1211, "text": "The code chunks with the same color represent the implementation of the same module. For example, the model definition in both the framework is colored light green." }, { "code": null, "e": 1634, "s": 1376, "text": "The first thing to notice, PyTorch lightning has incorporated train_dataloader, configure_optimizers, training_step in the class Net itself. Also, note that the whole training loop that we write in PyTorch transfers to just a few lines in PyTorch lightning." }, { "code": null, "e": 1696, "s": 1634, "text": "In general, a deep learning code has the following components" }, { "code": null, "e": 1702, "s": 1696, "text": "Model" }, { "code": null, "e": 1707, "s": 1702, "text": "Data" }, { "code": null, "e": 1712, "s": 1707, "text": "Loss" }, { "code": null, "e": 1722, "s": 1712, "text": "Optimizer" }, { "code": null, "e": 1742, "s": 1722, "text": "Train and Test Loop" }, { "code": null, "e": 1750, "s": 1742, "text": "Logging" }, { "code": null, "e": 1867, "s": 1750, "text": "Let’ understand the difference between PyTorch and PyTorch lightning with regards to the above-mentioned components." }, { "code": null, "e": 2034, "s": 1867, "text": "As we noticed above, the model architecture and definition is the same except that in Pytorch Lightning all the other function definitions are also in the same class." }, { "code": null, "e": 2106, "s": 2034, "text": "There could be two ways to define the data loader in Pytorch Lightning." }, { "code": null, "e": 2236, "s": 2106, "text": "You can define the train_dataloder and val_dataloader function within the Net class, as it was done earlier(in the first example)" }, { "code": null, "e": 2342, "s": 2236, "text": "You can define your own train_dataloader and val_dataloader as in PyTorch, to trainer.fit as shown below." }, { "code": null, "e": 2557, "s": 2342, "text": "Using the above method, you can define data loaders for PyTorch as well as PyTorch lightning. The main difference between them is that the trainer.fit() in Pytorch Lightning takes all the data loaders as arguments." }, { "code": null, "e": 2642, "s": 2557, "text": "trainer.fit(net, train_dataloader, val_dataloader)trainer.test(net, test_dataloader)" }, { "code": null, "e": 2807, "s": 2642, "text": "For n-class classification, we want to compute the cross-entropy loss. Cross-entropy is the same as NegativeLogLikelihood(log_softmax), so we will use that instead." }, { "code": null, "e": 2837, "s": 2807, "text": "Let’s use the Adam Optimizer." }, { "code": null, "e": 2931, "s": 2837, "text": "The self.parameters() passed here, include all the learnable parameters defined in the model." }, { "code": null, "e": 2954, "s": 2931, "text": "In PyTorch, we have to" }, { "code": null, "e": 2979, "s": 2954, "text": "Define the training loop" }, { "code": null, "e": 2993, "s": 2979, "text": "Load the data" }, { "code": null, "e": 3025, "s": 2993, "text": "Pass the data through the model" }, { "code": null, "e": 3038, "s": 3025, "text": "Compute loss" }, { "code": null, "e": 3051, "s": 3038, "text": "Do zero_grad" }, { "code": null, "e": 3084, "s": 3051, "text": "Backpropagate the loss function." }, { "code": null, "e": 3131, "s": 3084, "text": "However, in PyTorch lightning, we have to just" }, { "code": null, "e": 3240, "s": 3131, "text": "Define the training_step and validation_step, where we define how we want the data to pass through the model" }, { "code": null, "e": 3257, "s": 3240, "text": "Compute the loss" }, { "code": null, "e": 3319, "s": 3257, "text": "We don’t even have to specify model.train() and model.eval()." }, { "code": null, "e": 3646, "s": 3319, "text": "Tensorboard is one of the most common loggers used by us researchers. So as you notice above in PyTorch lightning, in the last line of function training_step and validation_step, self.log() is mentioned, this is used to log the training loss. This creates a folder named lightning_logs and saves all the logs and epochs there." }, { "code": null, "e": 3890, "s": 3646, "text": "The model definition process is similar with two main differences. 1) All other functions are also defined with the model class itself for PyTorch lightning. 2) The nn.Module in Pytorch is overridden in PyTorch lightning by nn.LightningModule." }, { "code": null, "e": 4029, "s": 3890, "text": "Data Loader can be defined in the same way. For PyTorch lightning, we have to pass train_loader, and val_loader at the time of train.fit()" }, { "code": null, "e": 4160, "s": 4029, "text": "Optimizer and loss can be defined the same way, but they need to be present as a function in the main class for PyTorch lightning." }, { "code": null, "e": 4371, "s": 4160, "text": "The training and validation loop are pre-defined in PyTorch lightning. We have to define training_step and validation_step, i.e., given a data point/batch, how would we like to pass the data through that model." }, { "code": null, "e": 4458, "s": 4371, "text": "A function for logging is pre-defined and can be directly called in Pytorch Lightning." }, { "code": null, "e": 4678, "s": 4458, "text": "Now that we know the difference between these two, let’s understand why we started this comparison in the first place. To make the code scalable and reduce our engineering efforts let’s look at the features of interest." }, { "code": null, "e": 4715, "s": 4678, "text": "We can do that using the code below." }, { "code": null, "e": 4767, "s": 4715, "text": "trainer = Trainer(gpus=8, distributed_backend='dp')" }, { "code": null, "e": 4997, "s": 4767, "text": "You can define the number of GPUs you want to use for distributed training, and the backend you want to use. Here I have defined ‘dp’ which is Distributed Parallel. You can also define it as ‘ddp’, i.e. Distributed Data-Parallel." }, { "code": null, "e": 5034, "s": 4997, "text": "We can do that using the code below." }, { "code": null, "e": 5067, "s": 5034, "text": "trainer = Trainer(tpu_cores=[5])" }, { "code": null, "e": 5239, "s": 5067, "text": "This code means that the model will train on a TPU core with ID 5. We can also define how many cores we need to use by enabling multi-TPU training using a single argument." }, { "code": null, "e": 5347, "s": 5239, "text": "This is my favourite. FP16 helps to speed up the training process without compromising much on performance." }, { "code": null, "e": 5379, "s": 5347, "text": "trainer = Trainer(precision=16)" }, { "code": null, "e": 5627, "s": 5379, "text": "This is used to stop the training when you don’t see any further improvement in model performance while training the model. How do we keep check if the model performance is improving or not? We can use validation loss or accuracy for that purpose." }, { "code": null, "e": 5827, "s": 5627, "text": "from pytorch_lightning.callbacks.early_stopping import EarlyStoppingdef validation_step(...): self.log('val_loss', loss)trainer = Trainer(callbacks=[EarlyStopping(monitor='val_loss', patience=3)])" }, { "code": null, "e": 6041, "s": 5827, "text": "In the above example, the trainer will track the validation accuracy. If there is no improvement in performance from the past 3 epochs (value of patience), then it will stop training and hence prevent overfitting." }, { "code": null, "e": 6302, "s": 6041, "text": "Learning rate is one of the most important hyperparameters, and it’s crucial to set the initial learning rate properly. Otherwise, it might happen that while training the model, the model converges to a local optimum that does not provide the best performance." }, { "code": null, "e": 6487, "s": 6302, "text": "net = LightningMNISTClassifier()# finds learning rate automatically# sets hparams.lr or hparams.learning_rate to that learning ratetrainer = Trainer(auto_lr_find=True)trainer.tune(net)" }, { "code": null, "e": 6723, "s": 6487, "text": "To find optimal learning rate, you have to make the argument auto_lr_find True, and then tune the trainer (using trainer.tune()), this will help you find the learning rate. After that, you can call trainer.fit() for training the model." }, { "code": null, "e": 7024, "s": 6723, "text": "Just by adding a few arguments, Pytorch Lightning helps us enjoy a lot of functionality, and each one of them is very crucial for us. Now that you have a basic idea, start practicing PyTorch lightning by writing your first neural network and exploring different functionality that the library offers." }, { "code": null, "e": 7145, "s": 7024, "text": "If you want to learn cool applications of deep learning check out our blog on speech processing with deep learning here." } ]
C++ nested loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting. The syntax for a nested for loop statement in C++ is as follows − for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); // you can put more statements. } The syntax for a nested while loop statement in C++ is as follows − while(condition) { while(condition) { statement(s); } statement(s); // you can put more statements. } The syntax for a nested do...while loop statement in C++ is as follows − do { statement(s); // you can put more statements. do { statement(s); } while( condition ); } while( condition ); The following program uses a nested for loop to find the prime numbers from 2 to 100 − #include <iostream> using namespace std; int main () { int i, j; for(i = 2; i<100; i++) { for(j = 2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) cout << i << " is prime\n"; } return 0; } This would produce the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2318, "text": "A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting." }, { "code": null, "e": 2472, "s": 2406, "text": "The syntax for a nested for loop statement in C++ is as follows −" }, { "code": null, "e": 2626, "s": 2472, "text": "for ( init; condition; increment ) {\n for ( init; condition; increment ) {\n statement(s);\n }\n statement(s); // you can put more statements.\n}\n" }, { "code": null, "e": 2694, "s": 2626, "text": "The syntax for a nested while loop statement in C++ is as follows −" }, { "code": null, "e": 2812, "s": 2694, "text": "while(condition) {\n while(condition) {\n statement(s);\n }\n statement(s); // you can put more statements.\n}\n" }, { "code": null, "e": 2885, "s": 2812, "text": "The syntax for a nested do...while loop statement in C++ is as follows −" }, { "code": null, "e": 3016, "s": 2885, "text": "do {\n statement(s); // you can put more statements.\n do {\n statement(s);\n } while( condition );\n\n} while( condition );\n" }, { "code": null, "e": 3103, "s": 3016, "text": "The following program uses a nested for loop to find the prime numbers from 2 to 100 −" }, { "code": null, "e": 3371, "s": 3103, "text": "#include <iostream>\nusing namespace std;\n \nint main () {\n int i, j;\n \n for(i = 2; i<100; i++) {\n for(j = 2; j <= (i/j); j++)\n if(!(i%j)) break; // if factor found, not prime\n if(j > (i/j)) cout << i << \" is prime\\n\";\n }\n \n return 0;\n}" }, { "code": null, "e": 3413, "s": 3371, "text": "This would produce the following result −" }, { "code": null, "e": 3710, "s": 3413, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n" }, { "code": null, "e": 3747, "s": 3710, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3766, "s": 3747, "text": " Arnab Chakraborty" }, { "code": null, "e": 3798, "s": 3766, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3821, "s": 3798, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3857, "s": 3821, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3874, "s": 3857, "text": " Frahaan Hussain" }, { "code": null, "e": 3909, "s": 3874, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3926, "s": 3909, "text": " Frahaan Hussain" }, { "code": null, "e": 3961, "s": 3926, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3978, "s": 3961, "text": " Frahaan Hussain" }, { "code": null, "e": 4013, "s": 3978, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4030, "s": 4013, "text": " Frahaan Hussain" }, { "code": null, "e": 4037, "s": 4030, "text": " Print" }, { "code": null, "e": 4048, "s": 4037, "text": " Add Notes" } ]
Multivalued Dependency (MVD) in DBMS - GeeksforGeeks
23 Feb, 2022 MVD or multivalued dependency means that for a single value of attribute ‘a’ multiple values of attribute ‘b’ exist. We write it as, a --> --> b It is read as: a is multi-valued dependent on b. Suppose a person named Geeks is working on 2 projects Microsoft and Oracle and has 2 hobbies namely Reading and Music. This can be expressed in a tabular format in the following way. Project and Hobby are multivalued attributes as they have more than one value for a single person i.e., Geeks. Multi Valued Dependency (MVD) :We can say that multivalued dependency exists if the following conditions are met. Conditions for MVD :Any attribute say a multiple define another attribute b; if any legal relation r(R), for all pairs of tuples t1 and t2 in r, such that, t1[a] = t2[a] Then there exists t3 and t4 in r such that. t1[a] = t2[a] = t3[a] = t4[a] t1[b] = t3[b]; t2[b] = t4[b] t1 = t4; t2 = t3 Then multivalued (MVD) dependency exists. To check the MVD in given table, we apply the conditions stated above and we check it with the values in the given table. Condition-1 for MVD – t1[a] = t2[a] = t3[a] = t4[a] Finding from table, t1[a] = t2[a] = t3[a] = t4[a] = Geeks So, condition 1 is Satisfied. Condition-2 for MVD – t1[b] = t3[b] And t2[b] = t4[b] Finding from table, t1[b] = t3[b] = MS And t2[b] = t4[b] = Oracle So, condition 2 is Satisfied. Condition-3 for MVD – ∃c ∈ R-(a ∪ b) where R is the set of attributes in the relational table. t1 = t4 And t2=t3 Finding from table, t1 = t4 = Reading And t2 = t3 = Music So, condition 3 is Satisfied. All conditions are satisfied, therefore, a --> --> b According to table we have got, name --> --> project And for, a --> --> C We get, name --> --> hobby Hence, we know that MVD exists in the above table and it can be stated by, name --> --> project name --> --> hobby the_rdx DBMS Write From Home DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS KDD Process in Data Mining Conflict Serializability in DBMS What is Temporary Table in SQL? Deadlock in DBMS 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": 24428, "s": 24400, "text": "\n23 Feb, 2022" }, { "code": null, "e": 24561, "s": 24428, "text": "MVD or multivalued dependency means that for a single value of attribute ‘a’ multiple values of attribute ‘b’ exist. We write it as," }, { "code": null, "e": 24574, "s": 24561, "text": "a --> --> b " }, { "code": null, "e": 24623, "s": 24574, "text": "It is read as: a is multi-valued dependent on b." }, { "code": null, "e": 24806, "s": 24623, "text": "Suppose a person named Geeks is working on 2 projects Microsoft and Oracle and has 2 hobbies namely Reading and Music. This can be expressed in a tabular format in the following way." }, { "code": null, "e": 24917, "s": 24806, "text": "Project and Hobby are multivalued attributes as they have more than one value for a single person i.e., Geeks." }, { "code": null, "e": 25031, "s": 24917, "text": "Multi Valued Dependency (MVD) :We can say that multivalued dependency exists if the following conditions are met." }, { "code": null, "e": 25187, "s": 25031, "text": "Conditions for MVD :Any attribute say a multiple define another attribute b; if any legal relation r(R), for all pairs of tuples t1 and t2 in r, such that," }, { "code": null, "e": 25202, "s": 25187, "text": "t1[a] = t2[a] " }, { "code": null, "e": 25246, "s": 25202, "text": "Then there exists t3 and t4 in r such that." }, { "code": null, "e": 25324, "s": 25246, "text": "t1[a] = t2[a] = t3[a] = t4[a]\nt1[b] = t3[b]; t2[b] = t4[b] \nt1 = t4; t2 = t3 " }, { "code": null, "e": 25366, "s": 25324, "text": "Then multivalued (MVD) dependency exists." }, { "code": null, "e": 25488, "s": 25366, "text": "To check the MVD in given table, we apply the conditions stated above and we check it with the values in the given table." }, { "code": null, "e": 25510, "s": 25488, "text": "Condition-1 for MVD –" }, { "code": null, "e": 25541, "s": 25510, "text": "t1[a] = t2[a] = t3[a] = t4[a] " }, { "code": null, "e": 25561, "s": 25541, "text": "Finding from table," }, { "code": null, "e": 25600, "s": 25561, "text": "t1[a] = t2[a] = t3[a] = t4[a] = Geeks " }, { "code": null, "e": 25630, "s": 25600, "text": "So, condition 1 is Satisfied." }, { "code": null, "e": 25652, "s": 25630, "text": "Condition-2 for MVD –" }, { "code": null, "e": 25687, "s": 25652, "text": "t1[b] = t3[b] \nAnd \nt2[b] = t4[b] " }, { "code": null, "e": 25707, "s": 25687, "text": "Finding from table," }, { "code": null, "e": 25756, "s": 25707, "text": "t1[b] = t3[b] = MS \nAnd \nt2[b] = t4[b] = Oracle " }, { "code": null, "e": 25786, "s": 25756, "text": "So, condition 2 is Satisfied." }, { "code": null, "e": 25808, "s": 25786, "text": "Condition-3 for MVD –" }, { "code": null, "e": 25903, "s": 25808, "text": "∃c ∈ R-(a ∪ b) where R is the set of attributes in the relational table.\nt1 = t4 \nAnd \nt2=t3 " }, { "code": null, "e": 25923, "s": 25903, "text": "Finding from table," }, { "code": null, "e": 25963, "s": 25923, "text": "t1 = t4 = Reading \nAnd\nt2 = t3 = Music " }, { "code": null, "e": 25993, "s": 25963, "text": "So, condition 3 is Satisfied." }, { "code": null, "e": 26034, "s": 25993, "text": "All conditions are satisfied, therefore," }, { "code": null, "e": 26047, "s": 26034, "text": "a --> --> b " }, { "code": null, "e": 26079, "s": 26047, "text": "According to table we have got," }, { "code": null, "e": 26101, "s": 26079, "text": "name --> --> project " }, { "code": null, "e": 26110, "s": 26101, "text": "And for," }, { "code": null, "e": 26123, "s": 26110, "text": "a --> --> C " }, { "code": null, "e": 26131, "s": 26123, "text": "We get," }, { "code": null, "e": 26151, "s": 26131, "text": "name --> --> hobby " }, { "code": null, "e": 26226, "s": 26151, "text": "Hence, we know that MVD exists in the above table and it can be stated by," }, { "code": null, "e": 26267, "s": 26226, "text": "name --> --> project\nname --> --> hobby " }, { "code": null, "e": 26275, "s": 26267, "text": "the_rdx" }, { "code": null, "e": 26280, "s": 26275, "text": "DBMS" }, { "code": null, "e": 26296, "s": 26280, "text": "Write From Home" }, { "code": null, "e": 26301, "s": 26296, "text": "DBMS" }, { "code": null, "e": 26399, "s": 26301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26440, "s": 26399, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 26467, "s": 26440, "text": "KDD Process in Data Mining" }, { "code": null, "e": 26500, "s": 26467, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 26532, "s": 26500, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26549, "s": 26532, "text": "Deadlock in DBMS" }, { "code": null, "e": 26585, "s": 26549, "text": "Convert integer to string in Python" }, { "code": null, "e": 26621, "s": 26585, "text": "Convert string to integer in Python" }, { "code": null, "e": 26682, "s": 26621, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26698, "s": 26682, "text": "Python infinity" } ]
Building a Simple Application using KivyMD in Python - GeeksforGeeks
01 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 will see how to make a simple application in KivyMDusing using Screen, Label, TextFieldInput, and Button. In order to start KivyMD, you must first install the Kivy framework on your computer. It can be installed using the below command: pip install kivymd We need to import the below widgets using kivyMD.uix library: MDLabel(): This widget is used in KivyMD applications to add a label or to display texts as a label. MDLabel(text, halign, theme_text_color, text_color, font_style) Parameters: text- The text we want to put on the label. halign- The position where we want to put the label. theme_text_color- The theme for text colors like custom, primary, secondary, hint, or error. text_color- If theme_text_color is custom we can assign text color to an RGB tuple. font_style- Like caption, headings. MDTextField(): This widget is used to add buttons in the KivyMD window. MDTextField(text, pos_hint) text- The text we want to put in the TextField. pos_hint- A dictionary having the position with respect to x-axis and y-axis. MDRectangleFlatButton(): This widget is used to add rectangular-shaped buttons to a KivyMD application. MDRectangleFlatButton(text, pos_hint, on_release) text- The text we want to put on the button. pos_hint- A dictionary having the position with respect to the x-axis and y-axis. on_release- It is a function that has the properties that we want to call on clicking the button. Let’s see the code for creating the simple app using the above-stated widgets and then we will discuss the code in detail. Python3 # importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.label import MDLabelfrom kivymd.uix.screen import Screenfrom kivymd.uix.textfield import MDTextFieldfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # defining label with all the parameters l = MDLabel(text="HI PEOPLE!", halign='center', theme_text_color="Custom", text_color=(0.5, 0, 0.5, 1), font_style='Caption') # defining Text field with all the parameters name = MDTextField(text="Enter name", pos_hint={ 'center_x': 0.8, 'center_y': 0.8}, size_hint_x=None, width=100) # defining Button with all the parameters btn = MDRectangleFlatButton(text="Submit", pos_hint={ 'center_x': 0.5, 'center_y': 0.3}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(name) screen.add_widget(btn) screen.add_widget(l) # 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: When the button is pressed it displays the following output in the command prompt: Explanation: This class Demo is derived from the App() class of the kivymd.app. This class is the base class for creating the kivyMD Application. It is basically the main entry point into the kivyMD run loop. Here the build() method “Initializes the application; it will be called only once. If this method returns a widget (tree), it will be used as the root widget and added to the window. Here in the build method firstly we define a screen for the widgets to be shown on it. Then we add the widgets one by oneLabel for the title or heading of the page.A text field for user input. You can add more text fields.A button for submitting or performing any function. Here on clicking submit button, a message is getting printed in console. We have made the function btnfunc() for the same. Label for the title or heading of the page. A text field for user input. You can add more text fields. A button for submitting or performing any function. Here on clicking submit button, a message is getting printed in console. We have made the function btnfunc() for the same. The Demo.run() is the run() method that launches the app in standalone mode and calls the class Demo which returns the screen. adnanirshad158 Python-gui python-modules 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": "\n01 Jun, 2021" }, { "code": null, "e": 24262, "s": 23901, "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 will see how to make a simple application in KivyMDusing using Screen, Label, TextFieldInput, and Button." }, { "code": null, "e": 24393, "s": 24262, "text": "In order to start KivyMD, you must first install the Kivy framework on your computer. It can be installed using the below command:" }, { "code": null, "e": 24412, "s": 24393, "text": "pip install kivymd" }, { "code": null, "e": 24474, "s": 24412, "text": "We need to import the below widgets using kivyMD.uix library:" }, { "code": null, "e": 24575, "s": 24474, "text": "MDLabel(): This widget is used in KivyMD applications to add a label or to display texts as a label." }, { "code": null, "e": 24639, "s": 24575, "text": "MDLabel(text, halign, theme_text_color, text_color, font_style)" }, { "code": null, "e": 24651, "s": 24639, "text": "Parameters:" }, { "code": null, "e": 24695, "s": 24651, "text": "text- The text we want to put on the label." }, { "code": null, "e": 24748, "s": 24695, "text": "halign- The position where we want to put the label." }, { "code": null, "e": 24841, "s": 24748, "text": "theme_text_color- The theme for text colors like custom, primary, secondary, hint, or error." }, { "code": null, "e": 24925, "s": 24841, "text": "text_color- If theme_text_color is custom we can assign text color to an RGB tuple." }, { "code": null, "e": 24961, "s": 24925, "text": "font_style- Like caption, headings." }, { "code": null, "e": 25033, "s": 24961, "text": "MDTextField(): This widget is used to add buttons in the KivyMD window." }, { "code": null, "e": 25061, "s": 25033, "text": "MDTextField(text, pos_hint)" }, { "code": null, "e": 25109, "s": 25061, "text": "text- The text we want to put in the TextField." }, { "code": null, "e": 25187, "s": 25109, "text": "pos_hint- A dictionary having the position with respect to x-axis and y-axis." }, { "code": null, "e": 25291, "s": 25187, "text": "MDRectangleFlatButton(): This widget is used to add rectangular-shaped buttons to a KivyMD application." }, { "code": null, "e": 25341, "s": 25291, "text": "MDRectangleFlatButton(text, pos_hint, on_release)" }, { "code": null, "e": 25386, "s": 25341, "text": "text- The text we want to put on the button." }, { "code": null, "e": 25468, "s": 25386, "text": "pos_hint- A dictionary having the position with respect to the x-axis and y-axis." }, { "code": null, "e": 25566, "s": 25468, "text": "on_release- It is a function that has the properties that we want to call on clicking the button." }, { "code": null, "e": 25689, "s": 25566, "text": "Let’s see the code for creating the simple app using the above-stated widgets and then we will discuss the code in detail." }, { "code": null, "e": 25697, "s": 25689, "text": "Python3" }, { "code": "# importing all necessary modules# like MDApp, MDLabel Screen, MDTextField# and MDRectangleFlatButtonfrom kivymd.app import MDAppfrom kivymd.uix.label import MDLabelfrom kivymd.uix.screen import Screenfrom kivymd.uix.textfield import MDTextFieldfrom kivymd.uix.button import MDRectangleFlatButton # creating Demo Class(base class)class Demo(MDApp): def build(self): screen = Screen() # defining label with all the parameters l = MDLabel(text=\"HI PEOPLE!\", halign='center', theme_text_color=\"Custom\", text_color=(0.5, 0, 0.5, 1), font_style='Caption') # defining Text field with all the parameters name = MDTextField(text=\"Enter name\", pos_hint={ 'center_x': 0.8, 'center_y': 0.8}, size_hint_x=None, width=100) # defining Button with all the parameters btn = MDRectangleFlatButton(text=\"Submit\", pos_hint={ 'center_x': 0.5, 'center_y': 0.3}, on_release=self.btnfunc) # adding widgets to screen screen.add_widget(name) screen.add_widget(btn) screen.add_widget(l) # 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": 27176, "s": 25697, "text": null }, { "code": null, "e": 27188, "s": 27180, "text": "Output:" }, { "code": null, "e": 27275, "s": 27192, "text": "When the button is pressed it displays the following output in the command prompt:" }, { "code": null, "e": 27292, "s": 27279, "text": "Explanation:" }, { "code": null, "e": 27490, "s": 27294, "text": "This class Demo is derived from the App() class of the kivymd.app. This class is the base class for creating the kivyMD Application. It is basically the main entry point into the kivyMD run loop." }, { "code": null, "e": 27673, "s": 27490, "text": "Here the build() method “Initializes the application; it will be called only once. If this method returns a widget (tree), it will be used as the root widget and added to the window." }, { "code": null, "e": 28070, "s": 27673, "text": "Here in the build method firstly we define a screen for the widgets to be shown on it. Then we add the widgets one by oneLabel for the title or heading of the page.A text field for user input. You can add more text fields.A button for submitting or performing any function. Here on clicking submit button, a message is getting printed in console. We have made the function btnfunc() for the same." }, { "code": null, "e": 28114, "s": 28070, "text": "Label for the title or heading of the page." }, { "code": null, "e": 28173, "s": 28114, "text": "A text field for user input. You can add more text fields." }, { "code": null, "e": 28348, "s": 28173, "text": "A button for submitting or performing any function. Here on clicking submit button, a message is getting printed in console. We have made the function btnfunc() for the same." }, { "code": null, "e": 28475, "s": 28348, "text": "The Demo.run() is the run() method that launches the app in standalone mode and calls the class Demo which returns the screen." }, { "code": null, "e": 28492, "s": 28477, "text": "adnanirshad158" }, { "code": null, "e": 28503, "s": 28492, "text": "Python-gui" }, { "code": null, "e": 28518, "s": 28503, "text": "python-modules" }, { "code": null, "e": 28525, "s": 28518, "text": "Python" }, { "code": null, "e": 28623, "s": 28525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28632, "s": 28623, "text": "Comments" }, { "code": null, "e": 28645, "s": 28632, "text": "Old Comments" }, { "code": null, "e": 28677, "s": 28645, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28733, "s": 28677, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28775, "s": 28733, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28817, "s": 28775, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28853, "s": 28817, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28875, "s": 28853, "text": "Defaultdict in Python" }, { "code": null, "e": 28914, "s": 28875, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28941, "s": 28914, "text": "Python Classes and Objects" }, { "code": null, "e": 28972, "s": 28941, "text": "Python | os.path.join() method" } ]
Lower bound in C++
In this tutorial, we will be discussing a program to understand the lower bound in C++. lower_bound() method in C++ is used to return the very first number in the container object which is not less than the given value. Live Demo #include <bits/stdc++.h> int main(){ std::vector<int> v{ 10, 20, 30, 40, 50 }; std::cout << "Vector contains :"; for (unsigned int i = 0; i < v.size(); i++) std::cout << " " << v[i]; std::cout << "\n"; std::vector <int>::iterator low1, low2; low1 = std::lower_bound(v.begin(), v.end(), 35); low2 = std::lower_bound(v.begin(), v.end(), 55); std::cout << "\nlower_bound for element 35 at position : " << (low1 - v.begin()); std::cout << "\nlower_bound for element 55 at position : " << (low2 - v.begin()); return 0; } Vector contains : 10 20 30 40 50 lower_bound for element 35 at position : 3 lower_bound for element 55 at position : 5
[ { "code": null, "e": 1150, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand the lower bound in C++." }, { "code": null, "e": 1282, "s": 1150, "text": "lower_bound() method in C++ is used to return the very first number in the container object which is not less than the given value." }, { "code": null, "e": 1293, "s": 1282, "text": " Live Demo" }, { "code": null, "e": 1869, "s": 1293, "text": "#include <bits/stdc++.h>\nint main(){\n std::vector<int> v{ 10, 20, 30, 40, 50 };\n std::cout << \"Vector contains :\";\n for (unsigned int i = 0; i < v.size(); i++)\n std::cout << \" \" << v[i];\n std::cout << \"\\n\";\n std::vector <int>::iterator low1, low2;\n low1 = std::lower_bound(v.begin(), v.end(), 35);\n low2 = std::lower_bound(v.begin(), v.end(), 55);\n std::cout\n << \"\\nlower_bound for element 35 at position : \"\n << (low1 - v.begin());\n std::cout\n << \"\\nlower_bound for element 55 at position : \"\n << (low2 - v.begin());\n return 0;\n}" }, { "code": null, "e": 1988, "s": 1869, "text": "Vector contains : 10 20 30 40 50\nlower_bound for element 35 at position : 3\nlower_bound for element 55 at position : 5" } ]
MySQL - PREPARE Statement
A prepared statement in MySQL represents a precompiled statement. A statement is compiled and stored in a prepared statement and you can later execute this multiple times. Instead of values we pass place holders to this statement. If you want to execute several identical queries (that differ by values only). You can use prepared statements. You can execute these statements in client libraries as well as in SQL scripts. A SQL prepared statement is based on three statements namely − PREPARE EXECUTE DEALLOCATE PREPARE The DEALLOCATE PREPARE is used to de-allocate a PREPARED statement. Following is the syntax of the EXECUTE statement − DEALLOCATE PREPARE stmt_name Where stmt_name is the name of the prepared statement to be de-allocated. Suppose we have created a table named Employee in the database using the CREATE statement and inserted three records in it as shown below − mysql> CREATE TABLE Employee(Name VARCHAR(255), Salary INT, Location VARCHAR(255)); You can prepare an INSERT statement with place holders instead of values as − mysql> PREPARE prepared_stmt FROM 'INSERT INTO EMPLOYE VALUES (?, ?, ?)'; Query OK, 0 rows affected (0.02 sec) Statement prepared Now execute the above created prepared statement − mysql> EXECUTE prepared_stmt USING @name, @sal, @loc; Query OK, 1 row affected (0.19 sec) Following query de-allocates the above created prepared statement. mysql> DEALLOCATE PREPARE prepared_stmt; Query OK, 0 rows affected (0.00 sec) After de-allocating the prepared statement if you try to execute it again an error will be generated − mysql> EXECUTE prepared_stmt USING @name, @sal, @loc; ERROR 1243 (HY000): Unknown prepared statement handler (prepared_stmt) given to EXECUTE We can also delete a prepared statement using this statement. Assume we have created another prepared statement as shown below − --Preparing the statement mysql> PREPARE prepared_stmt FROM 'SELECT * FROM EMPLOYE'; Query OK, 0 rows affected (0.00 sec) Statement prepared --Executing the statement mysql> EXECUTE prepared_stmt; +--------+--------+----------------+ | Name | Salary | Location | +--------+--------+----------------+ | Amit | 6554 | Hyderabad | | Sumith | 5981 | Vishakhapatnam | | Sudha | 7887 | Vijayawada | | Raghu | 9878 | Delhi | +--------+--------+----------------+ 4 rows in set (0.00 sec) Following statement drops the above created prepared statement − mysql> DROP PREPARE prepared_stmt; Query OK, 0 rows affected (0.00 sec) Assume we have created another table and populated it using the following queries − 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); Assume we have created another table and populated it using the following queries − 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); You can choose the table to execute a query dynamically using this statement as shown below − --Setting the table name dynamically mysql> SET @table = 'Student'; Query OK, 0 rows affected (0.00 sec) mysql> SET @statement = CONCAT('SELECT * FROM ', @table); Query OK, 0 rows affected (0.08 sec) --Preparing the statement mysql> PREPARE prepared_stmt FROM @statement; Query OK, 0 rows affected (0.16 sec) Statement prepared --Executing the statement mysql> EXECUTE prepared_stmt; +---------+------+-------+ | Name | age | Score | +---------+------+-------+ | Jeevan | 22 | 8 | | Raghav | 26 | –3 | | Khaleel | 21 | –9 | | Deva | 30 | 9 | +---------+------+-------+ 4 rows in set (0.10 sec) --De-allocating the statement mysql> DEALLOCATE PREPARE prepared_stmt; Query OK, 0 rows affected (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2564, "s": 2333, "text": "A prepared statement in MySQL represents a precompiled statement. A statement is compiled and stored in a prepared statement and you can later execute this multiple times. Instead of values we pass place holders to this statement." }, { "code": null, "e": 2756, "s": 2564, "text": "If you want to execute several identical queries (that differ by values only). You can use prepared statements. You can execute these statements in client libraries as well as in SQL scripts." }, { "code": null, "e": 2819, "s": 2756, "text": "A SQL prepared statement is based on three statements namely −" }, { "code": null, "e": 2827, "s": 2819, "text": "PREPARE" }, { "code": null, "e": 2835, "s": 2827, "text": "EXECUTE" }, { "code": null, "e": 2854, "s": 2835, "text": "DEALLOCATE PREPARE" }, { "code": null, "e": 2922, "s": 2854, "text": "The DEALLOCATE PREPARE is used to de-allocate a PREPARED statement." }, { "code": null, "e": 2973, "s": 2922, "text": "Following is the syntax of the EXECUTE statement −" }, { "code": null, "e": 3003, "s": 2973, "text": "DEALLOCATE PREPARE stmt_name\n" }, { "code": null, "e": 3077, "s": 3003, "text": "Where stmt_name is the name of the prepared statement to be de-allocated." }, { "code": null, "e": 3217, "s": 3077, "text": "Suppose we have created a table named Employee in the database using the CREATE statement and inserted three records in it as shown below −" }, { "code": null, "e": 3301, "s": 3217, "text": "mysql> CREATE TABLE Employee(Name VARCHAR(255), Salary INT, Location VARCHAR(255));" }, { "code": null, "e": 3379, "s": 3301, "text": "You can prepare an INSERT statement with place holders instead of values as −" }, { "code": null, "e": 3509, "s": 3379, "text": "mysql> PREPARE prepared_stmt FROM 'INSERT INTO EMPLOYE VALUES (?, ?, ?)';\nQuery OK, 0 rows affected (0.02 sec)\nStatement prepared" }, { "code": null, "e": 3560, "s": 3509, "text": "Now execute the above created prepared statement −" }, { "code": null, "e": 3650, "s": 3560, "text": "mysql> EXECUTE prepared_stmt USING @name, @sal, @loc;\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 3717, "s": 3650, "text": "Following query de-allocates the above created prepared statement." }, { "code": null, "e": 3795, "s": 3717, "text": "mysql> DEALLOCATE PREPARE prepared_stmt;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 3898, "s": 3795, "text": "After de-allocating the prepared statement if you try to execute it again an error will be generated −" }, { "code": null, "e": 4040, "s": 3898, "text": "mysql> EXECUTE prepared_stmt USING @name, @sal, @loc;\nERROR 1243 (HY000): Unknown prepared statement handler (prepared_stmt) given to EXECUTE" }, { "code": null, "e": 4169, "s": 4040, "text": "We can also delete a prepared statement using this statement. Assume we have created another prepared statement as shown below −" }, { "code": null, "e": 4688, "s": 4169, "text": "--Preparing the statement\nmysql> PREPARE prepared_stmt FROM 'SELECT * FROM EMPLOYE';\nQuery OK, 0 rows affected (0.00 sec)\nStatement prepared\n\n--Executing the statement\nmysql> EXECUTE prepared_stmt;\n+--------+--------+----------------+\n| Name | Salary | Location |\n+--------+--------+----------------+\n| Amit | 6554 | Hyderabad |\n| Sumith | 5981 | Vishakhapatnam |\n| Sudha | 7887 | Vijayawada |\n| Raghu | 9878 | Delhi |\n+--------+--------+----------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 4753, "s": 4688, "text": "Following statement drops the above created prepared statement −" }, { "code": null, "e": 4825, "s": 4753, "text": "mysql> DROP PREPARE prepared_stmt;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 4909, "s": 4825, "text": "Assume we have created another table and populated it using the following queries −" }, { "code": null, "e": 5226, "s": 4909, "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": 5310, "s": 5226, "text": "Assume we have created another table and populated it using the following queries −" }, { "code": null, "e": 5627, "s": 5310, "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": 5721, "s": 5627, "text": "You can choose the table to execute a query dynamically using this statement as shown below −" }, { "code": null, "e": 6457, "s": 5721, "text": "--Setting the table name dynamically\nmysql> SET @table = 'Student';\nQuery OK, 0 rows affected (0.00 sec)\nmysql> SET @statement = CONCAT('SELECT * FROM ', @table);\nQuery OK, 0 rows affected (0.08 sec)\n\n--Preparing the statement\nmysql> PREPARE prepared_stmt FROM @statement;\nQuery OK, 0 rows affected (0.16 sec)\nStatement prepared\n\n--Executing the statement\nmysql> EXECUTE prepared_stmt;\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.10 sec)\n\n--De-allocating the statement\nmysql> DEALLOCATE PREPARE prepared_stmt;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 6490, "s": 6457, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 6518, "s": 6490, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6553, "s": 6518, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6570, "s": 6553, "text": " Frahaan Hussain" }, { "code": null, "e": 6604, "s": 6570, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6639, "s": 6604, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 6673, "s": 6639, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 6701, "s": 6673, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6734, "s": 6701, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6754, "s": 6734, "text": " Harshit Srivastava" }, { "code": null, "e": 6787, "s": 6754, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 6805, "s": 6787, "text": " Trevoir Williams" }, { "code": null, "e": 6812, "s": 6805, "text": " Print" }, { "code": null, "e": 6823, "s": 6812, "text": " Add Notes" } ]
Text Summarization on the Books of Harry Potter | by Greg Rafferty | Towards Data Science
I’m Greg Rafferty, a data scientist in the Bay Area. You can check out the code for this project on my github. Feel free to contact me with any questions! In this series of posts, I’m looking at a few handy NLP techniques, through the lens of Harry Potter. Previous posts in this series on basic NLP looked at Topic Modeling with Latent Dirichlet Allocation and Regular Expressions, and my next post will look at sentiment analysis. Hermione interrupted them. “Aren’t you two ever going to read Hogwarts, A History?” How many times throughout the Harry Potter series does Hermione bug Harry and Ron to read the enormous tome Hogwarts, A History? Hint: it’s a lot. How many nights do the three of them spend in the library, reading through every book they can find to figure out who Nicolas Flamel is, or how to survive underwater, or preparing for their O.W.L.s? The mistake they’re all making is to try to read everything themselves. Remember when you were in school and stumbled upon the CliffsNotes summary of that book you never read but were supposed to write an essay about? That’s basically what text summarization does: provide the CliffsNotes version for any large document. Now, CliffsNotes have been written by rather well-educated people who are familiar with the book they’re summarizing. But this is the twenty-first century, aren’t computers supposed to be putting humans out of work? I looked into a few text summarization algorithms to see if we’re ready to put poor old Clifton out of a job. There are two types of text summarization algorithms: extractive and abstractive. All extractive summarization algorithms attempt to score the phrases or sentences in a document and return only the most highly informative blocks of text. Abstractive text summarization actually creates new text which doesn’t exist in that form in the document. Abstractive summarization is what you might do when explaining a book you read to your friend, and it is much more difficult for a computer to do than extractive summarization. Computers just aren’t that great at the act of creation. To date, there aren’t any abstractive summarization techniques which work suitably well on long documents. The best performing ones merely create a sentence based upon a single paragraph, or cut the length of a sentence in half while maintaining as much information as possible. Often, grammar suffers horribly. They’re usually based upon neural network models. This post will focus on the much more simple extractive text summarization techniques. Most of the algorithms I’ll present are packaged together in the sumy package for Python but I also use one summarizer from the Gensim package and one other technique I wrote myself using LDA topic keywords to enrich the sumy EdmundsonSummarizer. All examples output five-sentence summaries of the first chapter of Harry Potter and the Sorcerer’s Stone. See my Jupyter notebook for complete code. And a word of caution: don’t judge the results too harshly. They’re not great... (text summarization does seem to work better on drier works of non-fiction) LexRank is an unsupervised approach that gets its inspiration from the same ideas behind Google’s PageRank algorithm. The authors say it is “based on the concept of eigenvector centrality in a graph representation of sentences”, using “a connectivity matrix based on on intra-sentence cosine similarity.” Ok, so in a nutshell, it finds the relative importance of all words in a document and selects the sentences which contain the most of those high-scoring words. "The Potters, that's right, that's what I heard —" "— yes, their son, Harry —" Mr. Dursley stopped dead.Twelve times he clicked the Put-Outer, until the only lights left on the whole street were two tiny pinpricks in the distance, which were the eyes of the cat watching him.Dumbledore slipped the Put-Outer back inside his cloak and set off down the street toward number four, where he sat down on the wall next to the cat."But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —" "Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found," Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.Dumbledore turned and walked back down the street. One of the first text summarization algorithms was published in 1958 by Hans Peter Luhn, working at IBM research. Luhn’s algorithm is a naive approach based on TF-IDF and looking at the “window size” of non-important words between words of high importance. It also assigns higher weights to sentences occurring near the beginning of a document. It was now reading the sign that said Privet Drive — no, looking at the sign; cats couldn't read maps or signs.He didn't see the owls swooping past in broad daylight, though people down in the street did; they pointed and gazed open-mouthed as owl after owl sped overhead.No one knows why, or how, but they're saying that when he couldn't kill Harry Potter, Voldemort's power somehow broke — and that's why he's gone.""But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —" "Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found," Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.G'night, Professor McGonagall — Professor Dumbledore, sir." Latent Semantic Analysis is a relatively new algorithm which combines term frequency with singular value decomposition. He dashed back across the road, hurried up to his office, snapped at his secretary not to disturb him, seized his telephone, and had almost finished dialing his home number when he changed his mind.It seemed that Professor McGonagall had reached the point she was most anxious to discuss, the real reason she had been waiting on a cold, hard wall all day, for neither as a cat nor as a woman had she fixed Dumbledore with such a piercing stare as she did now.He looked simply too big to be allowed, and so wild — long tangles of bushy black hair and beard hid most of his face, he had hands the size of trash can lids, and his feet in their leather boots were like baby dolphins.For a full minute the three of them stood and looked at the little bundle; Hagrid's shoulders shook, Professor McGonagall blinked furiously, and the twinkling light that usually shone from Dumbledore's eyes seemed to have gone out.A breeze ruffled the neat hedges of Privet Drive, which lay silent and tidy under the inky sky, the very last place you would expect astonishing things to happen. TextRank is another text summarizer based on the ideas of PageRank, and was also developed at the same time as LexRank, though by different groups of people. TextRank is a bit more simplistic than LexRank; although both algorithms are very similar, LexRank applies a heuristic post-processing step to remove sentences with highly duplicitous. Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much.They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense.Mr. Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs. Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors. In 1969, Harold Edmundson developed the summarizer bearing his name. Edmundson’s algorithm was, along with Luhn’s, one of the seminal text summarization techniques. What sets the Edmundson summarizer apart from the others is that it takes into account “bonus words”, words stated by the user as of high importance; “stigma words”, words of low importance or even negative importance; and “stop words”, which are the same as used elsewhere in NLP processing. Edmundson suggested using the words in a document’s title as bonus words. Using the chapter title as bonus words, this is what Edmundson outputs: The Dursleys shuddered to think what the neighbors would say if the Potters arrived in the street.When Dudley had been put to bed, he went into the living room in time to catch the last report on the evening news: "And finally, bird-watchers everywhere have reported that the nation's owls have been behaving very unusually today.Twelve times he clicked the Put-Outer, until the only lights left on the whole street were two tiny pinpricks in the distance, which were the eyes of the cat watching him.Dumbledore slipped the Put-Outer back inside his cloak and set off down the street toward number four, where he sat down on the wall next to the cat.He couldn't know that at this very moment, people meeting in secret all over the country were holding up their glasses and saying in hushed voices: "To Harry Potter — the boy who lived!" Another addition I made was to use LDA to extract topic keywords, and then add those topic keywords back in as additional bonus words. With this modification, the Edmundson results are as follows: At half past eight, Mr. Dursley picked up his briefcase, pecked Mrs. Dursley on the cheek, and tried to kiss Dudley good-bye but missed, because Dudley was now having a tantrum and throwing his cereal at the walls.When Dudley had been put to bed, he went into the living room in time to catch the last report on the evening news: "And finally, bird-watchers everywhere have reported that the nation's owls have been behaving very unusually today.Twelve times he clicked the Put-Outer, until the only lights left on the whole street were two tiny pinpricks in the distance, which were the eyes of the cat watching him.One small hand closed on the letter beside him and he slept on, not knowing he was special, not knowing he was famous, not knowing he would be woken in a few hours' time by Mrs. Dursley's scream as she opened the front door to put out the milk bottles, nor that he would spend the next few weeks being prodded and pinched by his cousin Dudley.He couldn't know that at this very moment, people meeting in secret all over the country were holding up their glasses and saying in hushed voices: "To Harry Potter — the boy who lived!" The SumBasic algorithm was developed in 2005 and uses only the word probability approach to determine sentence importance. Sorry, but it’s pretty bad on this document. Mr. Dursley wondered."Harry.The cat was still there."It certainly seems so," said Dumbledore."Yes," said Professor McGonagall. Wow. That’s terrible. Ahem, moving on... The KLSum algorithm is a greedy method which adds sentences to the summary as long as the KL Divergence (a measure of entropy) is decreasing. It was on the corner of the street that he noticed the first sign of something peculiar — a cat reading a map.It grew steadily louder as they looked up and down the street for some sign of a headlight; it swelled to a roar as they both looked up at the sky — and a huge motorcycle fell out of the air and landed on the road in front of them.He looked simply too big to be allowed, and so wild — long tangles of bushy black hair and beard hid most of his face, he had hands the size of trash can lids, and his feet in their leather boots were like baby dolphins."But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —" "Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found," Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.He clicked it once, and twelve balls of light sped back to their street lamps so that Privet Drive glowed suddenly orange and he could make out a tabby cat slinking around the corner at the other end of the street. The Reduction algorithm is another graph-based model which values sentences according to the sum of the weights of their edges to other sentences in the document. This weight is computed in the same way as it is in the TexRank model. Mrs. Potter was Mrs. Dursley's sister, but they hadn't met for several years; in fact, Mrs. Dursley pretended she didn't have a sister, because her sister and her good-for-nothing husband were as unDursleyish as it was possible to be.It seemed that Professor McGonagall had reached the point she was most anxious to discuss, the real reason she had been waiting on a cold, hard wall all day, for neither as a cat nor as a woman had she fixed Dumbledore with such a piercing stare as she did now.Dumbledore took Harry in his arms and turned toward the Dursleys' house."But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —" "Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found," Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.G'night, Professor McGonagall — Professor Dumbledore, sir." The Gensim package for Python includes a summarizer which is a modification of the TextRank algorithm. Gensim’s approach modifies the sentence similarity function. It was now reading the sign that said Privet Drive — no, looking at the sign; cats couldn't read maps or signs.Dumbledore slipped the Put-Outer back inside his cloak and set off down the street toward number four, where he sat down on the wall next to the cat.They're a kind of Muggle sweet I'm rather fond of." "No, thank you," said Professor McGonagall coldly, as though she didn't think this was the moment for lemon drops.All this 'You-Know-Who' nonsense — for eleven years I have been trying to persuade people to call him by his proper name: Voldemort." Professor McGonagall flinched, but Dumbledore, who was unsticking two lemon drops, seemed not to notice.Professor McGonagall shot a sharp look at Dumbledore and said, "The owls are nothing next to the rumors that are flying around.It seemed that Professor McGonagall had reached the point she was most anxious to discuss, the real reason she had been waiting on a cold, hard wall all day, for neither as a cat nor as a woman had she fixed Dumbledore with such a piercing stare as she did now. So which algorithm do you think provides the best summary? There are a lot of parameters to tweak before making a final judgement. Some might perform better on shorter summaries, some on longer summaries. The style of writing could make a difference (I mentioned before that I’ve had better luck summarizing non-fiction than fiction). But if you’re Harry just entering Hogwarts’ library with the intent to answer some question and are intimidated by “the sheer size of the library; tens of thousands of books; thousands of shelves; hundreds of narrow rows”, then it couldn’t hurt to have a couple summaries available with a few mouse clicks. If only wizards used such silly muggle creations...
[ { "code": null, "e": 327, "s": 172, "text": "I’m Greg Rafferty, a data scientist in the Bay Area. You can check out the code for this project on my github. Feel free to contact me with any questions!" }, { "code": null, "e": 605, "s": 327, "text": "In this series of posts, I’m looking at a few handy NLP techniques, through the lens of Harry Potter. Previous posts in this series on basic NLP looked at Topic Modeling with Latent Dirichlet Allocation and Regular Expressions, and my next post will look at sentiment analysis." }, { "code": null, "e": 689, "s": 605, "text": "Hermione interrupted them. “Aren’t you two ever going to read Hogwarts, A History?”" }, { "code": null, "e": 1107, "s": 689, "text": "How many times throughout the Harry Potter series does Hermione bug Harry and Ron to read the enormous tome Hogwarts, A History? Hint: it’s a lot. How many nights do the three of them spend in the library, reading through every book they can find to figure out who Nicolas Flamel is, or how to survive underwater, or preparing for their O.W.L.s? The mistake they’re all making is to try to read everything themselves." }, { "code": null, "e": 1682, "s": 1107, "text": "Remember when you were in school and stumbled upon the CliffsNotes summary of that book you never read but were supposed to write an essay about? That’s basically what text summarization does: provide the CliffsNotes version for any large document. Now, CliffsNotes have been written by rather well-educated people who are familiar with the book they’re summarizing. But this is the twenty-first century, aren’t computers supposed to be putting humans out of work? I looked into a few text summarization algorithms to see if we’re ready to put poor old Clifton out of a job." }, { "code": null, "e": 2710, "s": 1682, "text": "There are two types of text summarization algorithms: extractive and abstractive. All extractive summarization algorithms attempt to score the phrases or sentences in a document and return only the most highly informative blocks of text. Abstractive text summarization actually creates new text which doesn’t exist in that form in the document. Abstractive summarization is what you might do when explaining a book you read to your friend, and it is much more difficult for a computer to do than extractive summarization. Computers just aren’t that great at the act of creation. To date, there aren’t any abstractive summarization techniques which work suitably well on long documents. The best performing ones merely create a sentence based upon a single paragraph, or cut the length of a sentence in half while maintaining as much information as possible. Often, grammar suffers horribly. They’re usually based upon neural network models. This post will focus on the much more simple extractive text summarization techniques." }, { "code": null, "e": 3264, "s": 2710, "text": "Most of the algorithms I’ll present are packaged together in the sumy package for Python but I also use one summarizer from the Gensim package and one other technique I wrote myself using LDA topic keywords to enrich the sumy EdmundsonSummarizer. All examples output five-sentence summaries of the first chapter of Harry Potter and the Sorcerer’s Stone. See my Jupyter notebook for complete code. And a word of caution: don’t judge the results too harshly. They’re not great... (text summarization does seem to work better on drier works of non-fiction)" }, { "code": null, "e": 3729, "s": 3264, "text": "LexRank is an unsupervised approach that gets its inspiration from the same ideas behind Google’s PageRank algorithm. The authors say it is “based on the concept of eigenvector centrality in a graph representation of sentences”, using “a connectivity matrix based on on intra-sentence cosine similarity.” Ok, so in a nutshell, it finds the relative importance of all words in a document and selects the sentences which contain the most of those high-scoring words." }, { "code": null, "e": 4534, "s": 3729, "text": "\"The Potters, that's right, that's what I heard —\" \"— yes, their son, Harry —\" Mr. Dursley stopped dead.Twelve times he clicked the Put-Outer, until the only lights left on the whole street were two tiny pinpricks in the distance, which were the eyes of the cat watching him.Dumbledore slipped the Put-Outer back inside his cloak and set off down the street toward number four, where he sat down on the wall next to the cat.\"But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —\" \"Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found,\" Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.Dumbledore turned and walked back down the street." }, { "code": null, "e": 4879, "s": 4534, "text": "One of the first text summarization algorithms was published in 1958 by Hans Peter Luhn, working at IBM research. Luhn’s algorithm is a naive approach based on TF-IDF and looking at the “window size” of non-important words between words of high importance. It also assigns higher weights to sentences occurring near the beginning of a document." }, { "code": null, "e": 5687, "s": 4879, "text": "It was now reading the sign that said Privet Drive — no, looking at the sign; cats couldn't read maps or signs.He didn't see the owls swooping past in broad daylight, though people down in the street did; they pointed and gazed open-mouthed as owl after owl sped overhead.No one knows why, or how, but they're saying that when he couldn't kill Harry Potter, Voldemort's power somehow broke — and that's why he's gone.\"\"But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —\" \"Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found,\" Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.G'night, Professor McGonagall — Professor Dumbledore, sir.\"" }, { "code": null, "e": 5807, "s": 5687, "text": "Latent Semantic Analysis is a relatively new algorithm which combines term frequency with singular value decomposition." }, { "code": null, "e": 6880, "s": 5807, "text": "He dashed back across the road, hurried up to his office, snapped at his secretary not to disturb him, seized his telephone, and had almost finished dialing his home number when he changed his mind.It seemed that Professor McGonagall had reached the point she was most anxious to discuss, the real reason she had been waiting on a cold, hard wall all day, for neither as a cat nor as a woman had she fixed Dumbledore with such a piercing stare as she did now.He looked simply too big to be allowed, and so wild — long tangles of bushy black hair and beard hid most of his face, he had hands the size of trash can lids, and his feet in their leather boots were like baby dolphins.For a full minute the three of them stood and looked at the little bundle; Hagrid's shoulders shook, Professor McGonagall blinked furiously, and the twinkling light that usually shone from Dumbledore's eyes seemed to have gone out.A breeze ruffled the neat hedges of Privet Drive, which lay silent and tidy under the inky sky, the very last place you would expect astonishing things to happen." }, { "code": null, "e": 7223, "s": 6880, "text": "TextRank is another text summarizer based on the ideas of PageRank, and was also developed at the same time as LexRank, though by different groups of people. TextRank is a bit more simplistic than LexRank; although both algorithms are very similar, LexRank applies a heuristic post-processing step to remove sentences with highly duplicitous." }, { "code": null, "e": 7840, "s": 7223, "text": "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much.They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense.Mr. Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs. Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors." }, { "code": null, "e": 8444, "s": 7840, "text": "In 1969, Harold Edmundson developed the summarizer bearing his name. Edmundson’s algorithm was, along with Luhn’s, one of the seminal text summarization techniques. What sets the Edmundson summarizer apart from the others is that it takes into account “bonus words”, words stated by the user as of high importance; “stigma words”, words of low importance or even negative importance; and “stop words”, which are the same as used elsewhere in NLP processing. Edmundson suggested using the words in a document’s title as bonus words. Using the chapter title as bonus words, this is what Edmundson outputs:" }, { "code": null, "e": 9281, "s": 8444, "text": "The Dursleys shuddered to think what the neighbors would say if the Potters arrived in the street.When Dudley had been put to bed, he went into the living room in time to catch the last report on the evening news: \"And finally, bird-watchers everywhere have reported that the nation's owls have been behaving very unusually today.Twelve times he clicked the Put-Outer, until the only lights left on the whole street were two tiny pinpricks in the distance, which were the eyes of the cat watching him.Dumbledore slipped the Put-Outer back inside his cloak and set off down the street toward number four, where he sat down on the wall next to the cat.He couldn't know that at this very moment, people meeting in secret all over the country were holding up their glasses and saying in hushed voices: \"To Harry Potter — the boy who lived!\"" }, { "code": null, "e": 9478, "s": 9281, "text": "Another addition I made was to use LDA to extract topic keywords, and then add those topic keywords back in as additional bonus words. With this modification, the Edmundson results are as follows:" }, { "code": null, "e": 10625, "s": 9478, "text": "At half past eight, Mr. Dursley picked up his briefcase, pecked Mrs. Dursley on the cheek, and tried to kiss Dudley good-bye but missed, because Dudley was now having a tantrum and throwing his cereal at the walls.When Dudley had been put to bed, he went into the living room in time to catch the last report on the evening news: \"And finally, bird-watchers everywhere have reported that the nation's owls have been behaving very unusually today.Twelve times he clicked the Put-Outer, until the only lights left on the whole street were two tiny pinpricks in the distance, which were the eyes of the cat watching him.One small hand closed on the letter beside him and he slept on, not knowing he was special, not knowing he was famous, not knowing he would be woken in a few hours' time by Mrs. Dursley's scream as she opened the front door to put out the milk bottles, nor that he would spend the next few weeks being prodded and pinched by his cousin Dudley.He couldn't know that at this very moment, people meeting in secret all over the country were holding up their glasses and saying in hushed voices: \"To Harry Potter — the boy who lived!\"" }, { "code": null, "e": 10793, "s": 10625, "text": "The SumBasic algorithm was developed in 2005 and uses only the word probability approach to determine sentence importance. Sorry, but it’s pretty bad on this document." }, { "code": null, "e": 10920, "s": 10793, "text": "Mr. Dursley wondered.\"Harry.The cat was still there.\"It certainly seems so,\" said Dumbledore.\"Yes,\" said Professor McGonagall." }, { "code": null, "e": 10961, "s": 10920, "text": "Wow. That’s terrible. Ahem, moving on..." }, { "code": null, "e": 11103, "s": 10961, "text": "The KLSum algorithm is a greedy method which adds sentences to the summary as long as the KL Divergence (a measure of entropy) is decreasing." }, { "code": null, "e": 12209, "s": 11103, "text": "It was on the corner of the street that he noticed the first sign of something peculiar — a cat reading a map.It grew steadily louder as they looked up and down the street for some sign of a headlight; it swelled to a roar as they both looked up at the sky — and a huge motorcycle fell out of the air and landed on the road in front of them.He looked simply too big to be allowed, and so wild — long tangles of bushy black hair and beard hid most of his face, he had hands the size of trash can lids, and his feet in their leather boots were like baby dolphins.\"But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —\" \"Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found,\" Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.He clicked it once, and twelve balls of light sped back to their street lamps so that Privet Drive glowed suddenly orange and he could make out a tabby cat slinking around the corner at the other end of the street." }, { "code": null, "e": 12443, "s": 12209, "text": "The Reduction algorithm is another graph-based model which values sentences according to the sum of the weights of their edges to other sentences in the document. This weight is computed in the same way as it is in the TexRank model." }, { "code": null, "e": 13400, "s": 12443, "text": "Mrs. Potter was Mrs. Dursley's sister, but they hadn't met for several years; in fact, Mrs. Dursley pretended she didn't have a sister, because her sister and her good-for-nothing husband were as unDursleyish as it was possible to be.It seemed that Professor McGonagall had reached the point she was most anxious to discuss, the real reason she had been waiting on a cold, hard wall all day, for neither as a cat nor as a woman had she fixed Dumbledore with such a piercing stare as she did now.Dumbledore took Harry in his arms and turned toward the Dursleys' house.\"But I c-c-can't stand it — Lily an' James dead — an' poor little Harry off ter live with Muggles —\" \"Yes, yes, it's all very sad, but get a grip on yourself, Hagrid, or we'll be found,\" Professor McGonagall whispered, patting Hagrid gingerly on the arm as Dumbledore stepped over the low garden wall and walked to the front door.G'night, Professor McGonagall — Professor Dumbledore, sir.\"" }, { "code": null, "e": 13564, "s": 13400, "text": "The Gensim package for Python includes a summarizer which is a modification of the TextRank algorithm. Gensim’s approach modifies the sentence similarity function." }, { "code": null, "e": 14617, "s": 13564, "text": "It was now reading the sign that said Privet Drive — no, looking at the sign; cats couldn't read maps or signs.Dumbledore slipped the Put-Outer back inside his cloak and set off down the street toward number four, where he sat down on the wall next to the cat.They're a kind of Muggle sweet I'm rather fond of.\" \"No, thank you,\" said Professor McGonagall coldly, as though she didn't think this was the moment for lemon drops.All this 'You-Know-Who' nonsense — for eleven years I have been trying to persuade people to call him by his proper name: Voldemort.\" Professor McGonagall flinched, but Dumbledore, who was unsticking two lemon drops, seemed not to notice.Professor McGonagall shot a sharp look at Dumbledore and said, \"The owls are nothing next to the rumors that are flying around.It seemed that Professor McGonagall had reached the point she was most anxious to discuss, the real reason she had been waiting on a cold, hard wall all day, for neither as a cat nor as a woman had she fixed Dumbledore with such a piercing stare as she did now." } ]
Intro to Dynamic Visualization with Python — Animations and Interactive Plots | by Naveen Venkatesan | Towards Data Science
Sometimes, you would like to create a dynamic graphic that either changes with time like a video, or adapts based on an interactive user input. These visualizations do a great of job of really showing how an output can change with its inputs. In this article, I will present the same data as a static plot, an animation, and an interactive plot. In keeping with the physical science theme of my previous articles, the data I am plotting will be from one of the most widely used equations in solid-state physics: the Fermi-Dirac distribution, which describes the occupancy of electrons in solids. The equation is shown below, which relates the fraction of states occupied at energy E as a function of the Fermi energy and temperature. Our first plot will be a static plot in which will have curves of f(E) at different temperatures. First, we import required packages: # Import packagesimport matplotlib as mplimport matplotlib.pyplot as pltimport numpy as np Since we are going to calculate the Fermi-Dirac distribution many times, we should write a function to do this calculation for us: # Fermi-Dirac Distributiondef fermi(E: float, E_f: float, T: float) -> float: k_b = 8.617 * (10**-5) # eV/K return 1/(np.exp((E - E_f)/(k_b * T)) + 1) Now we can start plotting the data! First I am going to edit some of the general plot parameters: # General plot parametersmpl.rcParams['font.family'] = 'Avenir'mpl.rcParams['font.size'] = 18mpl.rcParams['axes.linewidth'] = 2mpl.rcParams['axes.spines.top'] = Falsempl.rcParams['axes.spines.right'] = Falsempl.rcParams['xtick.major.size'] = 10mpl.rcParams['xtick.major.width'] = 2mpl.rcParams['ytick.major.size'] = 10mpl.rcParams['ytick.major.width'] = 2 We create our figure and add our axes object to it: # Create figure and add axesfig = plt.figure(figsize=(6, 4))ax = fig.add_subplot(111) To supply the varying temperature data to our Fermi-Dirac function, we generate an array of values between 100 K and 1000 K using numpy.linspace: # Temperature valuesT = np.linspace(100, 1000, 10) For each of these temperature values, we need to map a different color to its resulting curve. We will generate colors from the coolwarm colormap since we are in fact dealing with ichanging temperatures. Since we have generated 10 temperature values above, we will extract 10 colors from the coolwarm colormap. # Get colors from coolwarm colormapcolors = plt.get_cmap('coolwarm', 10) The simplest way to plot our data is to loop through all the temperature values and plot the corresponding curve each time. To generate x-axis values, we again use numpy.linspace to create an array of 100 evenly-spaced values between 0 and 1. Additionally, we are using a fixed Fermi energy value of 0.5 eV for all calculations. # Plot F-D datafor i in range(len(T)): x = np.linspace(0, 1, 100) y = fermi(x, 0.5, T[i]) ax.plot(x, y, color=colors(i), linewidth=2.5) The final element our plot needs is a method by which to distinguish the different colored temperature curves. To do this, we will create a legend by first creating a list of labels, and then passing them to the axes.legend method. # Add legendlabels = ['100 K', '200 K', '300 K', '400 K', '500 K', '600 K', '700 K', '800 K', '900 K', '1000 K']ax.legend(labels, bbox_to_anchor=(1.05, -0.1), loc='lower left', frameon=False, labelspacing=0.2) labelspacing — the vertical spacing between legend entries (default is 0.5) Finally, after adding axis labels, we are presented with the following plot: Now say we wanted to present the same data as above, but as a video — how would we do this? It turns out that we can do this very easily with matplotlib! We must import the following to make this functionality available to us: # Import animation packagefrom matplotlib.animation import FuncAnimation If we are using a Jupyter Notebook, we should also change the backend that matplotlib uses to render its figures in order to allow for interactive plots. # Change matplotlib backend%matplotlib notebook For our animation we need to do the following: (1) Store a reference to the plotted curve as a variable (2) Use a function call with this variable to keep updating the plot data We will first plot empty arrays and store this plot as a variable called f_d. Additionally, we will add a text annotation that displays the temperature of the current plot, so we will store a variable reference to this as well. We are aligning the top right corner of the text annotation to the top right corner of our axes object. # Create variable reference to plotf_d, = ax.plot([], [], linewidth=2.5)# Add text annotation and create variable referencetemp = ax.text(1, 1, '', ha='right', va='top', fontsize=24) Now to the workhorse of our animation — the animation function. This function will take the input of an index i and update the plot each time it is called. It will also update the text annotation with the current temperature and (just for fun!) change the color of the plot and text based on the same colors from the coolwarm colormap. # Animation functiondef animate(i): x = np.linspace(0, 1, 100) y = fermi(x, 0.5, T[i]) f_d.set_data(x, y) f_d.set_color(colors(i)) temp.set_text(str(int(T[i])) + ' K') temp.set_color(colors(i)) set_data(x, y) — set the new x and y data for the plot Now to the make the magic happen, we use the following line of code: # Create animationani = FuncAnimation(fig=fig, func=animate, frames=range(len(T)), interval=500, repeat=True) fig — the figure passed to the animation function func — the animation function for the plot frames — an array, starting at 0, representing the frames of the animation. In this case, we pass one with a length equal to the number of temperatures we are animating over (this is also the index i that gets passed to func). interval — delay between frames in milliseconds repeat — whether to repeat the animation at its conclusion There it is! Now, if your axis labels or part of your plot is cut off, you can try adding the following line of code to ensure that all elements are within view of the figure. # Ensure the entire plot is visiblefig.tight_layout() Now to save our animation, we use the following: # Save and show animationani.save('AnimatedPlot.gif', writer='imagemagick', fps=2) writer — the animation writer program — to generate .gif files, I use ImageMagick fps — frames per second of the animation (since we only have 10 frames, I am using an fps value of 2 to imitate the interval delay of 500 ms earlier) Finally, if we want to let the user play around with input parameters to observe their change on the output, we can make an interactive plot. We start by importing required packages. # Import slider packagefrom matplotlib.widgets import Slider We again start with creating a figure and axis object to hold our plot. However, this time, we adjust the size of the plot to make room for the sliders that we will add. # Create main axisax = fig.add_subplot(111)fig.subplots_adjust(bottom=0.2, top=0.75) figure.subplots_adjust() takes inputs for top, bottom, left, and right to indicate where to draw the four corners of the axis bounding box. In this case, we are making sure the top does not exceed 0.75 so we can place sliders on top of the plot. Sliders start out just like any other axes object. Here, we are adding both above the plot (one to vary the Fermi energy, and one to vary the temperature). Also, since we changed the global plot settings to remove the right and top spines, we will add them back here for the sliders. # Create axes for slidersax_Ef = fig.add_axes([0.3, 0.85, 0.4, 0.05])ax_Ef.spines['top'].set_visible(True)ax_Ef.spines['right'].set_visible(True)ax_T = fig.add_axes([0.3, 0.92, 0.4, 0.05])ax_T.spines['top'].set_visible(True)ax_T.spines['right'].set_visible(True) Now, we have to turn those axes objects into sliders: # Create sliderss_Ef = Slider(ax=ax_Ef, label='Fermi Energy ', valmin=0, valmax=1.0, valfmt=' %1.1f eV', facecolor='#cc7000')s_T = Slider(ax=ax_T, 'Temperature ', valmin=100, valmax=1000, valinit=100, valfmt='%i K', facecolor='#cc7000') ax — axes object to convert to slider label — the slider label that goes to the left of the slider valmin — minimum value of the slider valmax — maximum value of the slider valfmt — the string to display as the value of the slider, positioned to the right. %1.1f is a float with 1 decimal point and %i is an integer facecolor — the color to fill in the slider Now that we have created our sliders, let us plot the “default” dataset that will show when the figure is first loaded (Fermi energy of 0.5 eV and temperature of 300 K): # Plot default datax = np.linspace(-0, 1, 100)Ef_0 = 0.5T_0 = 100y = fermi(x, Ef_0, T_0)f_d, = ax.plot(x, y, linewidth=2.5) Just like in the animated plot case, we now will define the update function that will change the data as the sliders are updated. This update function takes the current values of the sliders, changes the data in the plot, and re-draws the figure. # Update valuesdef update(val): Ef = s_Ef.val T = s_T.val f_d.set_data(x, fermi(x, Ef, T)) fig.canvas.draw_idle()s_Ef.on_changed(update)s_T.on_changed(update) Slider.on_changed(func) calls the updating func when the slider value is changed. At last, when we show our plot we get this cool interactive figure! I hope this article showed how you can potentially make your data visualizations dynamic with animations and interactive sliders. Thank you for reading — I appreciate any comments and feedback. All the examples shown in this article can be found at this Github repository. You can follow me on Twitter or connect with me on LinkedIn for more articles and updates.
[ { "code": null, "e": 906, "s": 172, "text": "Sometimes, you would like to create a dynamic graphic that either changes with time like a video, or adapts based on an interactive user input. These visualizations do a great of job of really showing how an output can change with its inputs. In this article, I will present the same data as a static plot, an animation, and an interactive plot. In keeping with the physical science theme of my previous articles, the data I am plotting will be from one of the most widely used equations in solid-state physics: the Fermi-Dirac distribution, which describes the occupancy of electrons in solids. The equation is shown below, which relates the fraction of states occupied at energy E as a function of the Fermi energy and temperature." }, { "code": null, "e": 1040, "s": 906, "text": "Our first plot will be a static plot in which will have curves of f(E) at different temperatures. First, we import required packages:" }, { "code": null, "e": 1131, "s": 1040, "text": "# Import packagesimport matplotlib as mplimport matplotlib.pyplot as pltimport numpy as np" }, { "code": null, "e": 1262, "s": 1131, "text": "Since we are going to calculate the Fermi-Dirac distribution many times, we should write a function to do this calculation for us:" }, { "code": null, "e": 1419, "s": 1262, "text": "# Fermi-Dirac Distributiondef fermi(E: float, E_f: float, T: float) -> float: k_b = 8.617 * (10**-5) # eV/K return 1/(np.exp((E - E_f)/(k_b * T)) + 1)" }, { "code": null, "e": 1517, "s": 1419, "text": "Now we can start plotting the data! First I am going to edit some of the general plot parameters:" }, { "code": null, "e": 1873, "s": 1517, "text": "# General plot parametersmpl.rcParams['font.family'] = 'Avenir'mpl.rcParams['font.size'] = 18mpl.rcParams['axes.linewidth'] = 2mpl.rcParams['axes.spines.top'] = Falsempl.rcParams['axes.spines.right'] = Falsempl.rcParams['xtick.major.size'] = 10mpl.rcParams['xtick.major.width'] = 2mpl.rcParams['ytick.major.size'] = 10mpl.rcParams['ytick.major.width'] = 2" }, { "code": null, "e": 1925, "s": 1873, "text": "We create our figure and add our axes object to it:" }, { "code": null, "e": 2011, "s": 1925, "text": "# Create figure and add axesfig = plt.figure(figsize=(6, 4))ax = fig.add_subplot(111)" }, { "code": null, "e": 2157, "s": 2011, "text": "To supply the varying temperature data to our Fermi-Dirac function, we generate an array of values between 100 K and 1000 K using numpy.linspace:" }, { "code": null, "e": 2208, "s": 2157, "text": "# Temperature valuesT = np.linspace(100, 1000, 10)" }, { "code": null, "e": 2519, "s": 2208, "text": "For each of these temperature values, we need to map a different color to its resulting curve. We will generate colors from the coolwarm colormap since we are in fact dealing with ichanging temperatures. Since we have generated 10 temperature values above, we will extract 10 colors from the coolwarm colormap." }, { "code": null, "e": 2592, "s": 2519, "text": "# Get colors from coolwarm colormapcolors = plt.get_cmap('coolwarm', 10)" }, { "code": null, "e": 2921, "s": 2592, "text": "The simplest way to plot our data is to loop through all the temperature values and plot the corresponding curve each time. To generate x-axis values, we again use numpy.linspace to create an array of 100 evenly-spaced values between 0 and 1. Additionally, we are using a fixed Fermi energy value of 0.5 eV for all calculations." }, { "code": null, "e": 3066, "s": 2921, "text": "# Plot F-D datafor i in range(len(T)): x = np.linspace(0, 1, 100) y = fermi(x, 0.5, T[i]) ax.plot(x, y, color=colors(i), linewidth=2.5)" }, { "code": null, "e": 3298, "s": 3066, "text": "The final element our plot needs is a method by which to distinguish the different colored temperature curves. To do this, we will create a legend by first creating a list of labels, and then passing them to the axes.legend method." }, { "code": null, "e": 3528, "s": 3298, "text": "# Add legendlabels = ['100 K', '200 K', '300 K', '400 K', '500 K', '600 K', '700 K', '800 K', '900 K', '1000 K']ax.legend(labels, bbox_to_anchor=(1.05, -0.1), loc='lower left', frameon=False, labelspacing=0.2)" }, { "code": null, "e": 3604, "s": 3528, "text": "labelspacing — the vertical spacing between legend entries (default is 0.5)" }, { "code": null, "e": 3681, "s": 3604, "text": "Finally, after adding axis labels, we are presented with the following plot:" }, { "code": null, "e": 3908, "s": 3681, "text": "Now say we wanted to present the same data as above, but as a video — how would we do this? It turns out that we can do this very easily with matplotlib! We must import the following to make this functionality available to us:" }, { "code": null, "e": 3981, "s": 3908, "text": "# Import animation packagefrom matplotlib.animation import FuncAnimation" }, { "code": null, "e": 4135, "s": 3981, "text": "If we are using a Jupyter Notebook, we should also change the backend that matplotlib uses to render its figures in order to allow for interactive plots." }, { "code": null, "e": 4183, "s": 4135, "text": "# Change matplotlib backend%matplotlib notebook" }, { "code": null, "e": 4230, "s": 4183, "text": "For our animation we need to do the following:" }, { "code": null, "e": 4287, "s": 4230, "text": "(1) Store a reference to the plotted curve as a variable" }, { "code": null, "e": 4361, "s": 4287, "text": "(2) Use a function call with this variable to keep updating the plot data" }, { "code": null, "e": 4693, "s": 4361, "text": "We will first plot empty arrays and store this plot as a variable called f_d. Additionally, we will add a text annotation that displays the temperature of the current plot, so we will store a variable reference to this as well. We are aligning the top right corner of the text annotation to the top right corner of our axes object." }, { "code": null, "e": 4876, "s": 4693, "text": "# Create variable reference to plotf_d, = ax.plot([], [], linewidth=2.5)# Add text annotation and create variable referencetemp = ax.text(1, 1, '', ha='right', va='top', fontsize=24)" }, { "code": null, "e": 5212, "s": 4876, "text": "Now to the workhorse of our animation — the animation function. This function will take the input of an index i and update the plot each time it is called. It will also update the text annotation with the current temperature and (just for fun!) change the color of the plot and text based on the same colors from the coolwarm colormap." }, { "code": null, "e": 5424, "s": 5212, "text": "# Animation functiondef animate(i): x = np.linspace(0, 1, 100) y = fermi(x, 0.5, T[i]) f_d.set_data(x, y) f_d.set_color(colors(i)) temp.set_text(str(int(T[i])) + ' K') temp.set_color(colors(i))" }, { "code": null, "e": 5479, "s": 5424, "text": "set_data(x, y) — set the new x and y data for the plot" }, { "code": null, "e": 5548, "s": 5479, "text": "Now to the make the magic happen, we use the following line of code:" }, { "code": null, "e": 5658, "s": 5548, "text": "# Create animationani = FuncAnimation(fig=fig, func=animate, frames=range(len(T)), interval=500, repeat=True)" }, { "code": null, "e": 5708, "s": 5658, "text": "fig — the figure passed to the animation function" }, { "code": null, "e": 5751, "s": 5708, "text": "func — the animation function for the plot" }, { "code": null, "e": 5978, "s": 5751, "text": "frames — an array, starting at 0, representing the frames of the animation. In this case, we pass one with a length equal to the number of temperatures we are animating over (this is also the index i that gets passed to func)." }, { "code": null, "e": 6026, "s": 5978, "text": "interval — delay between frames in milliseconds" }, { "code": null, "e": 6085, "s": 6026, "text": "repeat — whether to repeat the animation at its conclusion" }, { "code": null, "e": 6261, "s": 6085, "text": "There it is! Now, if your axis labels or part of your plot is cut off, you can try adding the following line of code to ensure that all elements are within view of the figure." }, { "code": null, "e": 6315, "s": 6261, "text": "# Ensure the entire plot is visiblefig.tight_layout()" }, { "code": null, "e": 6364, "s": 6315, "text": "Now to save our animation, we use the following:" }, { "code": null, "e": 6447, "s": 6364, "text": "# Save and show animationani.save('AnimatedPlot.gif', writer='imagemagick', fps=2)" }, { "code": null, "e": 6529, "s": 6447, "text": "writer — the animation writer program — to generate .gif files, I use ImageMagick" }, { "code": null, "e": 6679, "s": 6529, "text": "fps — frames per second of the animation (since we only have 10 frames, I am using an fps value of 2 to imitate the interval delay of 500 ms earlier)" }, { "code": null, "e": 6862, "s": 6679, "text": "Finally, if we want to let the user play around with input parameters to observe their change on the output, we can make an interactive plot. We start by importing required packages." }, { "code": null, "e": 6923, "s": 6862, "text": "# Import slider packagefrom matplotlib.widgets import Slider" }, { "code": null, "e": 7093, "s": 6923, "text": "We again start with creating a figure and axis object to hold our plot. However, this time, we adjust the size of the plot to make room for the sliders that we will add." }, { "code": null, "e": 7178, "s": 7093, "text": "# Create main axisax = fig.add_subplot(111)fig.subplots_adjust(bottom=0.2, top=0.75)" }, { "code": null, "e": 7424, "s": 7178, "text": "figure.subplots_adjust() takes inputs for top, bottom, left, and right to indicate where to draw the four corners of the axis bounding box. In this case, we are making sure the top does not exceed 0.75 so we can place sliders on top of the plot." }, { "code": null, "e": 7708, "s": 7424, "text": "Sliders start out just like any other axes object. Here, we are adding both above the plot (one to vary the Fermi energy, and one to vary the temperature). Also, since we changed the global plot settings to remove the right and top spines, we will add them back here for the sliders." }, { "code": null, "e": 7971, "s": 7708, "text": "# Create axes for slidersax_Ef = fig.add_axes([0.3, 0.85, 0.4, 0.05])ax_Ef.spines['top'].set_visible(True)ax_Ef.spines['right'].set_visible(True)ax_T = fig.add_axes([0.3, 0.92, 0.4, 0.05])ax_T.spines['top'].set_visible(True)ax_T.spines['right'].set_visible(True)" }, { "code": null, "e": 8025, "s": 7971, "text": "Now, we have to turn those axes objects into sliders:" }, { "code": null, "e": 8288, "s": 8025, "text": "# Create sliderss_Ef = Slider(ax=ax_Ef, label='Fermi Energy ', valmin=0, valmax=1.0, valfmt=' %1.1f eV', facecolor='#cc7000')s_T = Slider(ax=ax_T, 'Temperature ', valmin=100, valmax=1000, valinit=100, valfmt='%i K', facecolor='#cc7000')" }, { "code": null, "e": 8326, "s": 8288, "text": "ax — axes object to convert to slider" }, { "code": null, "e": 8387, "s": 8326, "text": "label — the slider label that goes to the left of the slider" }, { "code": null, "e": 8424, "s": 8387, "text": "valmin — minimum value of the slider" }, { "code": null, "e": 8461, "s": 8424, "text": "valmax — maximum value of the slider" }, { "code": null, "e": 8604, "s": 8461, "text": "valfmt — the string to display as the value of the slider, positioned to the right. %1.1f is a float with 1 decimal point and %i is an integer" }, { "code": null, "e": 8648, "s": 8604, "text": "facecolor — the color to fill in the slider" }, { "code": null, "e": 8818, "s": 8648, "text": "Now that we have created our sliders, let us plot the “default” dataset that will show when the figure is first loaded (Fermi energy of 0.5 eV and temperature of 300 K):" }, { "code": null, "e": 8942, "s": 8818, "text": "# Plot default datax = np.linspace(-0, 1, 100)Ef_0 = 0.5T_0 = 100y = fermi(x, Ef_0, T_0)f_d, = ax.plot(x, y, linewidth=2.5)" }, { "code": null, "e": 9189, "s": 8942, "text": "Just like in the animated plot case, we now will define the update function that will change the data as the sliders are updated. This update function takes the current values of the sliders, changes the data in the plot, and re-draws the figure." }, { "code": null, "e": 9360, "s": 9189, "text": "# Update valuesdef update(val): Ef = s_Ef.val T = s_T.val f_d.set_data(x, fermi(x, Ef, T)) fig.canvas.draw_idle()s_Ef.on_changed(update)s_T.on_changed(update)" }, { "code": null, "e": 9510, "s": 9360, "text": "Slider.on_changed(func) calls the updating func when the slider value is changed. At last, when we show our plot we get this cool interactive figure!" } ]
FinRL for Quantitative Finance: Tutorial for Multiple Stock Trading | by Bruce Yang | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. This blog is a tutorial based on our paper: FinRL: A Deep Reinforcement Learning Library for Automated Stock Trading in Quantitative Finance, presented at NeurIPS 2020: Deep RL Workshop. arxiv.org The Jupyter notebook codes are available on our Github and Google Colab. github.com github.com A more complete application of FinRL for multiple stock trading can be found in our previous blog. To begin with, I would like explain the logic of multiple stock trading using Deep Reinforcement Learning. We use Dow 30 constituents as an example throughout this article, because those are the most popular stocks. A lot of people are terrified by the word “Deep Reinforcement Learning”, actually, you can just treat it as a “Smart AI” or “Smart Stock Trader” or “R2-D2 Trader” if you want, and just use it. Suppose that we have a well trained DRL agent “DRL Trader”, we want to use it to trade multiple stocks in our portfolio. Assume we are at time t, at the end of day at time t, we will know the open-high-low-close price of the Dow 30 constituents stocks. We can use these information to calculate technical indicators such as MACD, RSI, CCI, ADX. In Reinforcement Learning we call these data or features as “states”.We know that our portfolio value V(t) = balance (t) + dollar amount of the stocks (t).We feed the states into our well trained DRL Trader, the trader will output a list of actions, the action for each stock is a value within [-1, 1], we can treat this value as the trading signal, 1 means a strong buy signal, -1 means a strong sell signal.We calculate k = actions *h_max, h_max is a predefined parameter that sets as the maximum amount of shares to trade. So we will have a list of shares to trade.The dollar amount of shares = shares to trade* close price (t).Update balance and shares. These dollar amount of shares are the money we need to trade at time t. The updated balance = balance (t) −amount of money we pay to buy shares +amount of money we receive to sell shares. The updated shares = shares held (t) −shares to sell +shares to buy.So we take actions to trade based on the advice of our DRL Trader at the end of day at time t (time t’s close price equals time t+1’s open price). We hope that we will benefit from these actions by the end of day at time t+1.Take a step to time t+1, at the end of day, we will know the close price at t+1, the dollar amount of the stocks (t+1)= sum(updated shares * close price (t+1)). The portfolio value V(t+1)=balance (t+1) + dollar amount of the stocks (t+1).So the step reward by taking the actions from DRL Trader at time t to t+1 is r = v(t+1) − v(t). The reward can be positive or negative in the training stage. But of course, we need a positive reward in trading to say that our DRL Trader is effective.Repeat this process until termination. Assume we are at time t, at the end of day at time t, we will know the open-high-low-close price of the Dow 30 constituents stocks. We can use these information to calculate technical indicators such as MACD, RSI, CCI, ADX. In Reinforcement Learning we call these data or features as “states”. We know that our portfolio value V(t) = balance (t) + dollar amount of the stocks (t). We feed the states into our well trained DRL Trader, the trader will output a list of actions, the action for each stock is a value within [-1, 1], we can treat this value as the trading signal, 1 means a strong buy signal, -1 means a strong sell signal. We calculate k = actions *h_max, h_max is a predefined parameter that sets as the maximum amount of shares to trade. So we will have a list of shares to trade. The dollar amount of shares = shares to trade* close price (t). Update balance and shares. These dollar amount of shares are the money we need to trade at time t. The updated balance = balance (t) −amount of money we pay to buy shares +amount of money we receive to sell shares. The updated shares = shares held (t) −shares to sell +shares to buy. So we take actions to trade based on the advice of our DRL Trader at the end of day at time t (time t’s close price equals time t+1’s open price). We hope that we will benefit from these actions by the end of day at time t+1. Take a step to time t+1, at the end of day, we will know the close price at t+1, the dollar amount of the stocks (t+1)= sum(updated shares * close price (t+1)). The portfolio value V(t+1)=balance (t+1) + dollar amount of the stocks (t+1). So the step reward by taking the actions from DRL Trader at time t to t+1 is r = v(t+1) − v(t). The reward can be positive or negative in the training stage. But of course, we need a positive reward in trading to say that our DRL Trader is effective. Repeat this process until termination. Below are the logic chart of multiple stock trading and a made-up example for demonstration purpose: Multiple stock trading is different from single stock trading because as the number of stocks increase, the dimension of the data will increase, the state and action space in reinforcement learning will grow exponentially. So stability and reproducibility are very essential here. We introduce a DRL library FinRL that facilitates beginners to expose themselves to quantitative finance and to develop their own stock trading strategies. FinRL is characterized by its reproducibility, scalability, simplicity, applicability and extendibility. This article is focusing on one of the use cases in our paper: Mutiple Stock Trading. We use one Jupyter notebook to include all the necessary steps. Problem DefinitionLoad Python PackagesDownload DataPreprocess DataBuild EnvironmentImplement DRL AlgorithmsBacktesting Performance Problem Definition Load Python Packages Download Data Preprocess Data Build Environment Implement DRL Algorithms Backtesting Performance This problem is to design an automated trading solution for multiple stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem. The components of the reinforcement learning environment are: Action: {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For 30 stocks the entire action space is (2k+1)30, in this article we use k≤h_max=100, so the entire action space is around 1060. It means we can sample a maximum of 1060 pairs of state and action combinations. State: {balance, close price, shares, MACD, RSI, CCI, ADX}, 181-dimensional vector (30 stocks * 6 + 1) Reward function: r(s, a, s′) = v′ − v, where v′ and v represent the portfolio values at state s′ and s, respectively Environment: multiple stock trading for Dow 30 constituents. The data of the Dow 30 constituents stocks that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. Install the unstable development version of FinRL: # Install the unstable development version in Jupyter notebook:!pip install git+https://github.com/AI4Finance-Foundation/FinRL.git Import Packages: FinRL uses a YahooDownloader class to extract data. class YahooDownloader: """Provides methods for retrieving daily stock data from Yahoo Finance APIAttributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py)Methods ------- fetch_data() Fetches data from yahoo API""" Download and save the data in a pandas DataFrame: FinRL uses a FeatureEngineer class to preprocess data. class FeatureEngineer: """Provides methods for preprocessing the stock price dataAttributes ---------- df: DataFrame data downloaded from Yahoo API feature_number : int number of features we used use_technical_indicator : boolean we technical indicator or not use_turbulence : boolean use turbulence index or notMethods ------- preprocess_data() main method to do the feature engineering""" In real life trading, the model needs to be updated periodically using rolling windows. In this article, we just cut the data once into train and trade set. FinRL uses a EnvSetup class to setup environment. class EnvSetup: """Provides methods for retrieving daily stock data from Yahoo Finance APIAttributes ---------- stock_dim: int number of unique stocks hmax : int maximum number of shares to trade initial_amount: int start money transaction_cost_pct : float transaction cost percentage per trade reward_scaling: float scaling factor for reward, good for training tech_indicator_list: list a list of technical indicator names (modified from config.py)Methods ------- create_env_training() create env class for training create_env_validation() create env class for validation create_env_trading() create env class for trading""" The action space is just the number of unique stocks 30. The state space is 181 in this example. Initialize an environment class: User-defined Environment: a simulation environment class. The environment for training and trading is different in multiple stock trading case. Training v.s. Trading: turbulence index is used as a risk aversion signal after the actions generated by the DRL algorithms. Turbulence index should not be included in training, because it is not a part of model training, so only a trading environment should include the risk aversion signal. FinRL provides blueprint for training and trading environments in multiple stock trading. FinRL uses a DRLAgent class to implement the algorithms. class DRLAgent: """Provides implementations for DRL algorithmsAttributes ---------- env: gym environment class user-defined classMethods ------- train_PPO() the implementation for PPO algorithm train_A2C() the implementation for A2C algorithm train_DDPG() the implementation for DDPG algorithm train_TD3() the implementation for TD3 algorithm train_SAC() the implementation for SAC algorithm DRL_prediction() make a prediction in a test dataset and get results """ We use Soft Actor-Critic (SAC) for multiple stock trading, because it is one of the most recent state-of-art algorithms. SAC is featured by its stability. Assume that we have $1,000,000 initial capital at 2019/01/01. We use the SAC model to trade the Dow 30 stocks. FinRL uses a set of functions to do the backtesting with Quantopian pyfolio. The left table is the stats for backtesting performance, the right table is the stats for Index (DJIA) performance. Contributions of FinRL: FinRL is an open source library specifically designed and implemented for quantitative finance. Trading environments incorporating market frictions are used and provided. Trading tasks accompanied by hands-on tutorials with built-in DRL agents are available in a beginner-friendly and reproducible fashion using Jupyter notebook. Customization of trading time steps is feasible. FinRL has good scalability, with a broad range of fine-tuned state-of-the-art DRL algorithms. Adjusting the implementations to the rapid changing stock market is well supported. Typical use cases are selected and used to establish a benchmark for the quantitative finance community. Standard backtesting and evaluation metrics are also provided for easy and effective performance evaluation. I hope you found this article helpful and learned something about using DRL for multiple stock trading! Please report any issues to our Github.
[ { "code": null, "e": 471, "s": 171, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 658, "s": 471, "text": "This blog is a tutorial based on our paper: FinRL: A Deep Reinforcement Learning Library for Automated Stock Trading in Quantitative Finance, presented at NeurIPS 2020: Deep RL Workshop." }, { "code": null, "e": 668, "s": 658, "text": "arxiv.org" }, { "code": null, "e": 741, "s": 668, "text": "The Jupyter notebook codes are available on our Github and Google Colab." }, { "code": null, "e": 752, "s": 741, "text": "github.com" }, { "code": null, "e": 763, "s": 752, "text": "github.com" }, { "code": null, "e": 862, "s": 763, "text": "A more complete application of FinRL for multiple stock trading can be found in our previous blog." }, { "code": null, "e": 969, "s": 862, "text": "To begin with, I would like explain the logic of multiple stock trading using Deep Reinforcement Learning." }, { "code": null, "e": 1078, "s": 969, "text": "We use Dow 30 constituents as an example throughout this article, because those are the most popular stocks." }, { "code": null, "e": 1271, "s": 1078, "text": "A lot of people are terrified by the word “Deep Reinforcement Learning”, actually, you can just treat it as a “Smart AI” or “Smart Stock Trader” or “R2-D2 Trader” if you want, and just use it." }, { "code": null, "e": 1392, "s": 1271, "text": "Suppose that we have a well trained DRL agent “DRL Trader”, we want to use it to trade multiple stocks in our portfolio." }, { "code": null, "e": 3282, "s": 1392, "text": "Assume we are at time t, at the end of day at time t, we will know the open-high-low-close price of the Dow 30 constituents stocks. We can use these information to calculate technical indicators such as MACD, RSI, CCI, ADX. In Reinforcement Learning we call these data or features as “states”.We know that our portfolio value V(t) = balance (t) + dollar amount of the stocks (t).We feed the states into our well trained DRL Trader, the trader will output a list of actions, the action for each stock is a value within [-1, 1], we can treat this value as the trading signal, 1 means a strong buy signal, -1 means a strong sell signal.We calculate k = actions *h_max, h_max is a predefined parameter that sets as the maximum amount of shares to trade. So we will have a list of shares to trade.The dollar amount of shares = shares to trade* close price (t).Update balance and shares. These dollar amount of shares are the money we need to trade at time t. The updated balance = balance (t) −amount of money we pay to buy shares +amount of money we receive to sell shares. The updated shares = shares held (t) −shares to sell +shares to buy.So we take actions to trade based on the advice of our DRL Trader at the end of day at time t (time t’s close price equals time t+1’s open price). We hope that we will benefit from these actions by the end of day at time t+1.Take a step to time t+1, at the end of day, we will know the close price at t+1, the dollar amount of the stocks (t+1)= sum(updated shares * close price (t+1)). The portfolio value V(t+1)=balance (t+1) + dollar amount of the stocks (t+1).So the step reward by taking the actions from DRL Trader at time t to t+1 is r = v(t+1) − v(t). The reward can be positive or negative in the training stage. But of course, we need a positive reward in trading to say that our DRL Trader is effective.Repeat this process until termination." }, { "code": null, "e": 3576, "s": 3282, "text": "Assume we are at time t, at the end of day at time t, we will know the open-high-low-close price of the Dow 30 constituents stocks. We can use these information to calculate technical indicators such as MACD, RSI, CCI, ADX. In Reinforcement Learning we call these data or features as “states”." }, { "code": null, "e": 3663, "s": 3576, "text": "We know that our portfolio value V(t) = balance (t) + dollar amount of the stocks (t)." }, { "code": null, "e": 3918, "s": 3663, "text": "We feed the states into our well trained DRL Trader, the trader will output a list of actions, the action for each stock is a value within [-1, 1], we can treat this value as the trading signal, 1 means a strong buy signal, -1 means a strong sell signal." }, { "code": null, "e": 4078, "s": 3918, "text": "We calculate k = actions *h_max, h_max is a predefined parameter that sets as the maximum amount of shares to trade. So we will have a list of shares to trade." }, { "code": null, "e": 4142, "s": 4078, "text": "The dollar amount of shares = shares to trade* close price (t)." }, { "code": null, "e": 4426, "s": 4142, "text": "Update balance and shares. These dollar amount of shares are the money we need to trade at time t. The updated balance = balance (t) −amount of money we pay to buy shares +amount of money we receive to sell shares. The updated shares = shares held (t) −shares to sell +shares to buy." }, { "code": null, "e": 4652, "s": 4426, "text": "So we take actions to trade based on the advice of our DRL Trader at the end of day at time t (time t’s close price equals time t+1’s open price). We hope that we will benefit from these actions by the end of day at time t+1." }, { "code": null, "e": 4891, "s": 4652, "text": "Take a step to time t+1, at the end of day, we will know the close price at t+1, the dollar amount of the stocks (t+1)= sum(updated shares * close price (t+1)). The portfolio value V(t+1)=balance (t+1) + dollar amount of the stocks (t+1)." }, { "code": null, "e": 5142, "s": 4891, "text": "So the step reward by taking the actions from DRL Trader at time t to t+1 is r = v(t+1) − v(t). The reward can be positive or negative in the training stage. But of course, we need a positive reward in trading to say that our DRL Trader is effective." }, { "code": null, "e": 5181, "s": 5142, "text": "Repeat this process until termination." }, { "code": null, "e": 5282, "s": 5181, "text": "Below are the logic chart of multiple stock trading and a made-up example for demonstration purpose:" }, { "code": null, "e": 5563, "s": 5282, "text": "Multiple stock trading is different from single stock trading because as the number of stocks increase, the dimension of the data will increase, the state and action space in reinforcement learning will grow exponentially. So stability and reproducibility are very essential here." }, { "code": null, "e": 5719, "s": 5563, "text": "We introduce a DRL library FinRL that facilitates beginners to expose themselves to quantitative finance and to develop their own stock trading strategies." }, { "code": null, "e": 5824, "s": 5719, "text": "FinRL is characterized by its reproducibility, scalability, simplicity, applicability and extendibility." }, { "code": null, "e": 5974, "s": 5824, "text": "This article is focusing on one of the use cases in our paper: Mutiple Stock Trading. We use one Jupyter notebook to include all the necessary steps." }, { "code": null, "e": 6105, "s": 5974, "text": "Problem DefinitionLoad Python PackagesDownload DataPreprocess DataBuild EnvironmentImplement DRL AlgorithmsBacktesting Performance" }, { "code": null, "e": 6124, "s": 6105, "text": "Problem Definition" }, { "code": null, "e": 6145, "s": 6124, "text": "Load Python Packages" }, { "code": null, "e": 6159, "s": 6145, "text": "Download Data" }, { "code": null, "e": 6175, "s": 6159, "text": "Preprocess Data" }, { "code": null, "e": 6193, "s": 6175, "text": "Build Environment" }, { "code": null, "e": 6218, "s": 6193, "text": "Implement DRL Algorithms" }, { "code": null, "e": 6242, "s": 6218, "text": "Backtesting Performance" }, { "code": null, "e": 6459, "s": 6242, "text": "This problem is to design an automated trading solution for multiple stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem." }, { "code": null, "e": 6521, "s": 6459, "text": "The components of the reinforcement learning environment are:" }, { "code": null, "e": 6807, "s": 6521, "text": "Action: {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For 30 stocks the entire action space is (2k+1)30, in this article we use k≤h_max=100, so the entire action space is around 1060. It means we can sample a maximum of 1060 pairs of state and action combinations." }, { "code": null, "e": 6910, "s": 6807, "text": "State: {balance, close price, shares, MACD, RSI, CCI, ADX}, 181-dimensional vector (30 stocks * 6 + 1)" }, { "code": null, "e": 7027, "s": 6910, "text": "Reward function: r(s, a, s′) = v′ − v, where v′ and v represent the portfolio values at state s′ and s, respectively" }, { "code": null, "e": 7088, "s": 7027, "text": "Environment: multiple stock trading for Dow 30 constituents." }, { "code": null, "e": 7265, "s": 7088, "text": "The data of the Dow 30 constituents stocks that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume." }, { "code": null, "e": 7316, "s": 7265, "text": "Install the unstable development version of FinRL:" }, { "code": null, "e": 7447, "s": 7316, "text": "# Install the unstable development version in Jupyter notebook:!pip install git+https://github.com/AI4Finance-Foundation/FinRL.git" }, { "code": null, "e": 7464, "s": 7447, "text": "Import Packages:" }, { "code": null, "e": 7516, "s": 7464, "text": "FinRL uses a YahooDownloader class to extract data." }, { "code": null, "e": 7967, "s": 7516, "text": "class YahooDownloader: \"\"\"Provides methods for retrieving daily stock data from Yahoo Finance APIAttributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py)Methods ------- fetch_data() Fetches data from yahoo API\"\"\"" }, { "code": null, "e": 8017, "s": 7967, "text": "Download and save the data in a pandas DataFrame:" }, { "code": null, "e": 8072, "s": 8017, "text": "FinRL uses a FeatureEngineer class to preprocess data." }, { "code": null, "e": 8554, "s": 8072, "text": "class FeatureEngineer: \"\"\"Provides methods for preprocessing the stock price dataAttributes ---------- df: DataFrame data downloaded from Yahoo API feature_number : int number of features we used use_technical_indicator : boolean we technical indicator or not use_turbulence : boolean use turbulence index or notMethods ------- preprocess_data() main method to do the feature engineering\"\"\"" }, { "code": null, "e": 8711, "s": 8554, "text": "In real life trading, the model needs to be updated periodically using rolling windows. In this article, we just cut the data once into train and trade set." }, { "code": null, "e": 8761, "s": 8711, "text": "FinRL uses a EnvSetup class to setup environment." }, { "code": null, "e": 9489, "s": 8761, "text": "class EnvSetup: \"\"\"Provides methods for retrieving daily stock data from Yahoo Finance APIAttributes ---------- stock_dim: int number of unique stocks hmax : int maximum number of shares to trade initial_amount: int start money transaction_cost_pct : float transaction cost percentage per trade reward_scaling: float scaling factor for reward, good for training tech_indicator_list: list a list of technical indicator names (modified from config.py)Methods ------- create_env_training() create env class for training create_env_validation() create env class for validation create_env_trading() create env class for trading\"\"\"" }, { "code": null, "e": 9586, "s": 9489, "text": "The action space is just the number of unique stocks 30. The state space is 181 in this example." }, { "code": null, "e": 9619, "s": 9586, "text": "Initialize an environment class:" }, { "code": null, "e": 9677, "s": 9619, "text": "User-defined Environment: a simulation environment class." }, { "code": null, "e": 9763, "s": 9677, "text": "The environment for training and trading is different in multiple stock trading case." }, { "code": null, "e": 10056, "s": 9763, "text": "Training v.s. Trading: turbulence index is used as a risk aversion signal after the actions generated by the DRL algorithms. Turbulence index should not be included in training, because it is not a part of model training, so only a trading environment should include the risk aversion signal." }, { "code": null, "e": 10146, "s": 10056, "text": "FinRL provides blueprint for training and trading environments in multiple stock trading." }, { "code": null, "e": 10203, "s": 10146, "text": "FinRL uses a DRLAgent class to implement the algorithms." }, { "code": null, "e": 10753, "s": 10203, "text": "class DRLAgent: \"\"\"Provides implementations for DRL algorithmsAttributes ---------- env: gym environment class user-defined classMethods ------- train_PPO() the implementation for PPO algorithm train_A2C() the implementation for A2C algorithm train_DDPG() the implementation for DDPG algorithm train_TD3() the implementation for TD3 algorithm train_SAC() the implementation for SAC algorithm DRL_prediction() make a prediction in a test dataset and get results \"\"\"" }, { "code": null, "e": 10908, "s": 10753, "text": "We use Soft Actor-Critic (SAC) for multiple stock trading, because it is one of the most recent state-of-art algorithms. SAC is featured by its stability." }, { "code": null, "e": 11019, "s": 10908, "text": "Assume that we have $1,000,000 initial capital at 2019/01/01. We use the SAC model to trade the Dow 30 stocks." }, { "code": null, "e": 11096, "s": 11019, "text": "FinRL uses a set of functions to do the backtesting with Quantopian pyfolio." }, { "code": null, "e": 11212, "s": 11096, "text": "The left table is the stats for backtesting performance, the right table is the stats for Index (DJIA) performance." }, { "code": null, "e": 11236, "s": 11212, "text": "Contributions of FinRL:" }, { "code": null, "e": 11407, "s": 11236, "text": "FinRL is an open source library specifically designed and implemented for quantitative finance. Trading environments incorporating market frictions are used and provided." }, { "code": null, "e": 11615, "s": 11407, "text": "Trading tasks accompanied by hands-on tutorials with built-in DRL agents are available in a beginner-friendly and reproducible fashion using Jupyter notebook. Customization of trading time steps is feasible." }, { "code": null, "e": 11793, "s": 11615, "text": "FinRL has good scalability, with a broad range of fine-tuned state-of-the-art DRL algorithms. Adjusting the implementations to the rapid changing stock market is well supported." }, { "code": null, "e": 12007, "s": 11793, "text": "Typical use cases are selected and used to establish a benchmark for the quantitative finance community. Standard backtesting and evaluation metrics are also provided for easy and effective performance evaluation." }, { "code": null, "e": 12111, "s": 12007, "text": "I hope you found this article helpful and learned something about using DRL for multiple stock trading!" } ]
Program to Add Two Complex Numbers - GeeksforGeeks
18 Feb, 2022 Given two complex numbers of the form and the task is to add these two complex numbers. and Here the values of real and imaginary numbers are passed while calling the parameterized constructor and, with the help of a default(empty) constructor, the function addComp is called to get the addition of complex numbers. Illustration: Input: a1 = 4, b1 = 8 a2 = 5, b2 = 7 Output: Sum = 9 + i15 Explanation: (4 + i8) + (5 + i7) = (4 + 5) + i(8 + 7) = 9 + i15 Input: a1 = 9, b1 = 3 a2 = 6, b2 = 1 Output: 15 + i4 The following program is an illustration of the above example. C++ Java Python3 C# Javascript // C++ Program to Add Two Complex Numbers // Importing all libraries#include<bits/stdc++.h>using namespace std; // User Defined Complex classclass Complex { // Declaring variables public: int real, imaginary; // Constructor to accept // real and imaginary part Complex(int tempReal = 0, int tempImaginary = 0) { real = tempReal; imaginary = tempImaginary; } // Defining addComp() method // for adding two complex number Complex addComp(Complex C1, Complex C2) { // creating temporary variable Complex temp; // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; }}; // Main Classint main(){ // First Complex number Complex C1(3, 2); // printing first complex number cout<<"Complex number 1 : "<< C1.real << " + i"<< C1.imaginary<<endl; // Second Complex number Complex C2(9, 5); // printing second complex number cout<<"Complex number 2 : "<< C2.real << " + i"<< C2.imaginary<<endl; // for Storing the sum Complex C3; // calling addComp() method C3 = C3.addComp(C1, C2); // printing the sum cout<<"Sum of complex number : " << C3.real << " + i" << C3.imaginary;} // This code is contributed by chitranayal // Java Program to Add Two Complex Numbers // Importing all utility classesimport java.util.*; // Class 1// Helper class// User Defined Complex classclass Complex { // Declaring variables int real, imaginary; // Constructors of this class // Constructor 1 - Empty Constructor Complex() {} // Constructor 2 // Parameterised constructor // Constructor to accept // real and imaginary part Complex(int tempReal, int tempImaginary) { real = tempReal; imaginary = tempImaginary; } // Method // To add two complex number Complex addComp(Complex C1, Complex C2) { // Creating temporary variable Complex temp = new Complex(); // Adding real part of complex numbers temp.real = C1.real + C2.real; // Adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // Returning the sum return temp; }} // Class 2// Main Classpublic class GFG { // Main function public static void main(String[] args) { // First Complex number Complex C1 = new Complex(3, 2); // printing first complex number System.out.println("Complex number 1 : " + C1.real + " + i" + C1.imaginary); // Second Complex number Complex C2 = new Complex(9, 5); // Printing second complex number System.out.println("Complex number 2 : " + C2.real + " + i" + C2.imaginary); // Storing the sum Complex C3 = new Complex(); // Calling addComp() method C3 = C3.addComp(C1, C2); // Printing the sum System.out.println("Sum of complex number : " + C3.real + " + i" + C3.imaginary); }} # Python3 program to Add two complex numbers # User Defined Complex classclass Complex: # Constructor to accept # real and imaginary part def __init__(self, tempReal, tempImaginary): self.real = tempReal; self.imaginary = tempImaginary; # Defining addComp() method # for adding two complex number def addComp(self, C1, C2): # creating temporary variable temp=Complex(0, 0) # adding real part of complex numbers temp.real = C1.real + C2.real; # adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; # returning the sum return temp; # Driver codeif __name__=='__main__': # First Complex number C1 = Complex(3, 2); # printing first complex number print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary)) # Second Complex number C2 = Complex(9, 5); # printing second complex number print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary)) # for Storing the sum C3 = Complex(0, 0) # calling addComp() method C3 = C3.addComp(C1, C2); # printing the sum print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary)) # This code is contributed by rutvik_56. // C# program to Add two complex numbersusing System; // User Defined Complex classpublic class Complex{ // Declaring variables public int real, imaginary; // Empty Constructor public Complex() { } // Constructor to accept // real and imaginary part public Complex(int tempReal, int tempImaginary) { real = tempReal; imaginary = tempImaginary; } // Defining addComp() method // for adding two complex number public Complex addComp(Complex C1, Complex C2) { // creating temporary variable Complex temp = new Complex(); // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; }} // Main Classpublic class GFG{ // Main function public static void Main(String[] args) { // First Complex number Complex C1 = new Complex(3, 2); // printing first complex number Console.WriteLine("Complex number 1 : " + C1.real + " + i" + C1.imaginary); // Second Complex number Complex C2 = new Complex(9, 5); // printing second complex number Console.WriteLine("Complex number 2 : " + C2.real + " + i" + C2.imaginary); // for Storing the sum Complex C3 = new Complex(); // calling addComp() method C3 = C3.addComp(C1, C2); // printing the sum Console.WriteLine("Sum of complex number : " + C3.real + " + i" + C3.imaginary); }} // This code is contributed by Princi Singh <script>// Javascript program to Add two complex numbers // User Defined Complex class class Complex { // Constructor to accept // real and imaginary part constructor(tempReal, tempImaginary) { this.real = tempReal; this.imaginary = tempImaginary; } } // Defining addComp() method // for adding two complex number function addComp(C1,C2) { // creating temporary variable let temp = new Complex(); // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; } // First Complex number let C1 = new Complex(3, 2); // printing first complex number document.write("Complex number 1 : " + C1.real + " + i" + C1.imaginary+"<br>"); // Second Complex number let C2 = new Complex(9, 5); // printing second complex number document.write("Complex number 2 : " + C2.real + " + i" + C2.imaginary+"<br>"); // for Storing the sum let C3 = new Complex(); // calling addComp() method C3 = addComp(C1, C2); // printing the sum document.write("Sum of complex number : " + C3.real + " + i" + C3.imaginary+"<br>"); // This code is contributed by avanitrachhadiya2155</script> Complex number 1 : 3 + i2 Complex number 2 : 9 + i5 Sum of complex number : 12 + i7 princi singh ukasp khushboogoyal499 rutvik_56 avanitrachhadiya2155 utkarshgupta04092003 simranarora5sos number-theory Java Programs School Programming Technical Scripter number-theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Java Programming Examples How to Iterate HashMap in Java? Factory method design pattern in Java Traverse Through a HashMap in Java Iterate through List in Java Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 24551, "s": 24523, "text": "\n18 Feb, 2022" }, { "code": null, "e": 24639, "s": 24551, "text": "Given two complex numbers of the form and the task is to add these two complex numbers." }, { "code": null, "e": 24644, "s": 24639, "text": "and " }, { "code": null, "e": 24868, "s": 24644, "text": "Here the values of real and imaginary numbers are passed while calling the parameterized constructor and, with the help of a default(empty) constructor, the function addComp is called to get the addition of complex numbers." }, { "code": null, "e": 24884, "s": 24868, "text": "Illustration: " }, { "code": null, "e": 25110, "s": 24884, "text": "Input: a1 = 4, b1 = 8\n a2 = 5, b2 = 7\nOutput: Sum = 9 + i15\n\nExplanation: (4 + i8) + (5 + i7)\n = (4 + 5) + i(8 + 7) \n = 9 + i15\n\nInput: a1 = 9, b1 = 3\n a2 = 6, b2 = 1\nOutput: 15 + i4 " }, { "code": null, "e": 25173, "s": 25110, "text": "The following program is an illustration of the above example." }, { "code": null, "e": 25177, "s": 25173, "text": "C++" }, { "code": null, "e": 25182, "s": 25177, "text": "Java" }, { "code": null, "e": 25190, "s": 25182, "text": "Python3" }, { "code": null, "e": 25193, "s": 25190, "text": "C#" }, { "code": null, "e": 25204, "s": 25193, "text": "Javascript" }, { "code": "// C++ Program to Add Two Complex Numbers // Importing all libraries#include<bits/stdc++.h>using namespace std; // User Defined Complex classclass Complex { // Declaring variables public: int real, imaginary; // Constructor to accept // real and imaginary part Complex(int tempReal = 0, int tempImaginary = 0) { real = tempReal; imaginary = tempImaginary; } // Defining addComp() method // for adding two complex number Complex addComp(Complex C1, Complex C2) { // creating temporary variable Complex temp; // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; }}; // Main Classint main(){ // First Complex number Complex C1(3, 2); // printing first complex number cout<<\"Complex number 1 : \"<< C1.real << \" + i\"<< C1.imaginary<<endl; // Second Complex number Complex C2(9, 5); // printing second complex number cout<<\"Complex number 2 : \"<< C2.real << \" + i\"<< C2.imaginary<<endl; // for Storing the sum Complex C3; // calling addComp() method C3 = C3.addComp(C1, C2); // printing the sum cout<<\"Sum of complex number : \" << C3.real << \" + i\" << C3.imaginary;} // This code is contributed by chitranayal", "e": 26700, "s": 25204, "text": null }, { "code": "// Java Program to Add Two Complex Numbers // Importing all utility classesimport java.util.*; // Class 1// Helper class// User Defined Complex classclass Complex { // Declaring variables int real, imaginary; // Constructors of this class // Constructor 1 - Empty Constructor Complex() {} // Constructor 2 // Parameterised constructor // Constructor to accept // real and imaginary part Complex(int tempReal, int tempImaginary) { real = tempReal; imaginary = tempImaginary; } // Method // To add two complex number Complex addComp(Complex C1, Complex C2) { // Creating temporary variable Complex temp = new Complex(); // Adding real part of complex numbers temp.real = C1.real + C2.real; // Adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // Returning the sum return temp; }} // Class 2// Main Classpublic class GFG { // Main function public static void main(String[] args) { // First Complex number Complex C1 = new Complex(3, 2); // printing first complex number System.out.println(\"Complex number 1 : \" + C1.real + \" + i\" + C1.imaginary); // Second Complex number Complex C2 = new Complex(9, 5); // Printing second complex number System.out.println(\"Complex number 2 : \" + C2.real + \" + i\" + C2.imaginary); // Storing the sum Complex C3 = new Complex(); // Calling addComp() method C3 = C3.addComp(C1, C2); // Printing the sum System.out.println(\"Sum of complex number : \" + C3.real + \" + i\" + C3.imaginary); }}", "e": 28506, "s": 26700, "text": null }, { "code": "# Python3 program to Add two complex numbers # User Defined Complex classclass Complex: # Constructor to accept # real and imaginary part def __init__(self, tempReal, tempImaginary): self.real = tempReal; self.imaginary = tempImaginary; # Defining addComp() method # for adding two complex number def addComp(self, C1, C2): # creating temporary variable temp=Complex(0, 0) # adding real part of complex numbers temp.real = C1.real + C2.real; # adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; # returning the sum return temp; # Driver codeif __name__=='__main__': # First Complex number C1 = Complex(3, 2); # printing first complex number print(\"Complex number 1 :\", C1.real, \"+ i\" + str(C1.imaginary)) # Second Complex number C2 = Complex(9, 5); # printing second complex number print(\"Complex number 2 :\", C2.real, \"+ i\" + str(C2.imaginary)) # for Storing the sum C3 = Complex(0, 0) # calling addComp() method C3 = C3.addComp(C1, C2); # printing the sum print(\"Sum of complex number :\", C3.real, \"+ i\"+ str(C3.imaginary)) # This code is contributed by rutvik_56.", "e": 29767, "s": 28506, "text": null }, { "code": "// C# program to Add two complex numbersusing System; // User Defined Complex classpublic class Complex{ // Declaring variables public int real, imaginary; // Empty Constructor public Complex() { } // Constructor to accept // real and imaginary part public Complex(int tempReal, int tempImaginary) { real = tempReal; imaginary = tempImaginary; } // Defining addComp() method // for adding two complex number public Complex addComp(Complex C1, Complex C2) { // creating temporary variable Complex temp = new Complex(); // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; }} // Main Classpublic class GFG{ // Main function public static void Main(String[] args) { // First Complex number Complex C1 = new Complex(3, 2); // printing first complex number Console.WriteLine(\"Complex number 1 : \" + C1.real + \" + i\" + C1.imaginary); // Second Complex number Complex C2 = new Complex(9, 5); // printing second complex number Console.WriteLine(\"Complex number 2 : \" + C2.real + \" + i\" + C2.imaginary); // for Storing the sum Complex C3 = new Complex(); // calling addComp() method C3 = C3.addComp(C1, C2); // printing the sum Console.WriteLine(\"Sum of complex number : \" + C3.real + \" + i\" + C3.imaginary); }} // This code is contributed by Princi Singh", "e": 31536, "s": 29767, "text": null }, { "code": "<script>// Javascript program to Add two complex numbers // User Defined Complex class class Complex { // Constructor to accept // real and imaginary part constructor(tempReal, tempImaginary) { this.real = tempReal; this.imaginary = tempImaginary; } } // Defining addComp() method // for adding two complex number function addComp(C1,C2) { // creating temporary variable let temp = new Complex(); // adding real part of complex numbers temp.real = C1.real + C2.real; // adding Imaginary part of complex numbers temp.imaginary = C1.imaginary + C2.imaginary; // returning the sum return temp; } // First Complex number let C1 = new Complex(3, 2); // printing first complex number document.write(\"Complex number 1 : \" + C1.real + \" + i\" + C1.imaginary+\"<br>\"); // Second Complex number let C2 = new Complex(9, 5); // printing second complex number document.write(\"Complex number 2 : \" + C2.real + \" + i\" + C2.imaginary+\"<br>\"); // for Storing the sum let C3 = new Complex(); // calling addComp() method C3 = addComp(C1, C2); // printing the sum document.write(\"Sum of complex number : \" + C3.real + \" + i\" + C3.imaginary+\"<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 33103, "s": 31536, "text": null }, { "code": null, "e": 33187, "s": 33103, "text": "Complex number 1 : 3 + i2\nComplex number 2 : 9 + i5\nSum of complex number : 12 + i7" }, { "code": null, "e": 33200, "s": 33187, "text": "princi singh" }, { "code": null, "e": 33206, "s": 33200, "text": "ukasp" }, { "code": null, "e": 33223, "s": 33206, "text": "khushboogoyal499" }, { "code": null, "e": 33233, "s": 33223, "text": "rutvik_56" }, { "code": null, "e": 33254, "s": 33233, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33275, "s": 33254, "text": "utkarshgupta04092003" }, { "code": null, "e": 33291, "s": 33275, "text": "simranarora5sos" }, { "code": null, "e": 33305, "s": 33291, "text": "number-theory" }, { "code": null, "e": 33319, "s": 33305, "text": "Java Programs" }, { "code": null, "e": 33338, "s": 33319, "text": "School Programming" }, { "code": null, "e": 33357, "s": 33338, "text": "Technical Scripter" }, { "code": null, "e": 33371, "s": 33357, "text": "number-theory" }, { "code": null, "e": 33469, "s": 33371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33478, "s": 33469, "text": "Comments" }, { "code": null, "e": 33491, "s": 33478, "text": "Old Comments" }, { "code": null, "e": 33517, "s": 33491, "text": "Java Programming Examples" }, { "code": null, "e": 33549, "s": 33517, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 33587, "s": 33549, "text": "Factory method design pattern in Java" }, { "code": null, "e": 33622, "s": 33587, "text": "Traverse Through a HashMap in Java" }, { "code": null, "e": 33651, "s": 33622, "text": "Iterate through List in Java" }, { "code": null, "e": 33669, "s": 33651, "text": "Python Dictionary" }, { "code": null, "e": 33685, "s": 33669, "text": "Arrays in C/C++" }, { "code": null, "e": 33710, "s": 33685, "text": "Reverse a string in Java" }, { "code": null, "e": 33729, "s": 33710, "text": "Inheritance in C++" } ]
HTML | <table> width Attribute
29 May, 2019 The HTML <table> width Attribute is used to specify the width of a table. If width attribute is not set then it takes default width according to content. Syntax: <table width="pixels | %"> Attribute Values: pixels: It sets the width of table in terms of pixels. %: It sets the width of table in terms of percentage (%). Note: The <table> width Attribute is not supported by HTML 5. Example: <!DOCTYPE html><html> <head> <title> HTML table width Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table width Attribute</h2> <table border="1" width="250"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <table> width Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera 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": 28, "s": 0, "text": "\n29 May, 2019" }, { "code": null, "e": 182, "s": 28, "text": "The HTML <table> width Attribute is used to specify the width of a table. If width attribute is not set then it takes default width according to content." }, { "code": null, "e": 190, "s": 182, "text": "Syntax:" }, { "code": null, "e": 217, "s": 190, "text": "<table width=\"pixels | %\">" }, { "code": null, "e": 235, "s": 217, "text": "Attribute Values:" }, { "code": null, "e": 290, "s": 235, "text": "pixels: It sets the width of table in terms of pixels." }, { "code": null, "e": 348, "s": 290, "text": "%: It sets the width of table in terms of percentage (%)." }, { "code": null, "e": 410, "s": 348, "text": "Note: The <table> width Attribute is not supported by HTML 5." }, { "code": null, "e": 419, "s": 410, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML table width Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table width Attribute</h2> <table border=\"1\" width=\"250\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </table></body> </html>", "e": 862, "s": 419, "text": null }, { "code": null, "e": 870, "s": 862, "text": "Output:" }, { "code": null, "e": 962, "s": 870, "text": "Supported Browsers: The browser supported by HTML <table> width Attribute are listed below:" }, { "code": null, "e": 976, "s": 962, "text": "Google Chrome" }, { "code": null, "e": 994, "s": 976, "text": "Internet Explorer" }, { "code": null, "e": 1002, "s": 994, "text": "Firefox" }, { "code": null, "e": 1009, "s": 1002, "text": "Safari" }, { "code": null, "e": 1015, "s": 1009, "text": "Opera" }, { "code": null, "e": 1031, "s": 1015, "text": "HTML-Attributes" }, { "code": null, "e": 1036, "s": 1031, "text": "HTML" }, { "code": null, "e": 1053, "s": 1036, "text": "Web Technologies" }, { "code": null, "e": 1058, "s": 1053, "text": "HTML" } ]
Output of Python Programs | Set 21 (Bool)
11 Jun, 2021 Prerequisite : Boolean Note: Output of all these programs is tested on Python31. What is the output of the code: Python3 print(bool('False'))print(bool()) False, TrueNone, NoneTrue, TrueTrue, False False, True None, None True, True True, False Output: 4. True, False Explanation: If the argument passed to the bool function does not amount to zero then the Boolean function returns true else it always returns false. In the above code, in first line ‘False’ is passed to the function which is not amount to 0. Therefore output is true. In the second line, an empty list is passed to the function bool. Hence the output is false.2. What is the output of the code: Python3 print(not(4>3))print(not(5&5)) False, FalseNone, NoneTrue, TrueTrue, False False, False None, None True, True True, False Output: 1. False, False Explanation: The not function returns true if the argument is false, and false if the argument is true. Hence the first line of above code returns false, and the second line will also returns false.3. What is the output of the code: Python3 print(['love', 'python'][bool('gfg')]) lovepythongfgNone love python gfg None Output: 2. python Explanation: We can read the above code as print ‘love’ if the argument passed to the Boolean function is zero else print ‘python’. The argument passed to the Boolean function in the above code is ‘gfg’, which does not amount to zero and hence the output is: “python”.4. What is the output of the code: Python3 mylist =[0, 5, 2, 0, 'gfg', '', []]print(list(filter(bool, mylist))) [0, 0, ][0, 5, 2, 0, ‘gfg’, ”, []]Error[5, 2, ‘gfg’] [0, 0, ] [0, 5, 2, 0, ‘gfg’, ”, []] Error [5, 2, ‘gfg’] Output: 4. [5, 2, 'gfg'] Explanation: The code above returns a new list containing only those elements of the list mylist which are not equal to zero. Hence the output is: [5, 2, ‘gfg’].5. What is the output of the code: Python3 if (7 < 0) and (0 < -7): print("abhi")elif (7 > 0) or False: print("love")else: print("geeksforgeeks") geeksforgeeksloveabhiError geeksforgeeks love abhi Error Output: 2. love Explanation: The code shown above prints the appropriate option depending on the conditions given. The condition which matches is (7>0), and hence the output is: “love”. surinderdawra388 Python-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jun, 2021" }, { "code": null, "e": 167, "s": 52, "text": "Prerequisite : Boolean Note: Output of all these programs is tested on Python31. What is the output of the code: " }, { "code": null, "e": 175, "s": 167, "text": "Python3" }, { "code": "print(bool('False'))print(bool())", "e": 209, "s": 175, "text": null }, { "code": null, "e": 252, "s": 209, "text": "False, TrueNone, NoneTrue, TrueTrue, False" }, { "code": null, "e": 264, "s": 252, "text": "False, True" }, { "code": null, "e": 275, "s": 264, "text": "None, None" }, { "code": null, "e": 286, "s": 275, "text": "True, True" }, { "code": null, "e": 298, "s": 286, "text": "True, False" }, { "code": null, "e": 308, "s": 298, "text": "Output: " }, { "code": null, "e": 323, "s": 308, "text": "4. True, False" }, { "code": null, "e": 721, "s": 323, "text": "Explanation: If the argument passed to the bool function does not amount to zero then the Boolean function returns true else it always returns false. In the above code, in first line ‘False’ is passed to the function which is not amount to 0. Therefore output is true. In the second line, an empty list is passed to the function bool. Hence the output is false.2. What is the output of the code: " }, { "code": null, "e": 729, "s": 721, "text": "Python3" }, { "code": "print(not(4>3))print(not(5&5))", "e": 760, "s": 729, "text": null }, { "code": null, "e": 804, "s": 760, "text": "False, FalseNone, NoneTrue, TrueTrue, False" }, { "code": null, "e": 817, "s": 804, "text": "False, False" }, { "code": null, "e": 828, "s": 817, "text": "None, None" }, { "code": null, "e": 839, "s": 828, "text": "True, True" }, { "code": null, "e": 851, "s": 839, "text": "True, False" }, { "code": null, "e": 861, "s": 851, "text": "Output: " }, { "code": null, "e": 877, "s": 861, "text": "1. False, False" }, { "code": null, "e": 1112, "s": 877, "text": "Explanation: The not function returns true if the argument is false, and false if the argument is true. Hence the first line of above code returns false, and the second line will also returns false.3. What is the output of the code: " }, { "code": null, "e": 1120, "s": 1112, "text": "Python3" }, { "code": "print(['love', 'python'][bool('gfg')])", "e": 1159, "s": 1120, "text": null }, { "code": null, "e": 1177, "s": 1159, "text": "lovepythongfgNone" }, { "code": null, "e": 1182, "s": 1177, "text": "love" }, { "code": null, "e": 1189, "s": 1182, "text": "python" }, { "code": null, "e": 1193, "s": 1189, "text": "gfg" }, { "code": null, "e": 1198, "s": 1193, "text": "None" }, { "code": null, "e": 1208, "s": 1198, "text": "Output: " }, { "code": null, "e": 1218, "s": 1208, "text": "2. python" }, { "code": null, "e": 1523, "s": 1218, "text": "Explanation: We can read the above code as print ‘love’ if the argument passed to the Boolean function is zero else print ‘python’. The argument passed to the Boolean function in the above code is ‘gfg’, which does not amount to zero and hence the output is: “python”.4. What is the output of the code: " }, { "code": null, "e": 1531, "s": 1523, "text": "Python3" }, { "code": "mylist =[0, 5, 2, 0, 'gfg', '', []]print(list(filter(bool, mylist)))", "e": 1600, "s": 1531, "text": null }, { "code": null, "e": 1653, "s": 1600, "text": "[0, 0, ][0, 5, 2, 0, ‘gfg’, ”, []]Error[5, 2, ‘gfg’]" }, { "code": null, "e": 1662, "s": 1653, "text": "[0, 0, ]" }, { "code": null, "e": 1689, "s": 1662, "text": "[0, 5, 2, 0, ‘gfg’, ”, []]" }, { "code": null, "e": 1695, "s": 1689, "text": "Error" }, { "code": null, "e": 1709, "s": 1695, "text": "[5, 2, ‘gfg’]" }, { "code": null, "e": 1719, "s": 1709, "text": "Output: " }, { "code": null, "e": 1736, "s": 1719, "text": "4. [5, 2, 'gfg']" }, { "code": null, "e": 1934, "s": 1736, "text": "Explanation: The code above returns a new list containing only those elements of the list mylist which are not equal to zero. Hence the output is: [5, 2, ‘gfg’].5. What is the output of the code: " }, { "code": null, "e": 1942, "s": 1934, "text": "Python3" }, { "code": "if (7 < 0) and (0 < -7): print(\"abhi\")elif (7 > 0) or False: print(\"love\")else: print(\"geeksforgeeks\")", "e": 2054, "s": 1942, "text": null }, { "code": null, "e": 2081, "s": 2054, "text": "geeksforgeeksloveabhiError" }, { "code": null, "e": 2095, "s": 2081, "text": "geeksforgeeks" }, { "code": null, "e": 2100, "s": 2095, "text": "love" }, { "code": null, "e": 2105, "s": 2100, "text": "abhi" }, { "code": null, "e": 2111, "s": 2105, "text": "Error" }, { "code": null, "e": 2121, "s": 2111, "text": "Output: " }, { "code": null, "e": 2129, "s": 2121, "text": "2. love" }, { "code": null, "e": 2300, "s": 2129, "text": "Explanation: The code shown above prints the appropriate option depending on the conditions given. The condition which matches is (7>0), and hence the output is: “love”. " }, { "code": null, "e": 2317, "s": 2300, "text": "surinderdawra388" }, { "code": null, "e": 2331, "s": 2317, "text": "Python-Output" }, { "code": null, "e": 2346, "s": 2331, "text": "Program Output" } ]
Node.js process.platform Property
12 Oct, 2021 The process.platform property is an inbuilt application programming interface of the process module which is used to get the Operating System platform information. Syntax: process.platform Return Value: This property returns a string that represents the operating system platform. The returned value can be one of these ‘aix’, ‘android’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunprocess’, and ‘win32’. This values is set at compile time. Below examples illustrate the use of process.platform property in Node.js: Example 1: Javascript // Node.js program to demonstrate the// process.platform Property // Include process moduleconst process = require('process'); // Printing process.platform property valueconsole.log(process.platform); Output: win32 Example 2: Javascript // Node.js program to demonstrate the// process.platform Property // Include process moduleconst process = require('process'); // Printing process.platform property valuevar platform = process.platform;switch(platform) { case 'aix': console.log("IBM AIX platform"); break; case 'darwin': console.log("Darwin platform(MacOS, IOS etc)"); break; case 'freebsd': console.log("FreeBSD Platform"); break; case 'linux': console.log("Linux Platform"); break; case 'openbsd': console.log("OpenBSD platform"); break; case 'sunos': console.log("SunOS platform"); break; case 'win32': console.log("windows platform"); break; default: console.log("unknown platform");} Output: windows platform Note: The above program will compile and run by using the node filename.js command.Reference: https://nodejs.org/api/process.html#process_process_platform singghakshay Node.js-process-module 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 How to connect Node.js with React.js ? 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": "\n12 Oct, 2021" }, { "code": null, "e": 192, "s": 28, "text": "The process.platform property is an inbuilt application programming interface of the process module which is used to get the Operating System platform information." }, { "code": null, "e": 202, "s": 192, "text": "Syntax: " }, { "code": null, "e": 219, "s": 202, "text": "process.platform" }, { "code": null, "e": 472, "s": 219, "text": "Return Value: This property returns a string that represents the operating system platform. The returned value can be one of these ‘aix’, ‘android’, ‘darwin’, ‘freebsd’, ‘linux’, ‘openbsd’, ‘sunprocess’, and ‘win32’. This values is set at compile time." }, { "code": null, "e": 547, "s": 472, "text": "Below examples illustrate the use of process.platform property in Node.js:" }, { "code": null, "e": 560, "s": 547, "text": "Example 1: " }, { "code": null, "e": 571, "s": 560, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// process.platform Property // Include process moduleconst process = require('process'); // Printing process.platform property valueconsole.log(process.platform);", "e": 775, "s": 571, "text": null }, { "code": null, "e": 784, "s": 775, "text": "Output: " }, { "code": null, "e": 790, "s": 784, "text": "win32" }, { "code": null, "e": 802, "s": 790, "text": "Example 2: " }, { "code": null, "e": 813, "s": 802, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// process.platform Property // Include process moduleconst process = require('process'); // Printing process.platform property valuevar platform = process.platform;switch(platform) { case 'aix': console.log(\"IBM AIX platform\"); break; case 'darwin': console.log(\"Darwin platform(MacOS, IOS etc)\"); break; case 'freebsd': console.log(\"FreeBSD Platform\"); break; case 'linux': console.log(\"Linux Platform\"); break; case 'openbsd': console.log(\"OpenBSD platform\"); break; case 'sunos': console.log(\"SunOS platform\"); break; case 'win32': console.log(\"windows platform\"); break; default: console.log(\"unknown platform\");}", "e": 1612, "s": 813, "text": null }, { "code": null, "e": 1621, "s": 1612, "text": "Output: " }, { "code": null, "e": 1638, "s": 1621, "text": "windows platform" }, { "code": null, "e": 1794, "s": 1638, "text": "Note: The above program will compile and run by using the node filename.js command.Reference: https://nodejs.org/api/process.html#process_process_platform " }, { "code": null, "e": 1807, "s": 1794, "text": "singghakshay" }, { "code": null, "e": 1830, "s": 1807, "text": "Node.js-process-module" }, { "code": null, "e": 1838, "s": 1830, "text": "Node.js" }, { "code": null, "e": 1855, "s": 1838, "text": "Web Technologies" }, { "code": null, "e": 1953, "s": 1855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1985, "s": 1953, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2020, "s": 1985, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2090, "s": 2020, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2117, "s": 2090, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2156, "s": 2117, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 2218, "s": 2156, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2279, "s": 2218, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2329, "s": 2279, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2372, "s": 2329, "text": "How to fetch data from an API in ReactJS ?" } ]
Comparator nullsFirst() method in Java with examples
29 Apr, 2019 The nullsFirst(java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values to be less than non-null. The null first operates by the following logic: The null element is considered to be less than non-null.When both elements are null, then they are considered equal.When both elements are non-null, the specified Comparator determines the order.If the specified comparator is null, then the returned comparator considers all non-null elements equal.The returned comparator is serializable if the specified comparator is serializable. The null element is considered to be less than non-null. When both elements are null, then they are considered equal. When both elements are non-null, the specified Comparator determines the order. If the specified comparator is null, then the returned comparator considers all non-null elements equal. The returned comparator is serializable if the specified comparator is serializable. Syntax: static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) Parameters: This method accepts a single parameter comparator which is a Comparator for comparing non-null values Return value: This method returns a comparator that considers null to be less than non-null and compares non-null objects with the supplied Comparator. Below programs illustrate nullsFirst(java.util.Comparator) method:Program 1: // Java program to demonstrate// Comparator.nullsFirst(java.util.Comparator) method import java.util.Arrays;import java.util.Comparator; public class GFG { public static void main(String[] args) { // Create a collection of an array // of names also contain nulls String[] strings = { "aman", "suvam", null, "sahil", null }; // print the array System.out.println("Before sorting: " + Arrays.toString(strings)); // apply nullsFirst method // and sort the array Arrays.sort(strings, Comparator.nullsFirst( Comparator.naturalOrder())); // print the array System.out.println("After sorting: " + Arrays.toString(strings)); }} The output printed on console of IDE is shown below.Output: Program 2: // Java program to demonstrate// Comparator.nullsFirst(java.util.Comparator) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class GFG { public static void main(String[] args) { // Create some user objects User u1 = new User("Aaman", 25); User u2 = new User("Joyita", 22); User u3 = new User("Suvam", 28); User u4 = new User("mahafuj", 25); System.out.println("One null Objects"); List<User> list = Arrays.asList(u1, u2, u3, null, u4); Collections.sort(list, Comparator.nullsFirst( Comparator.comparing( User::getName))); list.forEach(user -> System.out.println(user)); System.out.println("\nMore than One null Objects"); list = Arrays.asList(u1, u4, null, u2, u3, null, null); Collections.sort(list, Comparator.nullsFirst( Comparator.comparing( User::getName))); list.forEach(user -> System.out.println(user)); }} class User implements Comparable<User> { public String name; public int age; public User(String name, int age) { this.name = name; this.age = age; } public int compareTo(User u1) { return name.compareTo(u1.name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; }} The output printed on console is shown below.Output: References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#nullsFirst(java.util.Comparator) Java - util package Java-Comparator Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Multidimensional Arrays in Java Collections in Java Stream In Java Set in Java Singleton Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2019" }, { "code": null, "e": 226, "s": 28, "text": "The nullsFirst(java.util.Comparator) method returns comparator that is a null-friendly comparator and considers null values to be less than non-null. The null first operates by the following logic:" }, { "code": null, "e": 610, "s": 226, "text": "The null element is considered to be less than non-null.When both elements are null, then they are considered equal.When both elements are non-null, the specified Comparator determines the order.If the specified comparator is null, then the returned comparator considers all non-null elements equal.The returned comparator is serializable if the specified comparator is serializable." }, { "code": null, "e": 667, "s": 610, "text": "The null element is considered to be less than non-null." }, { "code": null, "e": 728, "s": 667, "text": "When both elements are null, then they are considered equal." }, { "code": null, "e": 808, "s": 728, "text": "When both elements are non-null, the specified Comparator determines the order." }, { "code": null, "e": 913, "s": 808, "text": "If the specified comparator is null, then the returned comparator considers all non-null elements equal." }, { "code": null, "e": 998, "s": 913, "text": "The returned comparator is serializable if the specified comparator is serializable." }, { "code": null, "e": 1006, "s": 998, "text": "Syntax:" }, { "code": null, "e": 1077, "s": 1006, "text": "static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator)\n" }, { "code": null, "e": 1191, "s": 1077, "text": "Parameters: This method accepts a single parameter comparator which is a Comparator for comparing non-null values" }, { "code": null, "e": 1343, "s": 1191, "text": "Return value: This method returns a comparator that considers null to be less than non-null and compares non-null objects with the supplied Comparator." }, { "code": null, "e": 1420, "s": 1343, "text": "Below programs illustrate nullsFirst(java.util.Comparator) method:Program 1:" }, { "code": "// Java program to demonstrate// Comparator.nullsFirst(java.util.Comparator) method import java.util.Arrays;import java.util.Comparator; public class GFG { public static void main(String[] args) { // Create a collection of an array // of names also contain nulls String[] strings = { \"aman\", \"suvam\", null, \"sahil\", null }; // print the array System.out.println(\"Before sorting: \" + Arrays.toString(strings)); // apply nullsFirst method // and sort the array Arrays.sort(strings, Comparator.nullsFirst( Comparator.naturalOrder())); // print the array System.out.println(\"After sorting: \" + Arrays.toString(strings)); }}", "e": 2281, "s": 1420, "text": null }, { "code": null, "e": 2341, "s": 2281, "text": "The output printed on console of IDE is shown below.Output:" }, { "code": null, "e": 2352, "s": 2341, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Comparator.nullsFirst(java.util.Comparator) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class GFG { public static void main(String[] args) { // Create some user objects User u1 = new User(\"Aaman\", 25); User u2 = new User(\"Joyita\", 22); User u3 = new User(\"Suvam\", 28); User u4 = new User(\"mahafuj\", 25); System.out.println(\"One null Objects\"); List<User> list = Arrays.asList(u1, u2, u3, null, u4); Collections.sort(list, Comparator.nullsFirst( Comparator.comparing( User::getName))); list.forEach(user -> System.out.println(user)); System.out.println(\"\\nMore than One null Objects\"); list = Arrays.asList(u1, u4, null, u2, u3, null, null); Collections.sort(list, Comparator.nullsFirst( Comparator.comparing( User::getName))); list.forEach(user -> System.out.println(user)); }} class User implements Comparable<User> { public String name; public int age; public User(String name, int age) { this.name = name; this.age = age; } public int compareTo(User u1) { return name.compareTo(u1.name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return \"User [name=\" + name + \", age=\" + age + \"]\"; }}", "e": 4152, "s": 2352, "text": null }, { "code": null, "e": 4205, "s": 4152, "text": "The output printed on console is shown below.Output:" }, { "code": null, "e": 4319, "s": 4205, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#nullsFirst(java.util.Comparator)" }, { "code": null, "e": 4339, "s": 4319, "text": "Java - util package" }, { "code": null, "e": 4355, "s": 4339, "text": "Java-Comparator" }, { "code": null, "e": 4370, "s": 4355, "text": "Java-Functions" }, { "code": null, "e": 4375, "s": 4370, "text": "Java" }, { "code": null, "e": 4380, "s": 4375, "text": "Java" }, { "code": null, "e": 4478, "s": 4380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4529, "s": 4478, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4560, "s": 4529, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4579, "s": 4560, "text": "Interfaces in Java" }, { "code": null, "e": 4609, "s": 4579, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4627, "s": 4609, "text": "ArrayList in Java" }, { "code": null, "e": 4659, "s": 4627, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4679, "s": 4659, "text": "Collections in Java" }, { "code": null, "e": 4694, "s": 4679, "text": "Stream In Java" }, { "code": null, "e": 4706, "s": 4694, "text": "Set in Java" } ]
Simple Keyboard Racing with Python
21 Jul, 2021 Let’s make a simple keyboard racing game using Python. In the game, the participant clicks a pair of keys in quick succession and the program shows the total time taken by the racer to cover the distance. Rules: As soon as you see ‘GO!’ on screen, start pressing the keys ‘z’ and ‘x’. A ‘*’ sign is shown for every meter covered. Pressing ‘z’ and ‘x’ once will be counted as 1 meter; targets is to cover 10 meters. Modules Used: msvcrt : Used to get keystroke as input for race time : Used to calculate time taken to complete the race Note that MSVCRT module can only function on a terminal window, not on a GUI program/IDE. Below is the code: Python3 import msvcrtimport time high_score = 17.78name = "GeeksforGeeks"while True: distance = int(0) print('\n--------------------------------------------------------------') print('\n\nWelcome to the 100m sprint, tap z and x rapidly to move!') print('* = 10m') print('\nCurrent record:' + str(high_score) + ' by: ' + name) print('\nPress enter to start') input() print('Ready...') time.sleep(1) print('GO!') start_time = time.time() while distance < 10: k1 = msvcrt.getch().decode('ASCII') if k1 == 'z': k2 = msvcrt.getch().decode('ASCII') if k2 == 'x': distance += 1 if distance == 5: print("* You're halfway there!") elif distance % 1 == 0: print('*') fin_time = time.time() - start_time fin_time = round(fin_time, 2) print('Congratulations on successfully completing the race!') print('You took', fin_time, 'seconds to reach the finish line') if fin_time < high_score: print("Well done you've got a new high score ") name = input("Please enter your name : ") high_score = fin_time Output: Game Initiate Game in Progress Game Finished: New High Score ruhelaa48 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jul, 2021" }, { "code": null, "e": 257, "s": 52, "text": "Let’s make a simple keyboard racing game using Python. In the game, the participant clicks a pair of keys in quick succession and the program shows the total time taken by the racer to cover the distance." }, { "code": null, "e": 467, "s": 257, "text": "Rules: As soon as you see ‘GO!’ on screen, start pressing the keys ‘z’ and ‘x’. A ‘*’ sign is shown for every meter covered. Pressing ‘z’ and ‘x’ once will be counted as 1 meter; targets is to cover 10 meters." }, { "code": null, "e": 482, "s": 467, "text": "Modules Used: " }, { "code": null, "e": 588, "s": 482, "text": "msvcrt : Used to get keystroke as input for race\ntime : Used to calculate time taken to complete the race" }, { "code": null, "e": 678, "s": 588, "text": "Note that MSVCRT module can only function on a terminal window, not on a GUI program/IDE." }, { "code": null, "e": 699, "s": 678, "text": "Below is the code: " }, { "code": null, "e": 707, "s": 699, "text": "Python3" }, { "code": "import msvcrtimport time high_score = 17.78name = \"GeeksforGeeks\"while True: distance = int(0) print('\\n--------------------------------------------------------------') print('\\n\\nWelcome to the 100m sprint, tap z and x rapidly to move!') print('* = 10m') print('\\nCurrent record:' + str(high_score) + ' by: ' + name) print('\\nPress enter to start') input() print('Ready...') time.sleep(1) print('GO!') start_time = time.time() while distance < 10: k1 = msvcrt.getch().decode('ASCII') if k1 == 'z': k2 = msvcrt.getch().decode('ASCII') if k2 == 'x': distance += 1 if distance == 5: print(\"* You're halfway there!\") elif distance % 1 == 0: print('*') fin_time = time.time() - start_time fin_time = round(fin_time, 2) print('Congratulations on successfully completing the race!') print('You took', fin_time, 'seconds to reach the finish line') if fin_time < high_score: print(\"Well done you've got a new high score \") name = input(\"Please enter your name : \") high_score = fin_time", "e": 1882, "s": 707, "text": null }, { "code": null, "e": 1891, "s": 1882, "text": "Output: " }, { "code": null, "e": 1905, "s": 1891, "text": "Game Initiate" }, { "code": null, "e": 1922, "s": 1905, "text": "Game in Progress" }, { "code": null, "e": 1952, "s": 1922, "text": "Game Finished: New High Score" }, { "code": null, "e": 1964, "s": 1954, "text": "ruhelaa48" }, { "code": null, "e": 1979, "s": 1964, "text": "python-utility" }, { "code": null, "e": 1986, "s": 1979, "text": "Python" } ]
Find lexicographically smallest string in at most one swaps
29 Jun, 2022 Given a string str of length N. The task is to find out the lexicographically smallest string when at most only one swap is allowed. That is, two indices 1 <= i, j <= n can be chosen and swapped. This operation can be performed at most one time. Examples: Input: str = “string” Output: gtrins Explanation: Choose i=1, j=6, string becomes – gtrins. This is lexicographically smallest strings that can be formed. Input: str = “zyxw” Output: wyxz Approach: The idea is to use sorting and compute the smallest lexicographical string possible for the given string. After computing the sorted string, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string. For example, let str = “geeks” and the sorted = “eegks”. First unmatched character is in the first place. This character has to swapped such that this character matches the character with sorted string. Resulting lexicographical smallest string. On replacing “g” with the last occurring “e”, the string becomes eegks which is lexicographically smallest. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the lexicographically// smallest string that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.string findSmallest(string s){ int len = s.size(); // Store last occurrence of every character // and set -1 as default for every character. vector<int> loccur(26,-1); for (int i = len - 1; i >= 0; --i) { // Character index to fill // in the last occurrence array int chI = s[i] - 'a'; if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } string sorted_s = s; sort(sorted_s.begin(), sorted_s.end()); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character. int last_occ = loccur[chI]; // Swap this with the last occurrence swap(s[i], s[last_occ]); break; } } return s;} // Driver codeint main(){ string s = "geeks"; cout << findSmallest(s); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ // Function to return the lexicographically// smallest String that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.static String findSmallest(char []s){ int len = s.length; // Store last occurrence of every character int []loccur = new int[26]; // Set -1 as default for every character. Arrays.fill(loccur, -1); for (int i = len - 1; i >= 0; --i) { // Character index to fill // in the last occurrence array int chI = s[i] - 'a'; if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } char []sorted_s = s; Arrays.sort(sorted_s); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character. int last_occ = loccur[chI]; // Swap this with the last occurrence char temp = s[last_occ]; s[last_occ] = s[i]; s[i] = temp; break; } } return String.valueOf(s);} // Driver codepublic static void main(String[] args){ String s = "geeks"; System.out.print(findSmallest(s.toCharArray()));}} // This code is contributed by 29AjayKumar # Python3 implementation of the above approach # Function to return the lexicographically# smallest string that can be formed by# swapping at most one character.# The characters might not necessarily# be adjacent.def findSmallest(s) : length = len(s); # Store last occurrence of every character # Set -1 as default for every character. loccur = [-1]*26; for i in range(length - 1, -1, -1) : # Character index to fill # in the last occurrence array chI = ord(s[i]) - ord('a'); if (loccur[chI] == -1) : # If this is true then this # character is being visited # for the first time from the last # Thus last occurrence of this # character is stored in this index loccur[chI] = i; sorted_s = s; sorted_s.sort(); for i in range(length) : if (s[i] != sorted_s[i]) : # Character to replace chI = ord(sorted_s[i]) - ord('a'); # Find the last occurrence # of this character. last_occ = loccur[chI]; # Swap this with the last occurrence # swap(s[i], s[last_occ]); s[i],s[last_occ] = s[last_occ],s[i] break; return "".join(s); # Driver codeif __name__ == "__main__" : s = "geeks"; print(findSmallest(list(s))); # This code is contributed by Yash_R // C# implementation of the above approachusing System; class GFG{ // Function to return the lexicographically// smallest String that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.static String findSmallest(char []s){ int len = s.Length; // Store last occurrence of every character int []loccur = new int[26]; // Set -1 as default for every character. for (int i = 0; i < 26; i++) loccur[i] = -1; for (int i = len - 1; i >= 0; --i) { // char index to fill // in the last occurrence array int chI = s[i] - 'a'; if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } char []sorted_s = s; Array.Sort(sorted_s); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // char to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character. int last_occ = loccur[chI]; // Swap this with the last occurrence char temp = s[last_occ]; s[last_occ] = s[i]; s[i] = temp; break; } } return String.Join("", s);} // Driver codepublic static void Main(String[] args){ String s = "geeks"; Console.Write(findSmallest(s.ToCharArray()));}} // This code is contributed by sapnasingh4991 <script> // Javascript implementation of the above approach // Function to return the lexicographically// smallest string that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.function findSmallest(s){ let len = s.length; // Store last occurrence of every character let loccur = new Array(26); // Set -1 as default for every character. loccur.fill(-1); for(let i = len - 1; i >= 0; --i) { // Character index to fill // in the last occurrence array let chI = s[i].charCodeAt() - 'a'.charCodeAt(); if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } let sorted_s = s; sorted_s.sort(); for(let i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace let chI = sorted_s[i].charCodeAt() - 'a'.charCodeAt(); // Find the last occurrence // of this character. let last_occ = loccur[chI]; // Swap this with the last occurrence let temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return s.join("");} // Driver codelet s = "geeks"; document.write(findSmallest(s.split(''))); // This code is contributed by vaibhavrabadiya3 </script> eegks Time Complexity: O(N*log(N))Auxiliary Space: O(1) Yash_R 29AjayKumar sapnasingh4991 vaibhavrabadiya3 pankajsharmagfg ashutoshsinghgeeksforgeeks pushpeshrajdx01 Algorithms Greedy Searching Sorting Strings Searching Strings Greedy Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial CPU Scheduling in Operating Systems Understanding Time Complexity with Simple Examples Dijkstra's shortest path algorithm | Greedy Algo-7 Program for array rotation Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jun, 2022" }, { "code": null, "e": 301, "s": 54, "text": "Given a string str of length N. The task is to find out the lexicographically smallest string when at most only one swap is allowed. That is, two indices 1 <= i, j <= n can be chosen and swapped. This operation can be performed at most one time. " }, { "code": null, "e": 312, "s": 301, "text": "Examples: " }, { "code": null, "e": 467, "s": 312, "text": "Input: str = “string” Output: gtrins Explanation: Choose i=1, j=6, string becomes – gtrins. This is lexicographically smallest strings that can be formed." }, { "code": null, "e": 501, "s": 467, "text": "Input: str = “zyxw” Output: wyxz " }, { "code": null, "e": 799, "s": 501, "text": "Approach: The idea is to use sorting and compute the smallest lexicographical string possible for the given string. After computing the sorted string, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string. " }, { "code": null, "e": 1153, "s": 799, "text": "For example, let str = “geeks” and the sorted = “eegks”. First unmatched character is in the first place. This character has to swapped such that this character matches the character with sorted string. Resulting lexicographical smallest string. On replacing “g” with the last occurring “e”, the string becomes eegks which is lexicographically smallest." }, { "code": null, "e": 1205, "s": 1153, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1209, "s": 1205, "text": "C++" }, { "code": null, "e": 1214, "s": 1209, "text": "Java" }, { "code": null, "e": 1222, "s": 1214, "text": "Python3" }, { "code": null, "e": 1225, "s": 1222, "text": "C#" }, { "code": null, "e": 1236, "s": 1225, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the lexicographically// smallest string that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.string findSmallest(string s){ int len = s.size(); // Store last occurrence of every character // and set -1 as default for every character. vector<int> loccur(26,-1); for (int i = len - 1; i >= 0; --i) { // Character index to fill // in the last occurrence array int chI = s[i] - 'a'; if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } string sorted_s = s; sort(sorted_s.begin(), sorted_s.end()); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character. int last_occ = loccur[chI]; // Swap this with the last occurrence swap(s[i], s[last_occ]); break; } } return s;} // Driver codeint main(){ string s = \"geeks\"; cout << findSmallest(s); return 0;}", "e": 2667, "s": 1236, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to return the lexicographically// smallest String that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.static String findSmallest(char []s){ int len = s.length; // Store last occurrence of every character int []loccur = new int[26]; // Set -1 as default for every character. Arrays.fill(loccur, -1); for (int i = len - 1; i >= 0; --i) { // Character index to fill // in the last occurrence array int chI = s[i] - 'a'; if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } char []sorted_s = s; Arrays.sort(sorted_s); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character. int last_occ = loccur[chI]; // Swap this with the last occurrence char temp = s[last_occ]; s[last_occ] = s[i]; s[i] = temp; break; } } return String.valueOf(s);} // Driver codepublic static void main(String[] args){ String s = \"geeks\"; System.out.print(findSmallest(s.toCharArray()));}} // This code is contributed by 29AjayKumar", "e": 4265, "s": 2667, "text": null }, { "code": "# Python3 implementation of the above approach # Function to return the lexicographically# smallest string that can be formed by# swapping at most one character.# The characters might not necessarily# be adjacent.def findSmallest(s) : length = len(s); # Store last occurrence of every character # Set -1 as default for every character. loccur = [-1]*26; for i in range(length - 1, -1, -1) : # Character index to fill # in the last occurrence array chI = ord(s[i]) - ord('a'); if (loccur[chI] == -1) : # If this is true then this # character is being visited # for the first time from the last # Thus last occurrence of this # character is stored in this index loccur[chI] = i; sorted_s = s; sorted_s.sort(); for i in range(length) : if (s[i] != sorted_s[i]) : # Character to replace chI = ord(sorted_s[i]) - ord('a'); # Find the last occurrence # of this character. last_occ = loccur[chI]; # Swap this with the last occurrence # swap(s[i], s[last_occ]); s[i],s[last_occ] = s[last_occ],s[i] break; return \"\".join(s); # Driver codeif __name__ == \"__main__\" : s = \"geeks\"; print(findSmallest(list(s))); # This code is contributed by Yash_R", "e": 5653, "s": 4265, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the lexicographically// smallest String that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.static String findSmallest(char []s){ int len = s.Length; // Store last occurrence of every character int []loccur = new int[26]; // Set -1 as default for every character. for (int i = 0; i < 26; i++) loccur[i] = -1; for (int i = len - 1; i >= 0; --i) { // char index to fill // in the last occurrence array int chI = s[i] - 'a'; if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } char []sorted_s = s; Array.Sort(sorted_s); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // char to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character. int last_occ = loccur[chI]; // Swap this with the last occurrence char temp = s[last_occ]; s[last_occ] = s[i]; s[i] = temp; break; } } return String.Join(\"\", s);} // Driver codepublic static void Main(String[] args){ String s = \"geeks\"; Console.Write(findSmallest(s.ToCharArray()));}} // This code is contributed by sapnasingh4991", "e": 7273, "s": 5653, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to return the lexicographically// smallest string that can be formed by// swapping at most one character.// The characters might not necessarily// be adjacent.function findSmallest(s){ let len = s.length; // Store last occurrence of every character let loccur = new Array(26); // Set -1 as default for every character. loccur.fill(-1); for(let i = len - 1; i >= 0; --i) { // Character index to fill // in the last occurrence array let chI = s[i].charCodeAt() - 'a'.charCodeAt(); if (loccur[chI] == -1) { // If this is true then this // character is being visited // for the first time from the last // Thus last occurrence of this // character is stored in this index loccur[chI] = i; } } let sorted_s = s; sorted_s.sort(); for(let i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace let chI = sorted_s[i].charCodeAt() - 'a'.charCodeAt(); // Find the last occurrence // of this character. let last_occ = loccur[chI]; // Swap this with the last occurrence let temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return s.join(\"\");} // Driver codelet s = \"geeks\"; document.write(findSmallest(s.split(''))); // This code is contributed by vaibhavrabadiya3 </script>", "e": 8912, "s": 7273, "text": null }, { "code": null, "e": 8918, "s": 8912, "text": "eegks" }, { "code": null, "e": 8970, "s": 8920, "text": "Time Complexity: O(N*log(N))Auxiliary Space: O(1)" }, { "code": null, "e": 8977, "s": 8970, "text": "Yash_R" }, { "code": null, "e": 8989, "s": 8977, "text": "29AjayKumar" }, { "code": null, "e": 9004, "s": 8989, "text": "sapnasingh4991" }, { "code": null, "e": 9021, "s": 9004, "text": "vaibhavrabadiya3" }, { "code": null, "e": 9037, "s": 9021, "text": "pankajsharmagfg" }, { "code": null, "e": 9064, "s": 9037, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 9080, "s": 9064, "text": "pushpeshrajdx01" }, { "code": null, "e": 9091, "s": 9080, "text": "Algorithms" }, { "code": null, "e": 9098, "s": 9091, "text": "Greedy" }, { "code": null, "e": 9108, "s": 9098, "text": "Searching" }, { "code": null, "e": 9116, "s": 9108, "text": "Sorting" }, { "code": null, "e": 9124, "s": 9116, "text": "Strings" }, { "code": null, "e": 9134, "s": 9124, "text": "Searching" }, { "code": null, "e": 9142, "s": 9134, "text": "Strings" }, { "code": null, "e": 9149, "s": 9142, "text": "Greedy" }, { "code": null, "e": 9157, "s": 9149, "text": "Sorting" }, { "code": null, "e": 9168, "s": 9157, "text": "Algorithms" }, { "code": null, "e": 9266, "s": 9168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9291, "s": 9266, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 9340, "s": 9291, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 9378, "s": 9340, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9414, "s": 9378, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 9465, "s": 9414, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 9516, "s": 9465, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 9543, "s": 9516, "text": "Program for array rotation" }, { "code": null, "e": 9594, "s": 9543, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 9654, "s": 9594, "text": "Write a program to print all permutations of a given string" } ]
Managing Themes in ElectronJS
28 Jun, 2022 ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. To make desktop applications more attractive and engaging for the users, developers in addition to using CSS should also develop the application to make it compatible with the native System Theme. The application should provide a feature wherein the user can control the look and feel of the application and change the theme dynamically during runtime. This enhances the UI of the application and makes it blend in with the System environment. Electron provides a way by which we can achieve this using the Instance properties and events of the built-in nativeTheme module. This tutorial will demonstrate how to use the nativeTheme module. Any additional CSS should only be applied over the native System theme for Styling the application. We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Project Structure: Example: Follow the Steps given in Dynamic Styling in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. package.json: { "name": "electron-theme", "version": "1.0.0", "description": "Themes in Electron", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "electron" ], "author": "Radhesh Khanna", "license": "ISC", "dependencies": { "electron": "^8.3.0" } } Create the assets folder according to the project structure and create the light.css file and dark.css file respectively. We will be injecting these CSS files into the application dynamically during execution. Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. Native Theme in Electron: The nativeTheme module is used to read, respond and apply changes to the Chromium’s native color Theme. The native System Theme applies to the Chromium’s native color theme as well. This module is part of the Main Process. To import and use nativeTheme module in the Renderer Process, we will be using Electron remote module. Note: The nativeTheme module supports only Instance Events and Instance Properties. It does have any Instance methods associated with it. index.html: The Enable Dark Theme and Enable Light Theme buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file. HTML <br><br> <button id="dark"> Enable Dark Theme </button> <button id="light"> Enable Light Theme </button> index.js: Add the following snippet in that file. Javascript const electron = require("electron"); // Importing the nativeTheme module// using Electron remoteconst nativeTheme = electron.remote.nativeTheme;const path = require("path"); console.log("By Default, Dark Theme Enabled - ", nativeTheme.shouldUseDarkColors);console.log("High Contrast Colors - ", nativeTheme.shouldUseHighContrastColors);console.log("Inverted Colors - ", nativeTheme.shouldUseInvertedColorScheme); nativeTheme.on("updated", () => { console.log("Updated Event has been Emitted"); if (nativeTheme.shouldUseDarkColors) { console.log("Dark Theme Chosen by User"); } else { console.log("Light Theme Chosen by User"); }}); var dark = document.getElementById("dark");dark.addEventListener("click", () => { nativeTheme.themeSource = "dark";}); var light = document.getElementById("light");light.addEventListener("click", () => { nativeTheme.themeSource = "light";}); A detailed explanation of all the Instance Properties of the nativeTheme module used in the code are given below: nativeTheme.shouldUseDarkColors This Instance property is a Readonly Property. This property returns a Boolean value stating whether the System OS or Chromium currently has a dark mode enabled or it is being instructed to show a dark themed UI. To modify this property (change the theme of application), we need use the nativeTheme.themeSource Instance property. nativeTheme.shouldUseHighContrastColors This Instance property is a Readonly Property. This Instance property is supported on Windows and macOS only. This property returns a Boolean value stating whether the System OS or Chromium currently has a high-contrast mode enabled or it is being instructed to show a high-contrast themed UI. This property cannot be directly modified from code using the nativeTheme module. To modify this property, the user needs to enable high-contrast UI from within System Settings. nativeTheme.shouldUseInvertedColorScheme This Instance property is a Readonly Property. This Instance property is supported on Windows and macOS only. This property returns a Boolean value stating whether the System OS or Chromium currently has an inverted color scheme enabled or it is being instructed to use an inverted color scheme in the UI. This property cannot be directly modified from code using the nativeTheme module. To modify this property, the user needs to enable inverted color scheme from within System Settings. nativeTheme.themeSource This Instance property is used to change the theme of the application. This property can be changed dynamically during execution. This String property is used to Override and supersede the value (specifying the theme) which Chromium has chosen to use internally in accordance to the System Theme. This Property can take one of the following String values:system Setting this Instance property to system will remove the override values and will reset everything to OS default. This means that if the System theme has dark mode enabled, then chromium will automatically take this as its default theme and will apply it to the Electron application. The same case is also applicable when the System theme has light mode enabled. By default, the value of the themeSource property is system. This value aligns with the Default OS mode of the System.dark Setting this Instance Property to dark will have the following effects on the application. This value aligns with the Dark mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to true.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the dark themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the dark themed UI.The prefers-color-scheme CSS query will match dark mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output.light Setting this Instance property to light will have the following effects on the application. This value aligns with the Light mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to false.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the light themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the light themed UI.The prefers-color-scheme CSS query will match light mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output. system Setting this Instance property to system will remove the override values and will reset everything to OS default. This means that if the System theme has dark mode enabled, then chromium will automatically take this as its default theme and will apply it to the Electron application. The same case is also applicable when the System theme has light mode enabled. By default, the value of the themeSource property is system. This value aligns with the Default OS mode of the System. dark Setting this Instance Property to dark will have the following effects on the application. This value aligns with the Dark mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to true.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the dark themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the dark themed UI.The prefers-color-scheme CSS query will match dark mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output. The nativeTheme.shouldUseDarkColors Instance property will be set to true. Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the dark themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the dark themed UI. The prefers-color-scheme CSS query will match dark mode. The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output. light Setting this Instance property to light will have the following effects on the application. This value aligns with the Light mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to false.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the light themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the light themed UI.The prefers-color-scheme CSS query will match light mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output. The nativeTheme.shouldUseDarkColors Instance property will be set to false. Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the light themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the light themed UI. The prefers-color-scheme CSS query will match light mode. The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output. A detailed Explanation of the Instance Event of the nativeTheme module used in the code is given below: updated: Event This Instance Event is emitted when some property in the underlying native Chromium Theme has been changed. This means that the value of any of the Readonly Instance property has changed. As discussed above, the value of nativeTheme.shouldUseDarkColors property can be changed by changing the value of nativeTheme.themeSource property. After this Event is emitted, we need to manually check which Readonly property has changed as described above since this Instance event does not return any Promise/Callback. At this point, we should successfully be able to determine and change the Native Theme of the Electron application from the above code. Output: Note: In the above output, the System OS theme is set to dark mode by default and hence the nativeTheme.shouldUseDarkColors Instance property returns true. Also, upon reloading the application, any changes made to the theme will be reverted back to the default System OS theme since we are not persisting the value of nativeTheme.themeSource Instance property within the local storage of the application. After we have made the application successfully adapt to the native System Theme, we need to dynamically apply the respective CSS which is compatible with that theme for the application. This is important because some properties of styling cannot be applied to both themes. For example, we cannot use the same font-color for dark mode as well as for light mode. The following tutorial will demonstrate how to dynamically inject the respective CSS based on the theme applied. dark.css: Add the following snippet in that file. body { background-color: darkgray; color: white; } light.css: Add the following snippet in that file. body { background-color: lightgray; color: black; } index.js: Make the following changes to this file. The function loadCSS(load) dynamically inserts CSS into the HTML DOM structure based on the light or dark String value passed to it. We are simply appending another link tag with the respective CSS file and properties to the head tag of the index.html document using the appendChild method. Javascript const electron = require("electron"); // Importing the nativeTheme module// using Electron remoteconst nativeTheme = electron.remote.nativeTheme;const path = require("path"); console.log("By Default, Dark Theme Enabled - ", nativeTheme.shouldUseDarkColors);console.log("High Contrast Colors - ", nativeTheme.shouldUseHighContrastColors);console.log("Inverted Colors - ", nativeTheme.shouldUseInvertedColorScheme); function loadCSS(load) { var head = document.getElementsByTagName("head")[0]; var link = document.createElement("link"); link.rel = "stylesheet"; link.type = "text/css"; link.href = path.join(__dirname, "../assets/" + load + ".css"); head.appendChild(link);} nativeTheme.on("updated", () => { console.log("Updated Event has been Emitted"); if (nativeTheme.shouldUseDarkColors) { console.log("Dark Theme Chosen by User"); console.log("Dark Theme Enabled - ", nativeTheme.shouldUseDarkColors); loadCSS("dark"); } else { console.log("Light Theme Chosen by User"); console.log("Dark Theme Enabled - ", nativeTheme.shouldUseDarkColors); loadCSS("light"); }}); var dark = document.getElementById("dark");dark.addEventListener("click", () => { nativeTheme.themeSource = "dark";}); var light = document.getElementById("light");light.addEventListener("click", () => { nativeTheme.themeSource = "light";}); Output: When dynamically specifying the CSS file, we are not removing the previous CSS file, if any and hence styling applied to the Application is inclusive of both the CSS files. In case, we miss a property in any one of the CSS files, it will still be applied to the application upon changing the theme. Hence we can either remove the link tag first and then re-append it dynamically using JS or override all the properties of the previous CSS file, by making identical copies and simply changing the values. radheshkhanna simranarora5sos simmytarika5 ElectronJS CSS HTML JavaScript Node.js 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": "\n28 Jun, 2022" }, { "code": null, "e": 328, "s": 28, "text": "ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime." }, { "code": null, "e": 1069, "s": 328, "text": "To make desktop applications more attractive and engaging for the users, developers in addition to using CSS should also develop the application to make it compatible with the native System Theme. The application should provide a feature wherein the user can control the look and feel of the application and change the theme dynamically during runtime. This enhances the UI of the application and makes it blend in with the System environment. Electron provides a way by which we can achieve this using the Instance properties and events of the built-in nativeTheme module. This tutorial will demonstrate how to use the nativeTheme module. Any additional CSS should only be applied over the native System theme for Styling the application. " }, { "code": null, "e": 1239, "s": 1069, "text": "We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system." }, { "code": null, "e": 1258, "s": 1239, "text": "Project Structure:" }, { "code": null, "e": 1639, "s": 1258, "text": "Example: Follow the Steps given in Dynamic Styling in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. " }, { "code": null, "e": 1654, "s": 1639, "text": "package.json: " }, { "code": null, "e": 1949, "s": 1654, "text": "{\n \"name\": \"electron-theme\",\n \"version\": \"1.0.0\",\n \"description\": \"Themes in Electron\",\n \"main\": \"main.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"keywords\": [\n \"electron\"\n ],\n \"author\": \"Radhesh Khanna\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^8.3.0\"\n }\n}" }, { "code": null, "e": 2159, "s": 1949, "text": "Create the assets folder according to the project structure and create the light.css file and dark.css file respectively. We will be injecting these CSS files into the application dynamically during execution." }, { "code": null, "e": 2292, "s": 2159, "text": "Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result." }, { "code": null, "e": 2645, "s": 2292, "text": "Native Theme in Electron: The nativeTheme module is used to read, respond and apply changes to the Chromium’s native color Theme. The native System Theme applies to the Chromium’s native color theme as well. This module is part of the Main Process. To import and use nativeTheme module in the Renderer Process, we will be using Electron remote module. " }, { "code": null, "e": 2783, "s": 2645, "text": "Note: The nativeTheme module supports only Instance Events and Instance Properties. It does have any Instance methods associated with it." }, { "code": null, "e": 2965, "s": 2783, "text": "index.html: The Enable Dark Theme and Enable Light Theme buttons do not have any functionality associated with them yet. To change this, add the following code in the index.js file." }, { "code": null, "e": 2970, "s": 2965, "text": "HTML" }, { "code": "<br><br> <button id=\"dark\"> Enable Dark Theme </button> <button id=\"light\"> Enable Light Theme </button>", "e": 3091, "s": 2970, "text": null }, { "code": null, "e": 3143, "s": 3091, "text": "index.js: Add the following snippet in that file. " }, { "code": null, "e": 3154, "s": 3143, "text": "Javascript" }, { "code": "const electron = require(\"electron\"); // Importing the nativeTheme module// using Electron remoteconst nativeTheme = electron.remote.nativeTheme;const path = require(\"path\"); console.log(\"By Default, Dark Theme Enabled - \", nativeTheme.shouldUseDarkColors);console.log(\"High Contrast Colors - \", nativeTheme.shouldUseHighContrastColors);console.log(\"Inverted Colors - \", nativeTheme.shouldUseInvertedColorScheme); nativeTheme.on(\"updated\", () => { console.log(\"Updated Event has been Emitted\"); if (nativeTheme.shouldUseDarkColors) { console.log(\"Dark Theme Chosen by User\"); } else { console.log(\"Light Theme Chosen by User\"); }}); var dark = document.getElementById(\"dark\");dark.addEventListener(\"click\", () => { nativeTheme.themeSource = \"dark\";}); var light = document.getElementById(\"light\");light.addEventListener(\"click\", () => { nativeTheme.themeSource = \"light\";});", "e": 4095, "s": 3154, "text": null }, { "code": null, "e": 4212, "s": 4095, "text": " A detailed explanation of all the Instance Properties of the nativeTheme module used in the code are given below: " }, { "code": null, "e": 4575, "s": 4212, "text": "nativeTheme.shouldUseDarkColors This Instance property is a Readonly Property. This property returns a Boolean value stating whether the System OS or Chromium currently has a dark mode enabled or it is being instructed to show a dark themed UI. To modify this property (change the theme of application), we need use the nativeTheme.themeSource Instance property." }, { "code": null, "e": 5087, "s": 4575, "text": "nativeTheme.shouldUseHighContrastColors This Instance property is a Readonly Property. This Instance property is supported on Windows and macOS only. This property returns a Boolean value stating whether the System OS or Chromium currently has a high-contrast mode enabled or it is being instructed to show a high-contrast themed UI. This property cannot be directly modified from code using the nativeTheme module. To modify this property, the user needs to enable high-contrast UI from within System Settings." }, { "code": null, "e": 5617, "s": 5087, "text": "nativeTheme.shouldUseInvertedColorScheme This Instance property is a Readonly Property. This Instance property is supported on Windows and macOS only. This property returns a Boolean value stating whether the System OS or Chromium currently has an inverted color scheme enabled or it is being instructed to use an inverted color scheme in the UI. This property cannot be directly modified from code using the nativeTheme module. To modify this property, the user needs to enable inverted color scheme from within System Settings." }, { "code": null, "e": 7818, "s": 5617, "text": "nativeTheme.themeSource This Instance property is used to change the theme of the application. This property can be changed dynamically during execution. This String property is used to Override and supersede the value (specifying the theme) which Chromium has chosen to use internally in accordance to the System Theme. This Property can take one of the following String values:system Setting this Instance property to system will remove the override values and will reset everything to OS default. This means that if the System theme has dark mode enabled, then chromium will automatically take this as its default theme and will apply it to the Electron application. The same case is also applicable when the System theme has light mode enabled. By default, the value of the themeSource property is system. This value aligns with the Default OS mode of the System.dark Setting this Instance Property to dark will have the following effects on the application. This value aligns with the Dark mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to true.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the dark themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the dark themed UI.The prefers-color-scheme CSS query will match dark mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output.light Setting this Instance property to light will have the following effects on the application. This value aligns with the Light mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to false.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the light themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the light themed UI.The prefers-color-scheme CSS query will match light mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output." }, { "code": null, "e": 8307, "s": 7818, "text": "system Setting this Instance property to system will remove the override values and will reset everything to OS default. This means that if the System theme has dark mode enabled, then chromium will automatically take this as its default theme and will apply it to the Electron application. The same case is also applicable when the System theme has light mode enabled. By default, the value of the themeSource property is system. This value aligns with the Default OS mode of the System." }, { "code": null, "e": 8971, "s": 8307, "text": "dark Setting this Instance Property to dark will have the following effects on the application. This value aligns with the Dark mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to true.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the dark themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the dark themed UI.The prefers-color-scheme CSS query will match dark mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output." }, { "code": null, "e": 9046, "s": 8971, "text": "The nativeTheme.shouldUseDarkColors Instance property will be set to true." }, { "code": null, "e": 9329, "s": 9046, "text": "Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the dark themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the dark themed UI." }, { "code": null, "e": 9386, "s": 9329, "text": "The prefers-color-scheme CSS query will match dark mode." }, { "code": null, "e": 9491, "s": 9386, "text": "The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output." }, { "code": null, "e": 10162, "s": 9491, "text": "light Setting this Instance property to light will have the following effects on the application. This value aligns with the Light mode of the System.The nativeTheme.shouldUseDarkColors Instance property will be set to false.Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the light themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the light themed UI.The prefers-color-scheme CSS query will match light mode.The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output." }, { "code": null, "e": 10238, "s": 10162, "text": "The nativeTheme.shouldUseDarkColors Instance property will be set to false." }, { "code": null, "e": 10523, "s": 10238, "text": "Any UI rendered by the Electron application on Linux and Windows including context-menus, devTools, etc will use the light themed UI. The same has been demonstrated in the Output. Any UI rendered by the System on macOS including menus, window frames, etc will use the light themed UI." }, { "code": null, "e": 10581, "s": 10523, "text": "The prefers-color-scheme CSS query will match light mode." }, { "code": null, "e": 10686, "s": 10581, "text": "The Updated Instance event will be Emitted as shown in the code. The same is demonstrated in the Output." }, { "code": null, "e": 10791, "s": 10686, "text": "A detailed Explanation of the Instance Event of the nativeTheme module used in the code is given below: " }, { "code": null, "e": 11316, "s": 10791, "text": "updated: Event This Instance Event is emitted when some property in the underlying native Chromium Theme has been changed. This means that the value of any of the Readonly Instance property has changed. As discussed above, the value of nativeTheme.shouldUseDarkColors property can be changed by changing the value of nativeTheme.themeSource property. After this Event is emitted, we need to manually check which Readonly property has changed as described above since this Instance event does not return any Promise/Callback." }, { "code": null, "e": 11453, "s": 11316, "text": "At this point, we should successfully be able to determine and change the Native Theme of the Electron application from the above code. " }, { "code": null, "e": 11462, "s": 11453, "text": "Output: " }, { "code": null, "e": 11867, "s": 11462, "text": "Note: In the above output, the System OS theme is set to dark mode by default and hence the nativeTheme.shouldUseDarkColors Instance property returns true. Also, upon reloading the application, any changes made to the theme will be reverted back to the default System OS theme since we are not persisting the value of nativeTheme.themeSource Instance property within the local storage of the application." }, { "code": null, "e": 12343, "s": 11867, "text": "After we have made the application successfully adapt to the native System Theme, we need to dynamically apply the respective CSS which is compatible with that theme for the application. This is important because some properties of styling cannot be applied to both themes. For example, we cannot use the same font-color for dark mode as well as for light mode. The following tutorial will demonstrate how to dynamically inject the respective CSS based on the theme applied. " }, { "code": null, "e": 12393, "s": 12343, "text": "dark.css: Add the following snippet in that file." }, { "code": null, "e": 12452, "s": 12393, "text": "body {\n background-color: darkgray;\n color: white;\n}" }, { "code": null, "e": 12503, "s": 12452, "text": "light.css: Add the following snippet in that file." }, { "code": null, "e": 12563, "s": 12503, "text": "body {\n background-color: lightgray;\n color: black;\n}" }, { "code": null, "e": 12906, "s": 12563, "text": "index.js: Make the following changes to this file. The function loadCSS(load) dynamically inserts CSS into the HTML DOM structure based on the light or dark String value passed to it. We are simply appending another link tag with the respective CSS file and properties to the head tag of the index.html document using the appendChild method. " }, { "code": null, "e": 12917, "s": 12906, "text": "Javascript" }, { "code": "const electron = require(\"electron\"); // Importing the nativeTheme module// using Electron remoteconst nativeTheme = electron.remote.nativeTheme;const path = require(\"path\"); console.log(\"By Default, Dark Theme Enabled - \", nativeTheme.shouldUseDarkColors);console.log(\"High Contrast Colors - \", nativeTheme.shouldUseHighContrastColors);console.log(\"Inverted Colors - \", nativeTheme.shouldUseInvertedColorScheme); function loadCSS(load) { var head = document.getElementsByTagName(\"head\")[0]; var link = document.createElement(\"link\"); link.rel = \"stylesheet\"; link.type = \"text/css\"; link.href = path.join(__dirname, \"../assets/\" + load + \".css\"); head.appendChild(link);} nativeTheme.on(\"updated\", () => { console.log(\"Updated Event has been Emitted\"); if (nativeTheme.shouldUseDarkColors) { console.log(\"Dark Theme Chosen by User\"); console.log(\"Dark Theme Enabled - \", nativeTheme.shouldUseDarkColors); loadCSS(\"dark\"); } else { console.log(\"Light Theme Chosen by User\"); console.log(\"Dark Theme Enabled - \", nativeTheme.shouldUseDarkColors); loadCSS(\"light\"); }}); var dark = document.getElementById(\"dark\");dark.addEventListener(\"click\", () => { nativeTheme.themeSource = \"dark\";}); var light = document.getElementById(\"light\");light.addEventListener(\"click\", () => { nativeTheme.themeSource = \"light\";});", "e": 14405, "s": 12917, "text": null }, { "code": null, "e": 14918, "s": 14405, "text": "Output: When dynamically specifying the CSS file, we are not removing the previous CSS file, if any and hence styling applied to the Application is inclusive of both the CSS files. In case, we miss a property in any one of the CSS files, it will still be applied to the application upon changing the theme. Hence we can either remove the link tag first and then re-append it dynamically using JS or override all the properties of the previous CSS file, by making identical copies and simply changing the values. " }, { "code": null, "e": 14938, "s": 14924, "text": "radheshkhanna" }, { "code": null, "e": 14954, "s": 14938, "text": "simranarora5sos" }, { "code": null, "e": 14967, "s": 14954, "text": "simmytarika5" }, { "code": null, "e": 14978, "s": 14967, "text": "ElectronJS" }, { "code": null, "e": 14982, "s": 14978, "text": "CSS" }, { "code": null, "e": 14987, "s": 14982, "text": "HTML" }, { "code": null, "e": 14998, "s": 14987, "text": "JavaScript" }, { "code": null, "e": 15006, "s": 14998, "text": "Node.js" }, { "code": null, "e": 15023, "s": 15006, "text": "Web Technologies" }, { "code": null, "e": 15028, "s": 15023, "text": "HTML" } ]
Perl | push() Function
25 Jun, 2019 push() function in Perl is used to push a list of values onto the end of the array. push() function is often used with pop to implement stacks. push() function doesn’t depend on the type of values passed as list. These values can be alpha-numeric. Syntax: push(Array, List) Parameter:Array: in which list of values is to be addedList: which is to be added using push function Returns:the number of elements in new array. Example 1: #!/usr/bin/perl -w # Original Array@array = ( 10, 20, 30 ); # Printing Array elementsprint "Original Array: @array \n"; # Calling push function to # add a list of elementspush(@array, (35, 40, 55)); # Printing Updated array elementsprint "Updated Array: @array \n"; Output: Original Array: 10 20 30 Updated Array: 10 20 30 35 40 55 Example 2: #!/usr/bin/perl -w # Original Array@array = ( 10, A, 30 ); # Printing Array elementsprint "Original Array: @array \n"; # Calling push function to # add a list of elementspush(@array, (F, G, H)); # Printing Updated array elementsprint "Updated Array: @array \n"; Output: Original Array: 10 A 30 Updated Array: 10 A 30 F G H Perl-Array-Functions Perl-function Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Polymorphism in OOPs Perl | Boolean Values Perl | length() Function Perl | Subroutines or Functions Hello World Program in Perl Perl | ne operator Use of print() and say() in Perl Perl | Basic Syntax of a Perl Program Perl | eq operator
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 276, "s": 28, "text": "push() function in Perl is used to push a list of values onto the end of the array. push() function is often used with pop to implement stacks. push() function doesn’t depend on the type of values passed as list. These values can be alpha-numeric." }, { "code": null, "e": 302, "s": 276, "text": "Syntax: push(Array, List)" }, { "code": null, "e": 404, "s": 302, "text": "Parameter:Array: in which list of values is to be addedList: which is to be added using push function" }, { "code": null, "e": 449, "s": 404, "text": "Returns:the number of elements in new array." }, { "code": null, "e": 460, "s": 449, "text": "Example 1:" }, { "code": "#!/usr/bin/perl -w # Original Array@array = ( 10, 20, 30 ); # Printing Array elementsprint \"Original Array: @array \\n\"; # Calling push function to # add a list of elementspush(@array, (35, 40, 55)); # Printing Updated array elementsprint \"Updated Array: @array \\n\";", "e": 730, "s": 460, "text": null }, { "code": null, "e": 738, "s": 730, "text": "Output:" }, { "code": null, "e": 799, "s": 738, "text": "Original Array: 10 20 30 \nUpdated Array: 10 20 30 35 40 55 \n" }, { "code": null, "e": 811, "s": 799, "text": " Example 2:" }, { "code": "#!/usr/bin/perl -w # Original Array@array = ( 10, A, 30 ); # Printing Array elementsprint \"Original Array: @array \\n\"; # Calling push function to # add a list of elementspush(@array, (F, G, H)); # Printing Updated array elementsprint \"Updated Array: @array \\n\";", "e": 1077, "s": 811, "text": null }, { "code": null, "e": 1085, "s": 1077, "text": "Output:" }, { "code": null, "e": 1141, "s": 1085, "text": "Original Array: 10 A 30 \nUpdated Array: 10 A 30 F G H \n" }, { "code": null, "e": 1162, "s": 1141, "text": "Perl-Array-Functions" }, { "code": null, "e": 1176, "s": 1162, "text": "Perl-function" }, { "code": null, "e": 1181, "s": 1176, "text": "Perl" }, { "code": null, "e": 1186, "s": 1181, "text": "Perl" }, { "code": null, "e": 1284, "s": 1186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1325, "s": 1284, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 1353, "s": 1325, "text": "Perl | Polymorphism in OOPs" }, { "code": null, "e": 1375, "s": 1353, "text": "Perl | Boolean Values" }, { "code": null, "e": 1400, "s": 1375, "text": "Perl | length() Function" }, { "code": null, "e": 1432, "s": 1400, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 1460, "s": 1432, "text": "Hello World Program in Perl" }, { "code": null, "e": 1479, "s": 1460, "text": "Perl | ne operator" }, { "code": null, "e": 1512, "s": 1479, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 1550, "s": 1512, "text": "Perl | Basic Syntax of a Perl Program" } ]
How to search and replace text in a file in Python ?
14 Sep, 2021 In this article, we will learn how we can replace text in a file using python. Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents: To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions. Syntax: open(file, mode=’r’) Parameters: file : Location of the file mode : Mode in which you want toopen the file. Then we will open the same file in write mode to write the replaced content. Python3 # creating a variable and storing the text# that we want to searchsearch_text = "dummy" # creating a variable and storing the text# that we want to addreplace_text = "replaced" # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt', 'r') as file: # Reading the content of the file # using the read() function and storing # them in a new variable data = file.read() # Searching and replacing the text # using the replace() function data = data.replace(search_text, replace_text) # Opening our text file in write only# mode to write the replaced contentwith open(r'SampleFile.txt', 'w') as file: # Writing the replaced data in our # text file file.write(data) # Printing Text replacedprint("Text replaced") Output: Text replaced Let see how we can search and replace text using the pathlib2 module. First, we create a Text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents: Install pathlib2 module using the below command: pip install pathlib2 This module offers classes representing filesystem paths with semantics appropriate for different operating systems. To replace the text using pathlib2 module we will use the Path method of pathlib2 module. Syntax: Path(file) Parameters: file: Location of the file you want to open In the below code we are replacing “dummy” with “replaced” in our text file. using the pathlib2 module. Code: Python3 # Importing Path from pathlib2 modulefrom pathlib2 import Path # Creating a function to# replace the textdef replacetext(search_text, replace_text): # Opening the file using the Path function file = Path(r"SampleFile.txt") # Reading and storing the content of the file in # a data variable data = file.read_text() # Replacing the text using the replace function data = data.replace(search_text, replace_text) # Writing the replaced data # in the text file file.write_text(data) # Return "Text replaced" string return "Text replaced" # Creating a variable and storing# the text that we want to searchsearch_text = "dummy" # Creating a variable and storing# the text that we want to updatereplace_text = "replaced" # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text, replace_text)) Output: Text replaced Let see how we can search and replace text using the regex module. We are going to use the re.sub( ) method to replace the text. Syntax: re.sub(pattern, repl, string, count=0, flags=0) Parameters: repl : Text you want to add string : Text you want to replace Code: Python3 # Importing re moduleimport re # Creating a function to# replace the textdef replacetext(search_text,replace_text): # Opening the file in read and write mode with open('SampleFile.txt','r+') as f: # Reading the file data and store # it in a file variable file = f.read() # Replacing the pattern with the string # in the file data file = re.sub(search_text, replace_text, file) # Setting the position to the top # of the page to insert data f.seek(0) # Writing replaced data in the file f.write(file) # Truncating the file size f.truncate() # Return "Text replaced" string return "Text replaced" # Creating a variable and storing# the text that we want to searchsearch_text = "dummy" #Creating a variable and storing# the text that we want to updatereplace_text = "replaced" # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text,replace_text)) Output: Text replaced Let see how we can search and replace text using the fileinput module. For this, we will use FileInput() method to iterate over the data of the file and replace the text. Syntax: FileInput(files=None, inplace=False, backup=”, *, mode=’r’) Parameters: files : Location of the text file mode : Mode in which you want toopen the file inplace : If value is True then the file is moved to a backup file and standard output is directed to the input file backup : Extension for the backup file Code: Python3 # Importing FileInput from fileinput modulefrom fileinput import FileInput # Creating a function to# replace the textdef replacetext(search_text, replace_text): # Opening file using FileInput with FileInput("SampleFile.txt", inplace=True, backup='.bak') as f: # Iterating over every and changing # the search_text with replace_text # using the replace function for line in f: print(line.replace(search_text, replace_text), end='') # Return "Text replaced" string return "Text replaced" # Creating a variable and storing# the text that we want to searchsearch_text = "dummy" # Creating a variable and storing# the text that we want to updatereplace_text = "replaced" # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text, replace_text)) Output: Text replaced Picked Python file-handling-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Sep, 2021" }, { "code": null, "e": 131, "s": 52, "text": "In this article, we will learn how we can replace text in a file using python." }, { "code": null, "e": 325, "s": 131, "text": "Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:" }, { "code": null, "e": 524, "s": 325, "text": "To replace text in a file we are going to open the file in read-only using the open() function. Then we will t=read and replace the content in the text file using the read() and replace() functions." }, { "code": null, "e": 553, "s": 524, "text": "Syntax: open(file, mode=’r’)" }, { "code": null, "e": 565, "s": 553, "text": "Parameters:" }, { "code": null, "e": 593, "s": 565, "text": "file : Location of the file" }, { "code": null, "e": 640, "s": 593, "text": "mode : Mode in which you want toopen the file." }, { "code": null, "e": 717, "s": 640, "text": "Then we will open the same file in write mode to write the replaced content." }, { "code": null, "e": 725, "s": 717, "text": "Python3" }, { "code": "# creating a variable and storing the text# that we want to searchsearch_text = \"dummy\" # creating a variable and storing the text# that we want to addreplace_text = \"replaced\" # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt', 'r') as file: # Reading the content of the file # using the read() function and storing # them in a new variable data = file.read() # Searching and replacing the text # using the replace() function data = data.replace(search_text, replace_text) # Opening our text file in write only# mode to write the replaced contentwith open(r'SampleFile.txt', 'w') as file: # Writing the replaced data in our # text file file.write(data) # Printing Text replacedprint(\"Text replaced\")", "e": 1511, "s": 725, "text": null }, { "code": null, "e": 1519, "s": 1511, "text": "Output:" }, { "code": null, "e": 1533, "s": 1519, "text": "Text replaced" }, { "code": null, "e": 1738, "s": 1533, "text": "Let see how we can search and replace text using the pathlib2 module. First, we create a Text file in which we want to search and replace text. Let this file be SampleFile.txt with the following contents:" }, { "code": null, "e": 1787, "s": 1738, "text": "Install pathlib2 module using the below command:" }, { "code": null, "e": 1808, "s": 1787, "text": "pip install pathlib2" }, { "code": null, "e": 2015, "s": 1808, "text": "This module offers classes representing filesystem paths with semantics appropriate for different operating systems. To replace the text using pathlib2 module we will use the Path method of pathlib2 module." }, { "code": null, "e": 2034, "s": 2015, "text": "Syntax: Path(file)" }, { "code": null, "e": 2046, "s": 2034, "text": "Parameters:" }, { "code": null, "e": 2090, "s": 2046, "text": "file: Location of the file you want to open" }, { "code": null, "e": 2195, "s": 2090, "text": "In the below code we are replacing “dummy” with “replaced” in our text file. using the pathlib2 module. " }, { "code": null, "e": 2201, "s": 2195, "text": "Code:" }, { "code": null, "e": 2209, "s": 2201, "text": "Python3" }, { "code": "# Importing Path from pathlib2 modulefrom pathlib2 import Path # Creating a function to# replace the textdef replacetext(search_text, replace_text): # Opening the file using the Path function file = Path(r\"SampleFile.txt\") # Reading and storing the content of the file in # a data variable data = file.read_text() # Replacing the text using the replace function data = data.replace(search_text, replace_text) # Writing the replaced data # in the text file file.write_text(data) # Return \"Text replaced\" string return \"Text replaced\" # Creating a variable and storing# the text that we want to searchsearch_text = \"dummy\" # Creating a variable and storing# the text that we want to updatereplace_text = \"replaced\" # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text, replace_text))", "e": 3091, "s": 2209, "text": null }, { "code": null, "e": 3099, "s": 3091, "text": "Output:" }, { "code": null, "e": 3113, "s": 3099, "text": "Text replaced" }, { "code": null, "e": 3242, "s": 3113, "text": "Let see how we can search and replace text using the regex module. We are going to use the re.sub( ) method to replace the text." }, { "code": null, "e": 3298, "s": 3242, "text": "Syntax: re.sub(pattern, repl, string, count=0, flags=0)" }, { "code": null, "e": 3310, "s": 3298, "text": "Parameters:" }, { "code": null, "e": 3338, "s": 3310, "text": "repl : Text you want to add" }, { "code": null, "e": 3372, "s": 3338, "text": "string : Text you want to replace" }, { "code": null, "e": 3378, "s": 3372, "text": "Code:" }, { "code": null, "e": 3386, "s": 3378, "text": "Python3" }, { "code": "# Importing re moduleimport re # Creating a function to# replace the textdef replacetext(search_text,replace_text): # Opening the file in read and write mode with open('SampleFile.txt','r+') as f: # Reading the file data and store # it in a file variable file = f.read() # Replacing the pattern with the string # in the file data file = re.sub(search_text, replace_text, file) # Setting the position to the top # of the page to insert data f.seek(0) # Writing replaced data in the file f.write(file) # Truncating the file size f.truncate() # Return \"Text replaced\" string return \"Text replaced\" # Creating a variable and storing# the text that we want to searchsearch_text = \"dummy\" #Creating a variable and storing# the text that we want to updatereplace_text = \"replaced\" # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text,replace_text))", "e": 4413, "s": 3386, "text": null }, { "code": null, "e": 4421, "s": 4413, "text": "Output:" }, { "code": null, "e": 4435, "s": 4421, "text": "Text replaced" }, { "code": null, "e": 4606, "s": 4435, "text": "Let see how we can search and replace text using the fileinput module. For this, we will use FileInput() method to iterate over the data of the file and replace the text." }, { "code": null, "e": 4674, "s": 4606, "text": "Syntax: FileInput(files=None, inplace=False, backup=”, *, mode=’r’)" }, { "code": null, "e": 4686, "s": 4674, "text": "Parameters:" }, { "code": null, "e": 4720, "s": 4686, "text": "files : Location of the text file" }, { "code": null, "e": 4766, "s": 4720, "text": "mode : Mode in which you want toopen the file" }, { "code": null, "e": 4837, "s": 4766, "text": "inplace : If value is True then the file is moved to a backup file and" }, { "code": null, "e": 4883, "s": 4837, "text": "standard output is directed to the input file" }, { "code": null, "e": 4922, "s": 4883, "text": "backup : Extension for the backup file" }, { "code": null, "e": 4928, "s": 4922, "text": "Code:" }, { "code": null, "e": 4936, "s": 4928, "text": "Python3" }, { "code": "# Importing FileInput from fileinput modulefrom fileinput import FileInput # Creating a function to# replace the textdef replacetext(search_text, replace_text): # Opening file using FileInput with FileInput(\"SampleFile.txt\", inplace=True, backup='.bak') as f: # Iterating over every and changing # the search_text with replace_text # using the replace function for line in f: print(line.replace(search_text, replace_text), end='') # Return \"Text replaced\" string return \"Text replaced\" # Creating a variable and storing# the text that we want to searchsearch_text = \"dummy\" # Creating a variable and storing# the text that we want to updatereplace_text = \"replaced\" # Calling the replacetext function# and printing the returned statementprint(replacetext(search_text, replace_text))", "e": 5830, "s": 4936, "text": null }, { "code": null, "e": 5838, "s": 5830, "text": "Output:" }, { "code": null, "e": 5852, "s": 5838, "text": "Text replaced" }, { "code": null, "e": 5859, "s": 5852, "text": "Picked" }, { "code": null, "e": 5889, "s": 5859, "text": "Python file-handling-programs" }, { "code": null, "e": 5896, "s": 5889, "text": "Python" } ]