title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Calculate Standard Error in R
07 Sep, 2021 In this article, we are going to see how to calculate standard error in R Programming Language. Mathematically we can calculate standard error by using the formula: standard deviation/squareroot(n) Using sd() function with length function By using the standard error formula. Using plotrix package. Here we are going to use sd() function which will calculate the standard deviation and then the length() function to find the total number of observation. Syntax: sd(data)/sqrt(length((data))) R # consider a vector with 10 elementsa < - c(179, 160, 136, 227, 123, 23, 45, 67, 1, 234) # calculate standard errorprint(sd(a)/sqrt(length((a)))) Output: [1] 26.20274 Here we will use the standard error formula for getting the observations. Syntax: sqrt(sum((a-mean(a))^2/(length(a)-1)))/sqrt(length(a)) where data is the input data sqrt function is to find the square root sum is used to find the sum of elements in the data mean is the function used to find the mean of the data length is the function used to return the length of the data R # consider a vector with 10 elementsa <- c(179, 160, 136, 227, 123, 23, 45, 67, 1, 234) # calculate standard errorprint(sqrt(sum((a - mean(a)) ^ 2/(length(a) - 1))) /sqrt(length(a))) Output: [1] 26.20274 This is the built-in function that directly calculated the standard error. It is available in plotrix package Syntax: std.error(data) R # import plotrix packagelibrary("plotrix") # consider a vector with 10 elementsa <- c(179,160,136,227,123, 23,45,67,1,234) # calculate standard error using in built# functionprint(std.error(a)) Output: [1] 26.20274 kk773572498 Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Sep, 2021" }, { "code": null, "e": 125, "s": 28, "text": "In this article, we are going to see how to calculate standard error in R Programming Language. " }, { "code": null, "e": 194, "s": 125, "text": "Mathematically we can calculate standard error by using the formula:" }, { "code": null, "e": 227, "s": 194, "text": "standard deviation/squareroot(n)" }, { "code": null, "e": 268, "s": 227, "text": "Using sd() function with length function" }, { "code": null, "e": 305, "s": 268, "text": "By using the standard error formula." }, { "code": null, "e": 328, "s": 305, "text": "Using plotrix package." }, { "code": null, "e": 483, "s": 328, "text": "Here we are going to use sd() function which will calculate the standard deviation and then the length() function to find the total number of observation." }, { "code": null, "e": 521, "s": 483, "text": "Syntax: sd(data)/sqrt(length((data)))" }, { "code": null, "e": 523, "s": 521, "text": "R" }, { "code": "# consider a vector with 10 elementsa < - c(179, 160, 136, 227, 123, 23, 45, 67, 1, 234) # calculate standard errorprint(sd(a)/sqrt(length((a))))", "e": 676, "s": 523, "text": null }, { "code": null, "e": 684, "s": 676, "text": "Output:" }, { "code": null, "e": 697, "s": 684, "text": "[1] 26.20274" }, { "code": null, "e": 771, "s": 697, "text": "Here we will use the standard error formula for getting the observations." }, { "code": null, "e": 834, "s": 771, "text": "Syntax: sqrt(sum((a-mean(a))^2/(length(a)-1)))/sqrt(length(a))" }, { "code": null, "e": 840, "s": 834, "text": "where" }, { "code": null, "e": 863, "s": 840, "text": "data is the input data" }, { "code": null, "e": 904, "s": 863, "text": "sqrt function is to find the square root" }, { "code": null, "e": 956, "s": 904, "text": "sum is used to find the sum of elements in the data" }, { "code": null, "e": 1011, "s": 956, "text": "mean is the function used to find the mean of the data" }, { "code": null, "e": 1072, "s": 1011, "text": "length is the function used to return the length of the data" }, { "code": null, "e": 1074, "s": 1072, "text": "R" }, { "code": "# consider a vector with 10 elementsa <- c(179, 160, 136, 227, 123, 23, 45, 67, 1, 234) # calculate standard errorprint(sqrt(sum((a - mean(a)) ^ 2/(length(a) - 1))) /sqrt(length(a)))", "e": 1268, "s": 1074, "text": null }, { "code": null, "e": 1276, "s": 1268, "text": "Output:" }, { "code": null, "e": 1289, "s": 1276, "text": "[1] 26.20274" }, { "code": null, "e": 1400, "s": 1289, "text": "This is the built-in function that directly calculated the standard error. It is available in plotrix package " }, { "code": null, "e": 1424, "s": 1400, "text": "Syntax: std.error(data)" }, { "code": null, "e": 1426, "s": 1424, "text": "R" }, { "code": "# import plotrix packagelibrary(\"plotrix\") # consider a vector with 10 elementsa <- c(179,160,136,227,123, 23,45,67,1,234) # calculate standard error using in built# functionprint(std.error(a))", "e": 1626, "s": 1426, "text": null }, { "code": null, "e": 1634, "s": 1626, "text": "Output:" }, { "code": null, "e": 1647, "s": 1634, "text": "[1] 26.20274" }, { "code": null, "e": 1659, "s": 1647, "text": "kk773572498" }, { "code": null, "e": 1666, "s": 1659, "text": "Picked" }, { "code": null, "e": 1679, "s": 1666, "text": "R-Statistics" }, { "code": null, "e": 1690, "s": 1679, "text": "R Language" } ]
Program to Print Matrix in Z form
28 Jun, 2022 Given a square matrix of order n*n, we need to print elements of the matrix in Z form Input: [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]] Output: 4 5 6 8 3 8 1 8 7 5 Input: [[4, 5, 6, 8, 5], [1, 2, 3, 1, 4], [7, 8, 9, 4, 7], [1, 8, 7, 5, 2], [7, 9, 5, 6, 9], [9, 4, 5, 6, 6]] Output: 4 5 6 8 5 1 9 8 7 9 4 5 6 6 We need to traverse the first row of the matrix then the second diagonal and then the last row. C++ Java Python3 C# PHP Javascript // CPP program to print a square matrix in Z form#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to print a square matrix in Z formvoid printZform(int mat[][MAX], int n){ // print first row for (int i = 0; i < n; i++) cout << mat[0][i] << " "; // Print second diagonal int i = 1, j = n - 2; while (i < n && j >= 0) { cout << mat[i][j] << " "; i++; j--; } // Print last row for (int i = 1; i < n; i++) cout << mat[n - 1][i] << " ";} // Driver functionint main(){ int mat[][MAX] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); return 0;} // Java program to print a// square matrix in Z form import java.io.*;import java.lang.*; class GFG { public static void diag(int arr[][], int n) { int i = 0, j, k; // print first row for (j = 0; j < n - 1; j++) { System.out.print(arr[i][j] + " "); } // Print diagonal k = 1; for (i = 0; i < n - 1; i++) { for (j = 0; j < n; j++) { if (j == n - k) { System.out.print(arr[i][j] + " "); break; } } k++; } // Print last row i = n - 1; for (j = 0; j < n; j++) System.out.print(arr[i][j] + " "); System.out.print("\n"); } public static void main(String[] args) { int a[][] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }} // Code contributed by Mohit Gupta_OMG <(0_o)> # Python Program to print a Square# Matrix in Z form. # Function to print Matrix in Z formdef Z_print(Test_list): Result = [] # Empty list to Store Final Result # To find the difference b/w whole matrix and first elements diff = len(Test_list)-len(Test_list[0]) # Loop to find elements for Z form and to print it. for i in range(len(Test_list)): # If the elements if First or Last then print it as it is... if i == 0 or i == len(Test_list)-1: Result.append(Test_list[i]) Result = Result[0] print(*Result) Result = [] else: Result.append(Test_list[i][len(Test_list)-i-1-diff]) a = Result[0] # Give require spaces for printing elements... print(" " * (len(Test_list)-i-1-diff) + str(a)) Result = [] # Empty list again for storing next pattern return Result # Driver Functionif __name__ == "__main__": Test_list1 = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]] Z_print(Test_list1) # Passing Matrix to Z_print function // C# program to print a square// matrix in Z formusing System; class GFG { public static void printZform(int[, ] mat, int n) { int i, j; // print first row for (i = 0; i < n; i++) { Console.Write(mat[0, i] + " "); } // Print diagonal i = 1; j = n - 2; while (i < n && j >= 0) // print diagonal { Console.Write(mat[i, j] + " "); i++; j--; } // Print last row for (i = 1; i < n; i++) Console.Write(mat[n - 1, i] + " "); } // Driver code public static void Main() { int[, ] mat = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); }} // This code is contributed by vt_m. <?php// PHP program to print a// square matrix in Z form $MAX = 100; // Function to print a// square matrix in Z formfunction printZform( $mat, $n){ // print first row for($i = 0; $i < $n; $i++) echo $mat[0][$i] , " "; // Print diagonal $i = 1;$j = $n - 2; // print diagonal while ($i < $n and $j >= 0) { echo $mat[$i][$j] , " "; $i++; $j--; } // Print last row for ( $i = 1; $i < $n; $i++) echo $mat[$n - 1][$i] , " ";} // Driver Code $mat = array(array(4, 5, 6, 8), array(1, 2, 3, 1), array(7, 8, 9, 4), array(1, 8, 7, 5)); printZform($mat, 4); // This code is contributed by anuj_67.?> <script> // JavaScript program to print a square// matrix in Z form function printZform(mat, n){ var i, j; // print first row for (i = 0; i < n; i++) { document.write(mat[0][i] + " "); } // Print diagonal i = 1; j = n - 2; while (i < n && j >= 0) // print diagonal { document.write(mat[i][j] + " "); i++; j--; } // Print last row for (i = 1; i < n; i++) document.write(mat[n - 1][i] + " ");}// Driver codevar mat = [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ];printZform(mat, 4); </script> Alternatively, we can print first row and second diagonal except last element and then last row. C++14 Java C# Javascript // CPP program to print a square matrix in Z form#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to print a square matrix in Z formvoid printZform(int mat[][MAX], int n){ int i; // print first row except last element for (i = 0; i < n-1; i++) cout << mat[0][i] << " "; // Print second diagonal except last element for(i=0;i<n-1;i++) cout<<mat[i][n-i-1]<<" "; // Print last row for (i = 0; i < n; i++) cout << mat[n - 1][i] << " ";} // Driver functionint main(){ int mat[][MAX] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); return 0;} // Java program to print a square matrix in Z form public final class GFG { public static int MAX = 100; // Function to print a square matrix in Z form public static void printZform(int[][] mat, int n) { int i; // print first row except last element for (i = 0; i < n - 1; i++) { System.out.print(mat[0][i]); System.out.print(" "); } // Print second diagonal except last element for (i = 0; i < n - 1; i++) { System.out.print(mat[i][n - i - 1]); System.out.print(" "); } // Print last row for (i = 0; i < n; i++) { System.out.print(mat[n - 1][i]); System.out.print(" "); } } // Driver function public static void main(String[] args) { int[][] mat = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); }} // This code is contributed by Aarti_Rathi // C# program to print a square matrix in Z formusing System; public static class GFG { public static int MAX = 100; // Function to print a square matrix in Z form public static void printZform(int[, ] mat, int n) { int i; // print first row except last element for (i = 0; i < n - 1; i++) { Console.Write(mat[0, i]); Console.Write(" "); } // Print second diagonal except last element for (i = 0; i < n - 1; i++) { Console.Write(mat[i, n - i - 1]); Console.Write(" "); } // Print last row for (i = 0; i < n; i++) { Console.Write(mat[n - 1, i]); Console.Write(" "); } } // Driver function public static void Main() { int[, ] mat = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); }} // This code is contributed by Aarti_Rathi // JavaScript program to print a square// matrix in Z form function printZform(mat, n){ var i=0, j; // print first row except last element for (i = 0; i < n - 1; i++) { document.write(mat[0][i] + " "); } // Print second diagonal except last element for (i = 0; i < n - 1; i++) { document.write(mat[i][n - i - 1] + " "); } // Print last row for (i = 0; i < n; i++) { document.write(mat[n - 1][i] + " "); } } // Driver codevar mat = [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ];printZform(mat, 4); // This code is contributed by Aarti_Rathi 4 5 6 8 3 8 1 8 7 5 Time Complexity: O(n) Auxiliary Space: O(1) Alternate Simpler Implementation: Thanks to Aathishithan for suggesting this. C++14 Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std;#define MAX 100 // C++ program to print a// square matrix in Z formvoid diag(int arr[][MAX],int n){ int i = 0, j, k; for(i = 0;i < n;i++){ for(j = 0;j < n;j++){ if(i == 0) cout<<arr[i][j]<<" "; else if(j==n-i-1) cout<<arr[i][j]<<" "; else if(i == n-1) cout<<arr[i][j]<<" "; } }} //driver's codeint main() { int a[][MAX] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); } // Java program to print a// square matrix in Z form import java.lang.*;import java.io.*; class GFG { public static void diag(int arr[][], int n) { int i = 0, j, k; for(i = 0;i < n;i++){ for(j = 0;j < n;j++){ if(i == 0){ System.out.print(arr[i][j]+" "); } else if(j==n-i-1){ System.out.print(arr[i][j]+" "); } else if(i == n-1){ System.out.print(arr[i][j]+" "); } } } } public static void main(String[] args) { int a[][] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }} # Python3 program to print# square matrix in Z formdef diag(arr, n): for i in range(n): for j in range(n): if(i == 0): print(arr[i][j], end = " ") elif(j == n-(i+1)): print(arr[i][j], end = " ") elif(i == n - 1): print(arr[i][j], end = " ") # Driver codeif __name__ == '__main__': a= [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ] diag(a, 4)# This code is contributed by mohit kumar 29 and improved by Hari Aditya // C# program to print a// square matrix in Z formusing System; public class GFG { public static void diag(int [,]arr, int n) { int i = 0, j; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if(i == 0){ Console.Write(arr[i, j]+" "); } else if(i == j){ Console.Write(arr[i, j]+" "); } else if(i == n-1){ Console.Write(arr[i, j]+" "); } } } } public static void Main(string[] args) { int [,]a = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }} // This code is contributed by rrrtnx. <script> // Javascript program to print a// square matrix in Z form function diag(arr, n){ var i = 0, j; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if(i == 0){ document.write(arr[i][j]+" "); } else if(i == j){ document.write(arr[i][j]+" "); } else if(i == n-1){ document.write(arr[i][j]+" "); } } } } var a = [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ];diag(a, 4); // This code is contributed by rutvik_56. </script> 4 5 6 8 3 8 1 8 7 5 Time Complexity: O(n*n) Auxiliary Space: O(1) This article is contributed by Aarti_Rathi and R_Raj. 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. vt_m Aathishithan mohit kumar 29 gittysatyam noob2000 hariaditya rrrtnx rutvik_56 rishabhmittal prophet1999 sachinvinod1904 adi1212 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jun, 2022" }, { "code": null, "e": 140, "s": 53, "text": "Given a square matrix of order n*n, we need to print elements of the matrix in Z form " }, { "code": null, "e": 629, "s": 140, "text": " Input: [[4, 5, 6, 8], \n [1, 2, 3, 1], \n [7, 8, 9, 4], \n [1, 8, 7, 5]]\n \n Output: 4 5 6 8\n 3\n 8\n 1 8 7 5\n \n Input: [[4, 5, 6, 8, 5],\n [1, 2, 3, 1, 4],\n [7, 8, 9, 4, 7],\n [1, 8, 7, 5, 2],\n [7, 9, 5, 6, 9],\n [9, 4, 5, 6, 6]]\n \n Output: 4 5 6 8 5\n 1\n 9\n 8\n 7\n 9 4 5 6 6" }, { "code": null, "e": 728, "s": 631, "text": "We need to traverse the first row of the matrix then the second diagonal and then the last row. " }, { "code": null, "e": 732, "s": 728, "text": "C++" }, { "code": null, "e": 737, "s": 732, "text": "Java" }, { "code": null, "e": 745, "s": 737, "text": "Python3" }, { "code": null, "e": 748, "s": 745, "text": "C#" }, { "code": null, "e": 752, "s": 748, "text": "PHP" }, { "code": null, "e": 763, "s": 752, "text": "Javascript" }, { "code": "// CPP program to print a square matrix in Z form#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to print a square matrix in Z formvoid printZform(int mat[][MAX], int n){ // print first row for (int i = 0; i < n; i++) cout << mat[0][i] << \" \"; // Print second diagonal int i = 1, j = n - 2; while (i < n && j >= 0) { cout << mat[i][j] << \" \"; i++; j--; } // Print last row for (int i = 1; i < n; i++) cout << mat[n - 1][i] << \" \";} // Driver functionint main(){ int mat[][MAX] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); return 0;}", "e": 1509, "s": 763, "text": null }, { "code": "// Java program to print a// square matrix in Z form import java.io.*;import java.lang.*; class GFG { public static void diag(int arr[][], int n) { int i = 0, j, k; // print first row for (j = 0; j < n - 1; j++) { System.out.print(arr[i][j] + \" \"); } // Print diagonal k = 1; for (i = 0; i < n - 1; i++) { for (j = 0; j < n; j++) { if (j == n - k) { System.out.print(arr[i][j] + \" \"); break; } } k++; } // Print last row i = n - 1; for (j = 0; j < n; j++) System.out.print(arr[i][j] + \" \"); System.out.print(\"\\n\"); } public static void main(String[] args) { int a[][] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }} // Code contributed by Mohit Gupta_OMG <(0_o)>", "e": 2516, "s": 1509, "text": null }, { "code": "# Python Program to print a Square# Matrix in Z form. # Function to print Matrix in Z formdef Z_print(Test_list): Result = [] # Empty list to Store Final Result # To find the difference b/w whole matrix and first elements diff = len(Test_list)-len(Test_list[0]) # Loop to find elements for Z form and to print it. for i in range(len(Test_list)): # If the elements if First or Last then print it as it is... if i == 0 or i == len(Test_list)-1: Result.append(Test_list[i]) Result = Result[0] print(*Result) Result = [] else: Result.append(Test_list[i][len(Test_list)-i-1-diff]) a = Result[0] # Give require spaces for printing elements... print(\" \" * (len(Test_list)-i-1-diff) + str(a)) Result = [] # Empty list again for storing next pattern return Result # Driver Functionif __name__ == \"__main__\": Test_list1 = [[4, 5, 6, 8], [1, 2, 3, 1], [7, 8, 9, 4], [1, 8, 7, 5]] Z_print(Test_list1) # Passing Matrix to Z_print function", "e": 3648, "s": 2516, "text": null }, { "code": "// C# program to print a square// matrix in Z formusing System; class GFG { public static void printZform(int[, ] mat, int n) { int i, j; // print first row for (i = 0; i < n; i++) { Console.Write(mat[0, i] + \" \"); } // Print diagonal i = 1; j = n - 2; while (i < n && j >= 0) // print diagonal { Console.Write(mat[i, j] + \" \"); i++; j--; } // Print last row for (i = 1; i < n; i++) Console.Write(mat[n - 1, i] + \" \"); } // Driver code public static void Main() { int[, ] mat = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); }} // This code is contributed by vt_m.", "e": 4505, "s": 3648, "text": null }, { "code": "<?php// PHP program to print a// square matrix in Z form $MAX = 100; // Function to print a// square matrix in Z formfunction printZform( $mat, $n){ // print first row for($i = 0; $i < $n; $i++) echo $mat[0][$i] , \" \"; // Print diagonal $i = 1;$j = $n - 2; // print diagonal while ($i < $n and $j >= 0) { echo $mat[$i][$j] , \" \"; $i++; $j--; } // Print last row for ( $i = 1; $i < $n; $i++) echo $mat[$n - 1][$i] , \" \";} // Driver Code $mat = array(array(4, 5, 6, 8), array(1, 2, 3, 1), array(7, 8, 9, 4), array(1, 8, 7, 5)); printZform($mat, 4); // This code is contributed by anuj_67.?>", "e": 5237, "s": 4505, "text": null }, { "code": "<script> // JavaScript program to print a square// matrix in Z form function printZform(mat, n){ var i, j; // print first row for (i = 0; i < n; i++) { document.write(mat[0][i] + \" \"); } // Print diagonal i = 1; j = n - 2; while (i < n && j >= 0) // print diagonal { document.write(mat[i][j] + \" \"); i++; j--; } // Print last row for (i = 1; i < n; i++) document.write(mat[n - 1][i] + \" \");}// Driver codevar mat = [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ];printZform(mat, 4); </script>", "e": 5863, "s": 5237, "text": null }, { "code": null, "e": 5960, "s": 5863, "text": "Alternatively, we can print first row and second diagonal except last element and then last row." }, { "code": null, "e": 5966, "s": 5960, "text": "C++14" }, { "code": null, "e": 5971, "s": 5966, "text": "Java" }, { "code": null, "e": 5974, "s": 5971, "text": "C#" }, { "code": null, "e": 5985, "s": 5974, "text": "Javascript" }, { "code": "// CPP program to print a square matrix in Z form#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to print a square matrix in Z formvoid printZform(int mat[][MAX], int n){ int i; // print first row except last element for (i = 0; i < n-1; i++) cout << mat[0][i] << \" \"; // Print second diagonal except last element for(i=0;i<n-1;i++) cout<<mat[i][n-i-1]<<\" \"; // Print last row for (i = 0; i < n; i++) cout << mat[n - 1][i] << \" \";} // Driver functionint main(){ int mat[][MAX] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); return 0;}", "e": 6707, "s": 5985, "text": null }, { "code": "// Java program to print a square matrix in Z form public final class GFG { public static int MAX = 100; // Function to print a square matrix in Z form public static void printZform(int[][] mat, int n) { int i; // print first row except last element for (i = 0; i < n - 1; i++) { System.out.print(mat[0][i]); System.out.print(\" \"); } // Print second diagonal except last element for (i = 0; i < n - 1; i++) { System.out.print(mat[i][n - i - 1]); System.out.print(\" \"); } // Print last row for (i = 0; i < n; i++) { System.out.print(mat[n - 1][i]); System.out.print(\" \"); } } // Driver function public static void main(String[] args) { int[][] mat = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); }} // This code is contributed by Aarti_Rathi", "e": 7741, "s": 6707, "text": null }, { "code": "// C# program to print a square matrix in Z formusing System; public static class GFG { public static int MAX = 100; // Function to print a square matrix in Z form public static void printZform(int[, ] mat, int n) { int i; // print first row except last element for (i = 0; i < n - 1; i++) { Console.Write(mat[0, i]); Console.Write(\" \"); } // Print second diagonal except last element for (i = 0; i < n - 1; i++) { Console.Write(mat[i, n - i - 1]); Console.Write(\" \"); } // Print last row for (i = 0; i < n; i++) { Console.Write(mat[n - 1, i]); Console.Write(\" \"); } } // Driver function public static void Main() { int[, ] mat = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; printZform(mat, 4); }} // This code is contributed by Aarti_Rathi", "e": 8639, "s": 7741, "text": null }, { "code": "// JavaScript program to print a square// matrix in Z form function printZform(mat, n){ var i=0, j; // print first row except last element for (i = 0; i < n - 1; i++) { document.write(mat[0][i] + \" \"); } // Print second diagonal except last element for (i = 0; i < n - 1; i++) { document.write(mat[i][n - i - 1] + \" \"); } // Print last row for (i = 0; i < n; i++) { document.write(mat[n - 1][i] + \" \"); } } // Driver codevar mat = [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ];printZform(mat, 4); // This code is contributed by Aarti_Rathi", "e": 9342, "s": 8639, "text": null }, { "code": null, "e": 9363, "s": 9342, "text": "4 5 6 8 3 8 1 8 7 5 " }, { "code": null, "e": 9385, "s": 9363, "text": "Time Complexity: O(n)" }, { "code": null, "e": 9407, "s": 9385, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 9486, "s": 9407, "text": "Alternate Simpler Implementation: Thanks to Aathishithan for suggesting this. " }, { "code": null, "e": 9492, "s": 9486, "text": "C++14" }, { "code": null, "e": 9497, "s": 9492, "text": "Java" }, { "code": null, "e": 9505, "s": 9497, "text": "Python3" }, { "code": null, "e": 9508, "s": 9505, "text": "C#" }, { "code": null, "e": 9519, "s": 9508, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std;#define MAX 100 // C++ program to print a// square matrix in Z formvoid diag(int arr[][MAX],int n){ int i = 0, j, k; for(i = 0;i < n;i++){ for(j = 0;j < n;j++){ if(i == 0) cout<<arr[i][j]<<\" \"; else if(j==n-i-1) cout<<arr[i][j]<<\" \"; else if(i == n-1) cout<<arr[i][j]<<\" \"; } }} //driver's codeint main() { int a[][MAX] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }", "e": 10179, "s": 9519, "text": null }, { "code": "// Java program to print a// square matrix in Z form import java.lang.*;import java.io.*; class GFG { public static void diag(int arr[][], int n) { int i = 0, j, k; for(i = 0;i < n;i++){ for(j = 0;j < n;j++){ if(i == 0){ System.out.print(arr[i][j]+\" \"); } else if(j==n-i-1){ System.out.print(arr[i][j]+\" \"); } else if(i == n-1){ System.out.print(arr[i][j]+\" \"); } } } } public static void main(String[] args) { int a[][] = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }}", "e": 10934, "s": 10179, "text": null }, { "code": "# Python3 program to print# square matrix in Z formdef diag(arr, n): for i in range(n): for j in range(n): if(i == 0): print(arr[i][j], end = \" \") elif(j == n-(i+1)): print(arr[i][j], end = \" \") elif(i == n - 1): print(arr[i][j], end = \" \") # Driver codeif __name__ == '__main__': a= [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ] diag(a, 4)# This code is contributed by mohit kumar 29 and improved by Hari Aditya", "e": 11486, "s": 10934, "text": null }, { "code": "// C# program to print a// square matrix in Z formusing System; public class GFG { public static void diag(int [,]arr, int n) { int i = 0, j; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if(i == 0){ Console.Write(arr[i, j]+\" \"); } else if(i == j){ Console.Write(arr[i, j]+\" \"); } else if(i == n-1){ Console.Write(arr[i, j]+\" \"); } } } } public static void Main(string[] args) { int [,]a = { { 4, 5, 6, 8 }, { 1, 2, 3, 1 }, { 7, 8, 9, 4 }, { 1, 8, 7, 5 } }; diag(a, 4); }} // This code is contributed by rrrtnx.", "e": 12267, "s": 11486, "text": null }, { "code": "<script> // Javascript program to print a// square matrix in Z form function diag(arr, n){ var i = 0, j; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if(i == 0){ document.write(arr[i][j]+\" \"); } else if(i == j){ document.write(arr[i][j]+\" \"); } else if(i == n-1){ document.write(arr[i][j]+\" \"); } } } } var a = [ [ 4, 5, 6, 8 ], [ 1, 2, 3, 1 ], [ 7, 8, 9, 4 ], [ 1, 8, 7, 5 ] ];diag(a, 4); // This code is contributed by rutvik_56. </script>", "e": 12859, "s": 12267, "text": null }, { "code": null, "e": 12880, "s": 12859, "text": "4 5 6 8 3 8 1 8 7 5 " }, { "code": null, "e": 12904, "s": 12880, "text": "Time Complexity: O(n*n)" }, { "code": null, "e": 12926, "s": 12904, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 13356, "s": 12926, "text": "This article is contributed by Aarti_Rathi and R_Raj. 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": 13361, "s": 13356, "text": "vt_m" }, { "code": null, "e": 13374, "s": 13361, "text": "Aathishithan" }, { "code": null, "e": 13389, "s": 13374, "text": "mohit kumar 29" }, { "code": null, "e": 13401, "s": 13389, "text": "gittysatyam" }, { "code": null, "e": 13410, "s": 13401, "text": "noob2000" }, { "code": null, "e": 13421, "s": 13410, "text": "hariaditya" }, { "code": null, "e": 13428, "s": 13421, "text": "rrrtnx" }, { "code": null, "e": 13438, "s": 13428, "text": "rutvik_56" }, { "code": null, "e": 13452, "s": 13438, "text": "rishabhmittal" }, { "code": null, "e": 13464, "s": 13452, "text": "prophet1999" }, { "code": null, "e": 13480, "s": 13464, "text": "sachinvinod1904" }, { "code": null, "e": 13488, "s": 13480, "text": "adi1212" }, { "code": null, "e": 13495, "s": 13488, "text": "Matrix" }, { "code": null, "e": 13514, "s": 13495, "text": "School Programming" }, { "code": null, "e": 13521, "s": 13514, "text": "Matrix" } ]
Find the maximum node at a given level in a binary tree
31 Mar, 2022 Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call. So that the last call will return the node with maximum value among all nodes at the given level.Below is the step by step algorithm: Perform DFS traversal and every time decrease the value of level by 1 and keep traversing to the left and right subtrees recursively.When value of level becomes 0, it means we are on the given level, then return root->data.Find the maximum between the two values returned by left and right subtrees and return the maximum. Perform DFS traversal and every time decrease the value of level by 1 and keep traversing to the left and right subtrees recursively. When value of level becomes 0, it means we are on the given level, then return root->data. Find the maximum between the two values returned by left and right subtrees and return the maximum. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to find the node with// maximum value at a given level #include <iostream> using namespace std; // Tree nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new Nodestruct Node* newNode(int val){ struct Node* temp = new Node; temp->left = NULL; temp->right = NULL; temp->data = val; return temp;} // function to find the maximum value// at given levelint maxAtLevel(struct Node* root, int level){ // If the tree is empty if (root == NULL) return 0; // if level becomes 0, it means we are on // any node at the given level if (level == 0) return root->data; int x = maxAtLevel(root->left, level - 1); int y = maxAtLevel(root->right, level - 1); // return maximum of two return max(x, y);} // Driver codeint main(){ // Creating the tree struct Node* root = NULL; root = newNode(45); root->left = newNode(46); root->left->left = newNode(18); root->left->left->left = newNode(16); root->left->left->right = newNode(23); root->left->right = newNode(17); root->left->right->left = newNode(24); root->left->right->right = newNode(21); root->right = newNode(15); root->right->left = newNode(22); root->right->left->left = newNode(37); root->right->left->right = newNode(41); root->right->right = newNode(19); root->right->right->left = newNode(49); root->right->right->right = newNode(29); int level = 3; cout << maxAtLevel(root, level); return 0;} // Java program to find the// node with maximum value// at a given levelimport java.util.*;class GFG{ // Tree nodestatic class Node{ int data; Node left, right;} // Utility function to// create a new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = val; return temp;} // function to find// the maximum value// at given levelstatic int maxAtLevel(Node root, int level){ // If the tree is empty if (root == null) return 0; // if level becomes 0, // it means we are on // any node at the given level if (level == 0) return root.data; int x = maxAtLevel(root.left, level - 1); int y = maxAtLevel(root.right, level - 1); // return maximum of two return Math.max(x, y);} // Driver codepublic static void main(String args[]){ // Creating the tree Node root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; System.out.println(maxAtLevel(root, level));}} // This code is contributed// by Arnab Kundu # Python3 program to find the node # with maximum value at a given level # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function to find the maximum # value at given leveldef maxAtLevel(root, level): # If the tree is empty if (root == None) : return 0 # if level becomes 0, it means we # are on any node at the given level if (level == 0) : return root.data x = maxAtLevel(root.left, level - 1) y = maxAtLevel(root.right, level - 1) # return maximum of two return max(x, y) # Driver Codeif __name__ == '__main__': """ Let us create Binary Tree shown in above example """ root = newNode(45) root.left = newNode(46) root.left.left = newNode(18) root.left.left.left = newNode(16) root.left.left.right = newNode(23) root.left.right = newNode(17) root.left.right.left = newNode(24) root.left.right.right = newNode(21) root.right = newNode(15) root.right.left = newNode(22) root.right.left.left = newNode(37) root.right.left.right = newNode(41) root.right.right = newNode(19) root.right.right.left = newNode(49) root.right.right.right = newNode(29) level = 3 print(maxAtLevel(root, level)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to find the// node with maximum value// at a given levelusing System; class GFG{ // Tree node class Node { public int data; public Node left, right; } // Utility function to // create a new Node static Node newNode(int val) { Node temp = new Node(); temp.left = null; temp.right = null; temp.data = val; return temp; } // function to find // the maximum value // at given level static int maxAtLevel(Node root, int level) { // If the tree is empty if (root == null) return 0; // if level becomes 0, // it means we are on // any node at the given level if (level == 0) return root.data; int x = maxAtLevel(root.left, level - 1); int y = maxAtLevel(root.right, level - 1); // return maximum of two return Math.Max(x, y); } // Driver code public static void Main(String []args) { // Creating the tree Node root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; Console.WriteLine(maxAtLevel(root, level)); }} // This code is contributed by 29AjayKumar <script> // Javascript program to find the node// with maximum value at a given level// Tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }} // Utility function to// create a new Nodefunction newNode(val){ var temp = new Node(); temp.left = null; temp.right = null; temp.data = val; return temp;} // Function to find// the maximum value// at given levelfunction maxAtLevel(root, level){ // If the tree is empty if (root == null) return 0; // If level becomes 0, // it means we are on // any node at the given level if (level == 0) return root.data; var x = maxAtLevel(root.left, level - 1); var y = maxAtLevel(root.right, level - 1); // Return maximum of two return Math.max(x, y);} // Driver code// Creating the treevar root = null;root = newNode(45);root.left = newNode(46);root.left.left = newNode(18);root.left.left.left = newNode(16);root.left.left.right = newNode(23);root.left.right = newNode(17);root.left.right.left = newNode(24);root.left.right.right = newNode(21);root.right = newNode(15);root.right.left = newNode(22);root.right.left.left = newNode(37);root.right.left.right = newNode(41);root.right.right = newNode(19);root.right.right.left = newNode(49);root.right.right.right = newNode(29); var level = 3;document.write(maxAtLevel(root, level)); // This code is contributed by noob2000 </script> 49 Time Complexity : O(N), where N is the total number of nodes in the binary tree.Auxiliary Space: O(N) Iterative Approach It can also be done by using Queue, which uses level order traversal and it basically checks for the maximum node when the given level is equal to our count variable. (variable k). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for above approach#include<bits/stdc++.h>using namespace std; // Tree Nodeclass TreeNode{ public: TreeNode *left, *right; int data;}; TreeNode* newNode(int item){ TreeNode* temp = new TreeNode; temp->data = item; temp->left = temp->right = NULL; return temp;} // Function to calculate maximum nodeint bfs_maximumNode(TreeNode* root, int level){ // Check if root is NULL if(root == NULL) return 0; // Queue of type TreeNode* queue<TreeNode*> mq; // Push root in queue mq.push(root); int ans = 0, maxm = INT_MIN, k = 0 ; // While queue is not empty while( !mq.empty() ) { int size = mq.size(); // While size if not 0 while(size--) { // Accessing front element // in queue TreeNode* temp = mq.front(); mq.pop(); if(level == k && maxm < temp->data) maxm = temp->data; if(temp->left) mq.push(temp->left); if(temp->right) mq.push(temp->right); } k++; ans = max(maxm, ans); } // Return answer return ans;} // Driver Codeint main(){ TreeNode* root = NULL; root = newNode(45); root->left = newNode(46); root->left->left = newNode(18); root->left->left->left = newNode(16); root->left->left->right = newNode(23); root->left->right = newNode(17); root->left->right->left = newNode(24); root->left->right->right = newNode(21); root->right = newNode(15); root->right->left = newNode(22); root->right->left->left = newNode(37); root->right->left->right = newNode(41); root->right->right = newNode(19); root->right->right->left = newNode(49); root->right->right->right = newNode(29); int level = 3; // Function Call cout << bfs_maximumNode(root, level); return 0;} //This code is written done by Anurag Mishra. // Java program for above approachimport java.util.*; class GFG{ // Tree Nodestatic class TreeNode{ TreeNode left, right; int data;}; static TreeNode newNode(int item){ TreeNode temp = new TreeNode(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to calculate maximum nodestatic int bfs_maximumNode(TreeNode root, int level){ // Check if root is null if (root == null) return 0; // Queue of type TreeNode Queue<TreeNode> mq = new LinkedList<>(); // Push root in queue mq.add(root); int ans = 0, maxm = -10000000, k = 0; // While queue is not empty while (mq.size() != 0) { int size = mq.size(); // While size if not 0 while (size != 0) { size--; // Accessing front element // in queue TreeNode temp = mq.poll(); if (level == k && maxm < temp.data) maxm = temp.data; if (temp.left != null) mq.add(temp.left); if (temp.right != null) mq.add(temp.right); } k++; ans = Math.max(maxm, ans); } // Return answer return ans;} // Driver Codepublic static void main(String []args){ TreeNode root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; // Function Call System.out.print(bfs_maximumNode(root, level));}} // This code is contributed by pratham76 # Python3 program for above approachimport sys # Tree Nodeclass TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def newNode(item): temp = TreeNode(item) return temp # Function to calculate maximum nodedef bfs_maximumNode(root, level): # Check if root is NULL if(root == None): return 0 # Queue of type TreeNode* mq = [] # Append root in queue mq.append(root) ans = 0 maxm = -sys.maxsize - 1 k = 0 # While queue is not empty while(len(mq) != 0): size = len(mq) # While size if not 0 while(size): size -= 1 # Accessing front element # in queue temp = mq[0] mq.pop(0) if (level == k and maxm < temp.data): maxm = temp.data if (temp.left): mq.append(temp.left) if (temp.right): mq.append(temp.right) k += 1 ans = max(maxm, ans) # Return answer return ans # Driver Codeif __name__=="__main__": root = None root = newNode(45) root.left = newNode(46) root.left.left = newNode(18) root.left.left.left = newNode(16) root.left.left.right = newNode(23) root.left.right = newNode(17) root.left.right.left = newNode(24) root.left.right.right = newNode(21) root.right = newNode(15) root.right.left = newNode(22) root.right.left.left = newNode(37) root.right.left.right = newNode(41) root.right.right = newNode(19) root.right.right.left = newNode(49) root.right.right.right = newNode(29) level = 3 # Function Call print(bfs_maximumNode(root, level)) # This code is contributed by rutvik_56 // C# program for above approachusing System;using System.Collections.Generic;class GFG { // Tree Node class TreeNode { public int data; public TreeNode left, right; public TreeNode(int item) { data = item; left = right = null; } } static TreeNode newNode(int item) { TreeNode temp = new TreeNode(item); return temp; } // Function to calculate maximum node static int bfs_maximumNode(TreeNode root, int level) { // Check if root is null if (root == null) return 0; // Queue of type TreeNode List<TreeNode> mq = new List<TreeNode>(); // Push root in queue mq.Add(root); int ans = 0, maxm = -10000000, k = 0; // While queue is not empty while (mq.Count != 0) { int size = mq.Count; // While size if not 0 while (size != 0) { size--; // Accessing front element // in queue TreeNode temp = mq[0]; mq.RemoveAt(0); if (level == k && maxm < temp.data) maxm = temp.data; if (temp.left != null) mq.Add(temp.left); if (temp.right != null) mq.Add(temp.right); } k++; ans = Math.Max(maxm, ans); } // Return answer return ans; } static void Main() { TreeNode root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; // Function Call Console.Write(bfs_maximumNode(root, level)); }} // This code is contributed by suresh07. <script>// JavaScript program for above approach // Tree Nodeclass TreeNode{ constructor() { this.left = this.right = null; this.data = 0; }} function newNode(item){ let temp = new TreeNode(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to calculate maximum nodefunction bfs_maximumNode(root,level){ // Check if root is null if (root == null) return 0; // Queue of type TreeNode let mq = []; // Push root in queue mq.push(root); let ans = 0, maxm = -10000000, k = 0; // While queue is not empty while (mq.length != 0) { let size = mq.length; // While size if not 0 while (size != 0) { size--; // Accessing front element // in queue let temp = mq.shift(); if (level == k && maxm < temp.data) maxm = temp.data; if (temp.left != null) mq.push(temp.left); if (temp.right != null) mq.push(temp.right); } k++; ans = Math.max(maxm, ans); } // Return answer return ans;} // Driver Codelet root = null;root = newNode(45);root.left = newNode(46);root.left.left = newNode(18);root.left.left.left = newNode(16);root.left.left.right = newNode(23);root.left.right = newNode(17);root.left.right.left = newNode(24);root.left.right.right = newNode(21);root.right = newNode(15);root.right.left = newNode(22); root.right.left.left = newNode(37);root.right.left.right = newNode(41);root.right.right = newNode(19);root.right.right.left = newNode(49);root.right.right.right = newNode(29); let level = 3; // Function Calldocument.write(bfs_maximumNode(root, level)); // This code is contributed by avanitrachhadiya2155</script> 49 Time Complexity : O(N), where N is the total number of nodes in the binary tree.Auxiliary Space: O(N) andrew1234 SHUBHAMSINGH10 29AjayKumar 0nurag rutvik_56 pratham76 simmytarika5 noob2000 pankajsharmagfg avanitrachhadiya2155 suresh07 surinderdawra388 Binary Tree Binary Trees Quiz DFS Data Structures Tree Data Structures DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Hashing | A Complete Tutorial What is Data Structure: Types, Classifications and Applications TCS NQT Coding Sheet Find if there is a path between two vertices in an undirected graph Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Introduction to Data Structures
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Mar, 2022" }, { "code": null, "e": 159, "s": 53, "text": "Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level." }, { "code": null, "e": 488, "s": 159, "text": "The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call. So that the last call will return the node with maximum value among all nodes at the given level.Below is the step by step algorithm: " }, { "code": null, "e": 811, "s": 488, "text": "Perform DFS traversal and every time decrease the value of level by 1 and keep traversing to the left and right subtrees recursively.When value of level becomes 0, it means we are on the given level, then return root->data.Find the maximum between the two values returned by left and right subtrees and return the maximum." }, { "code": null, "e": 945, "s": 811, "text": "Perform DFS traversal and every time decrease the value of level by 1 and keep traversing to the left and right subtrees recursively." }, { "code": null, "e": 1036, "s": 945, "text": "When value of level becomes 0, it means we are on the given level, then return root->data." }, { "code": null, "e": 1136, "s": 1036, "text": "Find the maximum between the two values returned by left and right subtrees and return the maximum." }, { "code": null, "e": 1184, "s": 1136, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 1188, "s": 1184, "text": "C++" }, { "code": null, "e": 1193, "s": 1188, "text": "Java" }, { "code": null, "e": 1201, "s": 1193, "text": "Python3" }, { "code": null, "e": 1204, "s": 1201, "text": "C#" }, { "code": null, "e": 1215, "s": 1204, "text": "Javascript" }, { "code": "// C++ program to find the node with// maximum value at a given level #include <iostream> using namespace std; // Tree nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new Nodestruct Node* newNode(int val){ struct Node* temp = new Node; temp->left = NULL; temp->right = NULL; temp->data = val; return temp;} // function to find the maximum value// at given levelint maxAtLevel(struct Node* root, int level){ // If the tree is empty if (root == NULL) return 0; // if level becomes 0, it means we are on // any node at the given level if (level == 0) return root->data; int x = maxAtLevel(root->left, level - 1); int y = maxAtLevel(root->right, level - 1); // return maximum of two return max(x, y);} // Driver codeint main(){ // Creating the tree struct Node* root = NULL; root = newNode(45); root->left = newNode(46); root->left->left = newNode(18); root->left->left->left = newNode(16); root->left->left->right = newNode(23); root->left->right = newNode(17); root->left->right->left = newNode(24); root->left->right->right = newNode(21); root->right = newNode(15); root->right->left = newNode(22); root->right->left->left = newNode(37); root->right->left->right = newNode(41); root->right->right = newNode(19); root->right->right->left = newNode(49); root->right->right->right = newNode(29); int level = 3; cout << maxAtLevel(root, level); return 0;}", "e": 2735, "s": 1215, "text": null }, { "code": "// Java program to find the// node with maximum value// at a given levelimport java.util.*;class GFG{ // Tree nodestatic class Node{ int data; Node left, right;} // Utility function to// create a new Nodestatic Node newNode(int val){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = val; return temp;} // function to find// the maximum value// at given levelstatic int maxAtLevel(Node root, int level){ // If the tree is empty if (root == null) return 0; // if level becomes 0, // it means we are on // any node at the given level if (level == 0) return root.data; int x = maxAtLevel(root.left, level - 1); int y = maxAtLevel(root.right, level - 1); // return maximum of two return Math.max(x, y);} // Driver codepublic static void main(String args[]){ // Creating the tree Node root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; System.out.println(maxAtLevel(root, level));}} // This code is contributed// by Arnab Kundu", "e": 4272, "s": 2735, "text": null }, { "code": "# Python3 program to find the node # with maximum value at a given level # Helper function that allocates a new# node with the given data and None# left and right pointers. class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function to find the maximum # value at given leveldef maxAtLevel(root, level): # If the tree is empty if (root == None) : return 0 # if level becomes 0, it means we # are on any node at the given level if (level == 0) : return root.data x = maxAtLevel(root.left, level - 1) y = maxAtLevel(root.right, level - 1) # return maximum of two return max(x, y) # Driver Codeif __name__ == '__main__': \"\"\" Let us create Binary Tree shown in above example \"\"\" root = newNode(45) root.left = newNode(46) root.left.left = newNode(18) root.left.left.left = newNode(16) root.left.left.right = newNode(23) root.left.right = newNode(17) root.left.right.left = newNode(24) root.left.right.right = newNode(21) root.right = newNode(15) root.right.left = newNode(22) root.right.left.left = newNode(37) root.right.left.right = newNode(41) root.right.right = newNode(19) root.right.right.left = newNode(49) root.right.right.right = newNode(29) level = 3 print(maxAtLevel(root, level)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 5773, "s": 4272, "text": null }, { "code": "// C# program to find the// node with maximum value// at a given levelusing System; class GFG{ // Tree node class Node { public int data; public Node left, right; } // Utility function to // create a new Node static Node newNode(int val) { Node temp = new Node(); temp.left = null; temp.right = null; temp.data = val; return temp; } // function to find // the maximum value // at given level static int maxAtLevel(Node root, int level) { // If the tree is empty if (root == null) return 0; // if level becomes 0, // it means we are on // any node at the given level if (level == 0) return root.data; int x = maxAtLevel(root.left, level - 1); int y = maxAtLevel(root.right, level - 1); // return maximum of two return Math.Max(x, y); } // Driver code public static void Main(String []args) { // Creating the tree Node root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; Console.WriteLine(maxAtLevel(root, level)); }} // This code is contributed by 29AjayKumar", "e": 7535, "s": 5773, "text": null }, { "code": "<script> // Javascript program to find the node// with maximum value at a given level// Tree nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }} // Utility function to// create a new Nodefunction newNode(val){ var temp = new Node(); temp.left = null; temp.right = null; temp.data = val; return temp;} // Function to find// the maximum value// at given levelfunction maxAtLevel(root, level){ // If the tree is empty if (root == null) return 0; // If level becomes 0, // it means we are on // any node at the given level if (level == 0) return root.data; var x = maxAtLevel(root.left, level - 1); var y = maxAtLevel(root.right, level - 1); // Return maximum of two return Math.max(x, y);} // Driver code// Creating the treevar root = null;root = newNode(45);root.left = newNode(46);root.left.left = newNode(18);root.left.left.left = newNode(16);root.left.left.right = newNode(23);root.left.right = newNode(17);root.left.right.left = newNode(24);root.left.right.right = newNode(21);root.right = newNode(15);root.right.left = newNode(22);root.right.left.left = newNode(37);root.right.left.right = newNode(41);root.right.right = newNode(19);root.right.right.left = newNode(49);root.right.right.right = newNode(29); var level = 3;document.write(maxAtLevel(root, level)); // This code is contributed by noob2000 </script>", "e": 9002, "s": 7535, "text": null }, { "code": null, "e": 9005, "s": 9002, "text": "49" }, { "code": null, "e": 9107, "s": 9005, "text": "Time Complexity : O(N), where N is the total number of nodes in the binary tree.Auxiliary Space: O(N)" }, { "code": null, "e": 9307, "s": 9107, "text": "Iterative Approach It can also be done by using Queue, which uses level order traversal and it basically checks for the maximum node when the given level is equal to our count variable. (variable k)." }, { "code": null, "e": 9358, "s": 9307, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 9362, "s": 9358, "text": "C++" }, { "code": null, "e": 9367, "s": 9362, "text": "Java" }, { "code": null, "e": 9375, "s": 9367, "text": "Python3" }, { "code": null, "e": 9378, "s": 9375, "text": "C#" }, { "code": null, "e": 9389, "s": 9378, "text": "Javascript" }, { "code": "// C++ program for above approach#include<bits/stdc++.h>using namespace std; // Tree Nodeclass TreeNode{ public: TreeNode *left, *right; int data;}; TreeNode* newNode(int item){ TreeNode* temp = new TreeNode; temp->data = item; temp->left = temp->right = NULL; return temp;} // Function to calculate maximum nodeint bfs_maximumNode(TreeNode* root, int level){ // Check if root is NULL if(root == NULL) return 0; // Queue of type TreeNode* queue<TreeNode*> mq; // Push root in queue mq.push(root); int ans = 0, maxm = INT_MIN, k = 0 ; // While queue is not empty while( !mq.empty() ) { int size = mq.size(); // While size if not 0 while(size--) { // Accessing front element // in queue TreeNode* temp = mq.front(); mq.pop(); if(level == k && maxm < temp->data) maxm = temp->data; if(temp->left) mq.push(temp->left); if(temp->right) mq.push(temp->right); } k++; ans = max(maxm, ans); } // Return answer return ans;} // Driver Codeint main(){ TreeNode* root = NULL; root = newNode(45); root->left = newNode(46); root->left->left = newNode(18); root->left->left->left = newNode(16); root->left->left->right = newNode(23); root->left->right = newNode(17); root->left->right->left = newNode(24); root->left->right->right = newNode(21); root->right = newNode(15); root->right->left = newNode(22); root->right->left->left = newNode(37); root->right->left->right = newNode(41); root->right->right = newNode(19); root->right->right->left = newNode(49); root->right->right->right = newNode(29); int level = 3; // Function Call cout << bfs_maximumNode(root, level); return 0;} //This code is written done by Anurag Mishra.", "e": 11403, "s": 9389, "text": null }, { "code": "// Java program for above approachimport java.util.*; class GFG{ // Tree Nodestatic class TreeNode{ TreeNode left, right; int data;}; static TreeNode newNode(int item){ TreeNode temp = new TreeNode(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to calculate maximum nodestatic int bfs_maximumNode(TreeNode root, int level){ // Check if root is null if (root == null) return 0; // Queue of type TreeNode Queue<TreeNode> mq = new LinkedList<>(); // Push root in queue mq.add(root); int ans = 0, maxm = -10000000, k = 0; // While queue is not empty while (mq.size() != 0) { int size = mq.size(); // While size if not 0 while (size != 0) { size--; // Accessing front element // in queue TreeNode temp = mq.poll(); if (level == k && maxm < temp.data) maxm = temp.data; if (temp.left != null) mq.add(temp.left); if (temp.right != null) mq.add(temp.right); } k++; ans = Math.max(maxm, ans); } // Return answer return ans;} // Driver Codepublic static void main(String []args){ TreeNode root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; // Function Call System.out.print(bfs_maximumNode(root, level));}} // This code is contributed by pratham76", "e": 13471, "s": 11403, "text": null }, { "code": "# Python3 program for above approachimport sys # Tree Nodeclass TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def newNode(item): temp = TreeNode(item) return temp # Function to calculate maximum nodedef bfs_maximumNode(root, level): # Check if root is NULL if(root == None): return 0 # Queue of type TreeNode* mq = [] # Append root in queue mq.append(root) ans = 0 maxm = -sys.maxsize - 1 k = 0 # While queue is not empty while(len(mq) != 0): size = len(mq) # While size if not 0 while(size): size -= 1 # Accessing front element # in queue temp = mq[0] mq.pop(0) if (level == k and maxm < temp.data): maxm = temp.data if (temp.left): mq.append(temp.left) if (temp.right): mq.append(temp.right) k += 1 ans = max(maxm, ans) # Return answer return ans # Driver Codeif __name__==\"__main__\": root = None root = newNode(45) root.left = newNode(46) root.left.left = newNode(18) root.left.left.left = newNode(16) root.left.left.right = newNode(23) root.left.right = newNode(17) root.left.right.left = newNode(24) root.left.right.right = newNode(21) root.right = newNode(15) root.right.left = newNode(22) root.right.left.left = newNode(37) root.right.left.right = newNode(41) root.right.right = newNode(19) root.right.right.left = newNode(49) root.right.right.right = newNode(29) level = 3 # Function Call print(bfs_maximumNode(root, level)) # This code is contributed by rutvik_56", "e": 15351, "s": 13471, "text": null }, { "code": "// C# program for above approachusing System;using System.Collections.Generic;class GFG { // Tree Node class TreeNode { public int data; public TreeNode left, right; public TreeNode(int item) { data = item; left = right = null; } } static TreeNode newNode(int item) { TreeNode temp = new TreeNode(item); return temp; } // Function to calculate maximum node static int bfs_maximumNode(TreeNode root, int level) { // Check if root is null if (root == null) return 0; // Queue of type TreeNode List<TreeNode> mq = new List<TreeNode>(); // Push root in queue mq.Add(root); int ans = 0, maxm = -10000000, k = 0; // While queue is not empty while (mq.Count != 0) { int size = mq.Count; // While size if not 0 while (size != 0) { size--; // Accessing front element // in queue TreeNode temp = mq[0]; mq.RemoveAt(0); if (level == k && maxm < temp.data) maxm = temp.data; if (temp.left != null) mq.Add(temp.left); if (temp.right != null) mq.Add(temp.right); } k++; ans = Math.Max(maxm, ans); } // Return answer return ans; } static void Main() { TreeNode root = null; root = newNode(45); root.left = newNode(46); root.left.left = newNode(18); root.left.left.left = newNode(16); root.left.left.right = newNode(23); root.left.right = newNode(17); root.left.right.left = newNode(24); root.left.right.right = newNode(21); root.right = newNode(15); root.right.left = newNode(22); root.right.left.left = newNode(37); root.right.left.right = newNode(41); root.right.right = newNode(19); root.right.right.left = newNode(49); root.right.right.right = newNode(29); int level = 3; // Function Call Console.Write(bfs_maximumNode(root, level)); }} // This code is contributed by suresh07.", "e": 17774, "s": 15351, "text": null }, { "code": "<script>// JavaScript program for above approach // Tree Nodeclass TreeNode{ constructor() { this.left = this.right = null; this.data = 0; }} function newNode(item){ let temp = new TreeNode(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to calculate maximum nodefunction bfs_maximumNode(root,level){ // Check if root is null if (root == null) return 0; // Queue of type TreeNode let mq = []; // Push root in queue mq.push(root); let ans = 0, maxm = -10000000, k = 0; // While queue is not empty while (mq.length != 0) { let size = mq.length; // While size if not 0 while (size != 0) { size--; // Accessing front element // in queue let temp = mq.shift(); if (level == k && maxm < temp.data) maxm = temp.data; if (temp.left != null) mq.push(temp.left); if (temp.right != null) mq.push(temp.right); } k++; ans = Math.max(maxm, ans); } // Return answer return ans;} // Driver Codelet root = null;root = newNode(45);root.left = newNode(46);root.left.left = newNode(18);root.left.left.left = newNode(16);root.left.left.right = newNode(23);root.left.right = newNode(17);root.left.right.left = newNode(24);root.left.right.right = newNode(21);root.right = newNode(15);root.right.left = newNode(22); root.right.left.left = newNode(37);root.right.left.right = newNode(41);root.right.right = newNode(19);root.right.right.left = newNode(49);root.right.right.right = newNode(29); let level = 3; // Function Calldocument.write(bfs_maximumNode(root, level)); // This code is contributed by avanitrachhadiya2155</script>", "e": 19670, "s": 17774, "text": null }, { "code": null, "e": 19673, "s": 19670, "text": "49" }, { "code": null, "e": 19776, "s": 19673, "text": "Time Complexity : O(N), where N is the total number of nodes in the binary tree.Auxiliary Space: O(N) " }, { "code": null, "e": 19787, "s": 19776, "text": "andrew1234" }, { "code": null, "e": 19802, "s": 19787, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 19814, "s": 19802, "text": "29AjayKumar" }, { "code": null, "e": 19821, "s": 19814, "text": "0nurag" }, { "code": null, "e": 19831, "s": 19821, "text": "rutvik_56" }, { "code": null, "e": 19841, "s": 19831, "text": "pratham76" }, { "code": null, "e": 19854, "s": 19841, "text": "simmytarika5" }, { "code": null, "e": 19863, "s": 19854, "text": "noob2000" }, { "code": null, "e": 19879, "s": 19863, "text": "pankajsharmagfg" }, { "code": null, "e": 19900, "s": 19879, "text": "avanitrachhadiya2155" }, { "code": null, "e": 19909, "s": 19900, "text": "suresh07" }, { "code": null, "e": 19926, "s": 19909, "text": "surinderdawra388" }, { "code": null, "e": 19938, "s": 19926, "text": "Binary Tree" }, { "code": null, "e": 19956, "s": 19938, "text": "Binary Trees Quiz" }, { "code": null, "e": 19960, "s": 19956, "text": "DFS" }, { "code": null, "e": 19976, "s": 19960, "text": "Data Structures" }, { "code": null, "e": 19981, "s": 19976, "text": "Tree" }, { "code": null, "e": 19997, "s": 19981, "text": "Data Structures" }, { "code": null, "e": 20001, "s": 19997, "text": "DFS" }, { "code": null, "e": 20006, "s": 20001, "text": "Tree" }, { "code": null, "e": 20104, "s": 20006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20136, "s": 20104, "text": "Introduction to Data Structures" }, { "code": null, "e": 20174, "s": 20136, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 20238, "s": 20174, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20259, "s": 20238, "text": "TCS NQT Coding Sheet" }, { "code": null, "e": 20327, "s": 20259, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 20377, "s": 20327, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 20412, "s": 20377, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 20446, "s": 20412, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 20475, "s": 20446, "text": "AVL Tree | Set 1 (Insertion)" } ]
How to iterate over a 2D list (list of lists) in Java
17 Mar, 2020 Given a 2D list, the task is to iterate this 2D list in Java. 2D list (list of lists)The 2D list refers to a list of lists, i.e. each row of the list is another list. [ [5, 10], [1], [20, 30, 40] ] Iterate a 2D list: There are two ways of iterating over a list of list in Java. Iterating over the list of lists using loop:Get the 2D list to the iteratedWe need two for-each loops to iterate the 2D list successfully.In the first for-each loop, each row of the 2D lists will be taken as a separate listfor (List list : listOfLists) { } In the second for-each loop, each item of the list in each row will be taken separatelyfor (K item : list) { } Hence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using loop import java.util.*;public class List_of_list { // Iterate the 2D list using loop // and print each element public static <K> void iterateUsingForEach(List<List<K> > listOfLists) { // Iterate the 2D list // and print each element System.out.println("["); for (List<K> list : listOfLists) { System.out.print(" ["); for (K item : list) { System.out.print(" " + item + ", "); } System.out.println("], "); } System.out.println("]"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingForEach(listOfLists); }}Output:[ [ 5, 10, ], [ 1, ], [ 20, 30, 40, ], ] Iterating over the list of lists using iterator:Get the 2D list to the iteratedWe need two iterators to iterate the 2D list successfully.The first iterator will iterate each row of the 2D lists as a separate listIterator listOfListsIterator = listOfLists.iterator(); Each row of the 2D list can be obtained with the help of next() method of IteratorlistOfListsIterator.next(); But the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list.list = (List)listOfListsIterator.next(); The second iterator will iterate each item of the list in each row separatelyIterator eachListIterator = list.iterator(); Hence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using iterator import java.util.*; class List_of_list { // Iterate the 2D list using Iterator // and print each element public static <K> void iterateUsingIterator(List<List<K> > listOfLists) { // Iterator for the 2D list Iterator listOfListsIterator = listOfLists.iterator(); System.out.println("["); while (listOfListsIterator.hasNext()) { // Type cast next() method // to convert from Object to List<K> List<K> list = new ArrayList<K>(); list = (List<K>)listOfListsIterator.next(); // Iterator for list Iterator eachListIterator = list.iterator(); System.out.print(" ["); while (eachListIterator.hasNext()) { System.out.print( " " + eachListIterator.next() + ", "); } System.out.println("], "); } System.out.println("]"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingIterator(listOfLists); }}Output:[ [ 5, 10, ], [ 1, ], [ 20, 30, 40, ], ] Iterating over the list of lists using loop:Get the 2D list to the iteratedWe need two for-each loops to iterate the 2D list successfully.In the first for-each loop, each row of the 2D lists will be taken as a separate listfor (List list : listOfLists) { } In the second for-each loop, each item of the list in each row will be taken separatelyfor (K item : list) { } Hence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using loop import java.util.*;public class List_of_list { // Iterate the 2D list using loop // and print each element public static <K> void iterateUsingForEach(List<List<K> > listOfLists) { // Iterate the 2D list // and print each element System.out.println("["); for (List<K> list : listOfLists) { System.out.print(" ["); for (K item : list) { System.out.print(" " + item + ", "); } System.out.println("], "); } System.out.println("]"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingForEach(listOfLists); }}Output:[ [ 5, 10, ], [ 1, ], [ 20, 30, 40, ], ] Get the 2D list to the iterated We need two for-each loops to iterate the 2D list successfully. In the first for-each loop, each row of the 2D lists will be taken as a separate listfor (List list : listOfLists) { } for (List list : listOfLists) { } In the second for-each loop, each item of the list in each row will be taken separatelyfor (K item : list) { } for (K item : list) { } Hence we can do any operation on this item. Here we are printing the item. Below is the implementation of the above approach: // Java code to demonstrate the concept of// list of lists using loop import java.util.*;public class List_of_list { // Iterate the 2D list using loop // and print each element public static <K> void iterateUsingForEach(List<List<K> > listOfLists) { // Iterate the 2D list // and print each element System.out.println("["); for (List<K> list : listOfLists) { System.out.print(" ["); for (K item : list) { System.out.print(" " + item + ", "); } System.out.println("], "); } System.out.println("]"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingForEach(listOfLists); }} Output: [ [ 5, 10, ], [ 1, ], [ 20, 30, 40, ], ] Iterating over the list of lists using iterator:Get the 2D list to the iteratedWe need two iterators to iterate the 2D list successfully.The first iterator will iterate each row of the 2D lists as a separate listIterator listOfListsIterator = listOfLists.iterator(); Each row of the 2D list can be obtained with the help of next() method of IteratorlistOfListsIterator.next(); But the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list.list = (List)listOfListsIterator.next(); The second iterator will iterate each item of the list in each row separatelyIterator eachListIterator = list.iterator(); Hence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using iterator import java.util.*; class List_of_list { // Iterate the 2D list using Iterator // and print each element public static <K> void iterateUsingIterator(List<List<K> > listOfLists) { // Iterator for the 2D list Iterator listOfListsIterator = listOfLists.iterator(); System.out.println("["); while (listOfListsIterator.hasNext()) { // Type cast next() method // to convert from Object to List<K> List<K> list = new ArrayList<K>(); list = (List<K>)listOfListsIterator.next(); // Iterator for list Iterator eachListIterator = list.iterator(); System.out.print(" ["); while (eachListIterator.hasNext()) { System.out.print( " " + eachListIterator.next() + ", "); } System.out.println("], "); } System.out.println("]"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingIterator(listOfLists); }}Output:[ [ 5, 10, ], [ 1, ], [ 20, 30, 40, ], ] Get the 2D list to the iterated We need two iterators to iterate the 2D list successfully. The first iterator will iterate each row of the 2D lists as a separate listIterator listOfListsIterator = listOfLists.iterator(); Iterator listOfListsIterator = listOfLists.iterator(); Each row of the 2D list can be obtained with the help of next() method of IteratorlistOfListsIterator.next(); But the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list.list = (List)listOfListsIterator.next(); listOfListsIterator.next(); But the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list. list = (List)listOfListsIterator.next(); The second iterator will iterate each item of the list in each row separatelyIterator eachListIterator = list.iterator(); Iterator eachListIterator = list.iterator(); Hence we can do any operation on this item. Here we are printing the item. Below is the implementation of the above approach: // Java code to demonstrate the concept of// list of lists using iterator import java.util.*; class List_of_list { // Iterate the 2D list using Iterator // and print each element public static <K> void iterateUsingIterator(List<List<K> > listOfLists) { // Iterator for the 2D list Iterator listOfListsIterator = listOfLists.iterator(); System.out.println("["); while (listOfListsIterator.hasNext()) { // Type cast next() method // to convert from Object to List<K> List<K> list = new ArrayList<K>(); list = (List<K>)listOfListsIterator.next(); // Iterator for list Iterator eachListIterator = list.iterator(); System.out.print(" ["); while (eachListIterator.hasNext()) { System.out.print( " " + eachListIterator.next() + ", "); } System.out.println("], "); } System.out.println("]"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingIterator(listOfLists); }} Output: [ [ 5, 10, ], [ 1, ], [ 20, 30, 40, ], ] Java-Iterator java-list Traversal Java Java Traversal 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 Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Mar, 2020" }, { "code": null, "e": 90, "s": 28, "text": "Given a 2D list, the task is to iterate this 2D list in Java." }, { "code": null, "e": 195, "s": 90, "text": "2D list (list of lists)The 2D list refers to a list of lists, i.e. each row of the list is another list." }, { "code": null, "e": 235, "s": 195, "text": "[\n [5, 10],\n [1], \n [20, 30, 40]\n] \n" }, { "code": null, "e": 315, "s": 235, "text": "Iterate a 2D list: There are two ways of iterating over a list of list in Java." }, { "code": null, "e": 5010, "s": 315, "text": "Iterating over the list of lists using loop:Get the 2D list to the iteratedWe need two for-each loops to iterate the 2D list successfully.In the first for-each loop, each row of the 2D lists will be taken as a separate listfor (List list : listOfLists)\n { }\nIn the second for-each loop, each item of the list in each row will be taken separatelyfor (K item : list)\n { }\nHence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using loop import java.util.*;public class List_of_list { // Iterate the 2D list using loop // and print each element public static <K> void iterateUsingForEach(List<List<K> > listOfLists) { // Iterate the 2D list // and print each element System.out.println(\"[\"); for (List<K> list : listOfLists) { System.out.print(\" [\"); for (K item : list) { System.out.print(\" \" + item + \", \"); } System.out.println(\"], \"); } System.out.println(\"]\"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingForEach(listOfLists); }}Output:[\n [ 5, 10, ], \n [ 1, ], \n [ 20, 30, 40, ], \n]\nIterating over the list of lists using iterator:Get the 2D list to the iteratedWe need two iterators to iterate the 2D list successfully.The first iterator will iterate each row of the 2D lists as a separate listIterator listOfListsIterator = listOfLists.iterator();\nEach row of the 2D list can be obtained with the help of next() method of IteratorlistOfListsIterator.next();\nBut the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list.list = (List)listOfListsIterator.next();\nThe second iterator will iterate each item of the list in each row separatelyIterator eachListIterator = list.iterator();\nHence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using iterator import java.util.*; class List_of_list { // Iterate the 2D list using Iterator // and print each element public static <K> void iterateUsingIterator(List<List<K> > listOfLists) { // Iterator for the 2D list Iterator listOfListsIterator = listOfLists.iterator(); System.out.println(\"[\"); while (listOfListsIterator.hasNext()) { // Type cast next() method // to convert from Object to List<K> List<K> list = new ArrayList<K>(); list = (List<K>)listOfListsIterator.next(); // Iterator for list Iterator eachListIterator = list.iterator(); System.out.print(\" [\"); while (eachListIterator.hasNext()) { System.out.print( \" \" + eachListIterator.next() + \", \"); } System.out.println(\"], \"); } System.out.println(\"]\"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingIterator(listOfLists); }}Output:[\n [ 5, 10, ], \n [ 1, ], \n [ 20, 30, 40, ], \n]\n" }, { "code": null, "e": 7023, "s": 5010, "text": "Iterating over the list of lists using loop:Get the 2D list to the iteratedWe need two for-each loops to iterate the 2D list successfully.In the first for-each loop, each row of the 2D lists will be taken as a separate listfor (List list : listOfLists)\n { }\nIn the second for-each loop, each item of the list in each row will be taken separatelyfor (K item : list)\n { }\nHence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using loop import java.util.*;public class List_of_list { // Iterate the 2D list using loop // and print each element public static <K> void iterateUsingForEach(List<List<K> > listOfLists) { // Iterate the 2D list // and print each element System.out.println(\"[\"); for (List<K> list : listOfLists) { System.out.print(\" [\"); for (K item : list) { System.out.print(\" \" + item + \", \"); } System.out.println(\"], \"); } System.out.println(\"]\"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingForEach(listOfLists); }}Output:[\n [ 5, 10, ], \n [ 1, ], \n [ 20, 30, 40, ], \n]\n" }, { "code": null, "e": 7055, "s": 7023, "text": "Get the 2D list to the iterated" }, { "code": null, "e": 7119, "s": 7055, "text": "We need two for-each loops to iterate the 2D list successfully." }, { "code": null, "e": 7240, "s": 7119, "text": "In the first for-each loop, each row of the 2D lists will be taken as a separate listfor (List list : listOfLists)\n { }\n" }, { "code": null, "e": 7276, "s": 7240, "text": "for (List list : listOfLists)\n { }\n" }, { "code": null, "e": 7389, "s": 7276, "text": "In the second for-each loop, each item of the list in each row will be taken separatelyfor (K item : list)\n { }\n" }, { "code": null, "e": 7415, "s": 7389, "text": "for (K item : list)\n { }\n" }, { "code": null, "e": 7490, "s": 7415, "text": "Hence we can do any operation on this item. Here we are printing the item." }, { "code": null, "e": 7541, "s": 7490, "text": "Below is the implementation of the above approach:" }, { "code": "// Java code to demonstrate the concept of// list of lists using loop import java.util.*;public class List_of_list { // Iterate the 2D list using loop // and print each element public static <K> void iterateUsingForEach(List<List<K> > listOfLists) { // Iterate the 2D list // and print each element System.out.println(\"[\"); for (List<K> list : listOfLists) { System.out.print(\" [\"); for (K item : list) { System.out.print(\" \" + item + \", \"); } System.out.println(\"], \"); } System.out.println(\"]\"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingForEach(listOfLists); }}", "e": 9003, "s": 7541, "text": null }, { "code": null, "e": 9011, "s": 9003, "text": "Output:" }, { "code": null, "e": 9062, "s": 9011, "text": "[\n [ 5, 10, ], \n [ 1, ], \n [ 20, 30, 40, ], \n]\n" }, { "code": null, "e": 11745, "s": 9062, "text": "Iterating over the list of lists using iterator:Get the 2D list to the iteratedWe need two iterators to iterate the 2D list successfully.The first iterator will iterate each row of the 2D lists as a separate listIterator listOfListsIterator = listOfLists.iterator();\nEach row of the 2D list can be obtained with the help of next() method of IteratorlistOfListsIterator.next();\nBut the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list.list = (List)listOfListsIterator.next();\nThe second iterator will iterate each item of the list in each row separatelyIterator eachListIterator = list.iterator();\nHence we can do any operation on this item. Here we are printing the item.Below is the implementation of the above approach:// Java code to demonstrate the concept of// list of lists using iterator import java.util.*; class List_of_list { // Iterate the 2D list using Iterator // and print each element public static <K> void iterateUsingIterator(List<List<K> > listOfLists) { // Iterator for the 2D list Iterator listOfListsIterator = listOfLists.iterator(); System.out.println(\"[\"); while (listOfListsIterator.hasNext()) { // Type cast next() method // to convert from Object to List<K> List<K> list = new ArrayList<K>(); list = (List<K>)listOfListsIterator.next(); // Iterator for list Iterator eachListIterator = list.iterator(); System.out.print(\" [\"); while (eachListIterator.hasNext()) { System.out.print( \" \" + eachListIterator.next() + \", \"); } System.out.println(\"], \"); } System.out.println(\"]\"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingIterator(listOfLists); }}Output:[\n [ 5, 10, ], \n [ 1, ], \n [ 20, 30, 40, ], \n]\n" }, { "code": null, "e": 11777, "s": 11745, "text": "Get the 2D list to the iterated" }, { "code": null, "e": 11836, "s": 11777, "text": "We need two iterators to iterate the 2D list successfully." }, { "code": null, "e": 11967, "s": 11836, "text": "The first iterator will iterate each row of the 2D lists as a separate listIterator listOfListsIterator = listOfLists.iterator();\n" }, { "code": null, "e": 12023, "s": 11967, "text": "Iterator listOfListsIterator = listOfLists.iterator();\n" }, { "code": null, "e": 12296, "s": 12023, "text": "Each row of the 2D list can be obtained with the help of next() method of IteratorlistOfListsIterator.next();\nBut the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list.list = (List)listOfListsIterator.next();\n" }, { "code": null, "e": 12325, "s": 12296, "text": "listOfListsIterator.next();\n" }, { "code": null, "e": 12447, "s": 12325, "text": "But the next() method returns the Iterator as an Object’s object. Hence we need to cast this returned object into a list." }, { "code": null, "e": 12489, "s": 12447, "text": "list = (List)listOfListsIterator.next();\n" }, { "code": null, "e": 12612, "s": 12489, "text": "The second iterator will iterate each item of the list in each row separatelyIterator eachListIterator = list.iterator();\n" }, { "code": null, "e": 12658, "s": 12612, "text": "Iterator eachListIterator = list.iterator();\n" }, { "code": null, "e": 12733, "s": 12658, "text": "Hence we can do any operation on this item. Here we are printing the item." }, { "code": null, "e": 12784, "s": 12733, "text": "Below is the implementation of the above approach:" }, { "code": "// Java code to demonstrate the concept of// list of lists using iterator import java.util.*; class List_of_list { // Iterate the 2D list using Iterator // and print each element public static <K> void iterateUsingIterator(List<List<K> > listOfLists) { // Iterator for the 2D list Iterator listOfListsIterator = listOfLists.iterator(); System.out.println(\"[\"); while (listOfListsIterator.hasNext()) { // Type cast next() method // to convert from Object to List<K> List<K> list = new ArrayList<K>(); list = (List<K>)listOfListsIterator.next(); // Iterator for list Iterator eachListIterator = list.iterator(); System.out.print(\" [\"); while (eachListIterator.hasNext()) { System.out.print( \" \" + eachListIterator.next() + \", \"); } System.out.println(\"], \"); } System.out.println(\"]\"); } // Driver code public static void main(String[] args) { // List of Lists ArrayList<List<Integer> > listOfLists = new ArrayList<List<Integer> >(); // Create N lists one by one // and append to the list of lists List<Integer> list1 = new ArrayList<Integer>(); list1.add(5); list1.add(10); listOfLists.add(list1); List<Integer> list2 = new ArrayList<Integer>(); list2.add(1); listOfLists.add(list2); List<Integer> list3 = new ArrayList<Integer>(); list3.add(20); list3.add(30); list3.add(40); listOfLists.add(list3); // Iterate the 2D list iterateUsingIterator(listOfLists); }}", "e": 14625, "s": 12784, "text": null }, { "code": null, "e": 14633, "s": 14625, "text": "Output:" }, { "code": null, "e": 14684, "s": 14633, "text": "[\n [ 5, 10, ], \n [ 1, ], \n [ 20, 30, 40, ], \n]\n" }, { "code": null, "e": 14698, "s": 14684, "text": "Java-Iterator" }, { "code": null, "e": 14708, "s": 14698, "text": "java-list" }, { "code": null, "e": 14718, "s": 14708, "text": "Traversal" }, { "code": null, "e": 14723, "s": 14718, "text": "Java" }, { "code": null, "e": 14728, "s": 14723, "text": "Java" }, { "code": null, "e": 14738, "s": 14728, "text": "Traversal" }, { "code": null, "e": 14836, "s": 14738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14851, "s": 14836, "text": "Stream In Java" }, { "code": null, "e": 14872, "s": 14851, "text": "Introduction to Java" }, { "code": null, "e": 14893, "s": 14872, "text": "Constructors in Java" }, { "code": null, "e": 14912, "s": 14893, "text": "Exceptions in Java" }, { "code": null, "e": 14929, "s": 14912, "text": "Generics in Java" }, { "code": null, "e": 14959, "s": 14929, "text": "Functional Interfaces in Java" }, { "code": null, "e": 14985, "s": 14959, "text": "Java Programming Examples" }, { "code": null, "e": 15001, "s": 14985, "text": "Strings in Java" }, { "code": null, "e": 15038, "s": 15001, "text": "Differences between JDK, JRE and JVM" } ]
Perfect Sum Problem | Practice | GeeksforGeeks
Given an array arr[] of non-negative integers and an integer sum, the task is to count all subsets of the given array with a sum equal to a given sum. Note: Answer can be very large, so, output answer modulo 109+7 Example 1: Input: N = 6, arr[] = {2, 3, 5, 6, 8, 10} sum = 10 Output: 3 Explanation: {2, 3, 5}, {2, 8}, {10} Input: N = 5, arr[] = {1, 2, 3, 4, 5} sum = 10 Output: 3 Explanation: {1, 2, 3, 4}, {1, 4, 5}, {2, 3, 5} 0 shiva109013 hours ago int mod = (int)(1e9 + 7); int count(int arr[],int n,int sum,vector<vector<int>>&dp){ if(sum == 0 && n == 0)return 1; if(sum < 0 || n <= 0)return 0; if(dp[n][sum] != -1)return dp[n][sum]%mod; return dp[n][sum] = (count(arr,n - 1,sum - arr[n - 1],dp)%mod + count(arr,n- 1,sum,dp)%mod)%mod; } int perfectSum(int arr[], int n, int sum) { // Your code goes here vector<vector<int>> dp(n+1,vector<int>(sum+1,-1)); return count(arr,n,sum,dp)%mod; } 0 akkeshri1404200114 hours ago int perfectSum(int arr[], int n, int sum) { // Your code goes here int mod=1e9+7; vector<vector<int>>dp(n+1,vector<int>(sum+1)); for(int i=0;i<n+1;i++){ for(int j=0;j<sum+1;j++){ if(i==0){ dp[i][j]=0; } else if(j==0){ dp[i][j]=1; } } } dp[0][0]=1; for(int i=1;i<n+1;i++){ for(int j=0;j<sum+1;j++){ if(j>=arr[i-1]){ dp[i][j]=(dp[i-1][j]+dp[i-1][j-arr[i-1]])%mod; } else{ dp[i][j]=dp[i-1][j]%mod; } } } return dp[n][sum]; } +1 shrishmishra1 day ago Someone Please figure out error in my code. public: int mod=1000000007;int perfectSum(int arr[], int n, int sum){ int t[n+1][sum+1]; for(int i=0;i<=n;i++) { t[i][0]=1; } for(int j=1;j<=sum;j++) { t[0][j]=0; } for(int i=1;i<=n;i++) { for(int j=1;i<=sum;j++) { if(arr[i-1]>j) { t[i][j]=t[i-1][j]%mod; } else{ t[i][j]=(t[i-1][j]%mod+t[i-1][j-arr[i-1]]%mod)%mod; } } } return (t[n][sum]); } +1 cyrusthapa2 days ago Both recursive + bottom up public: int mod = (int)(1e9 + 7); int count(int arr[],int n,int sum,vector<vector<int>>&dp){ if(sum == 0 && n == 0)return 1; if(sum < 0 || n <= 0)return 0; if(dp[n][sum] != -1)return dp[n][sum]%mod; return dp[n][sum] = (count(arr,n - 1,sum - arr[n - 1],dp)%mod + count(arr,n- 1,sum,dp)%mod)%mod; } int perfectSum(int arr[], int n, int sum){ vector<vector<int>>dp(n + 1, vector<int>(sum + 1,0)); // return count(arr,n,sum,dp)%mod; for(int i = 0 ;i <= n;i++) dp[i][ 0 ] = 1; for(int i = 1 ;i <= n;i++){ for(int summ = 0 ;summ <= sum ;summ++){ dp[i][summ] = dp[i - 1][summ]%mod; if( summ >= arr[i - 1] ) dp[i][summ] = (dp[i][summ]%mod + dp[i - 1][summ - arr[i - 1]]%mod)%mod; } } return dp[n][sum]%mod; } 0 ramanbansal98762 days ago Please find out the mistake in my code.int perfectSum(int arr[], int n, int sum){ int dp[sum+1][n+1]; for(int i=0;i<=sum;i++){ for(int j=0;j<=n;j++){ if(i==0 && j==0){ dp[i][j] = 1; } else if(i==0 && j!=0){ dp[i][j] = 1; } else if(i!=0 && j==0){ dp[i][j] = 0; } else{ if(i>=arr[j-1]){ dp[i][j] = dp[i-arr[j-1]][j-1] + dp[i][j-1]; } else{ dp[i][j] = dp[i][j-1]; } } } } return dp[sum][n];} +1 soumya1107993 days ago dp = [[-1 for i in range(1001)] for j in range(1001)] def subset_sum_K_count(arr, target, n): mod= 1000000009 if n== 0: if target == 0: return 1 else: return 0 if dp[n][target] != -1: return dp[n][target] if arr[n-1] <= target: return subset_sum_K_count(arr, target - arr[n-1], n-1)%mod + subset_sum_K_count(arr, target, n-1)%mod else: return subset_sum_K_count(arr, target, n-1)%mod 0 mitashiv01013 days ago Memoization and Tabular method both int m=1000000007;//memoization methodint perfect(int arr[],int n,int sum,vector<vector<int>>&dp){ // if(sum==0)return 1; if(n==0){ // if(sum==arr[0])return 1; if(sum==0&&arr[0]==0)return 2; if(sum==0||arr[0]==sum)return 1; return 0; } if(dp[n][sum]!=-1)return dp[n][sum]; if(sum>=arr[n])return dp[n][sum] = (perfect(arr,n-1,sum-arr[n],dp)%m+perfect(arr,n-1,sum,dp)%m)%m; else return dp[n][sum] = perfect(arr,n-1,sum,dp)%m; }int perfectSum(int arr[], int n, int sum){ // Your code goes here vector<vector<int>>dp(n+1,vector<int>(sum+1,-1)); // table method for(int i=0;i<=n;i++){ for(int j=0;j<=sum;j++){ if(i==0 && j==0)dp[i][j]=1; else if(i==0 && j!=0) dp[i][j]=0; else if(j>=arr[i-1])dp[i][j] = ((dp[i-1][j-arr[i-1]])%m+dp[i-1][j]%m)%m; else dp[i][j] = dp[i-1][j]%m; } } return dp[n][sum]; // to call memoization/recursion function // memset(dp,-1,sizeof(dp)); // return perfect(arr,n-1,sum,dp)%m; } +1 chessnoobdj4 days ago C++ dp space optimization int perfectSum(int arr[], int n, int sum) { int dp[sum+1] = {0}, mod = 1e9+7; dp[0] = 1; for(int i=0; i<n; i++){ for(int j=sum; j>=0; j--){ if(j-arr[i] >= 0) dp[j] = (dp[j]+dp[j-arr[i]])%mod; } } return dp[sum]; } 0 aditya_njr4 days ago // memo int m = 1000000007; int solve(int arr[], int sum, int ind, vector<vector<int>>&t) { if(ind == 0){ if(sum==0 && arr[0]==0) return 2; if(sum==0 || sum == arr[0]) return 1; return 0; } if (t[ind][sum] != -1) { return t[ind][sum] % m; } int notTake = solve(arr, sum, ind - 1, t) % m; int take = 0; if (arr[ind] <= sum) { take = solve(arr, sum - arr[ind], ind - 1, t) % m; } return t[ind][sum] = (take + notTake) % m; } int perfectSum(int arr[], int n, int sum) { vector<vector<int>>t(n, vector<int>(sum + 1, -1)); return solve(arr, sum, n-1, t); } +1 dajulal5 days ago //dp bottom up int perfectSum(int arr[], int n, int sum){ // Your code goes here int mod=1000000007; int t[n+1][sum+1]; t[0][0] = 1; for (int i = 1; i <= sum; i++) t[0][i] = 0; for(int i=1;i<=n;i++){ for(int j=0;j<=sum;j++){ if(arr[i-1]<=j){ t[i][j] = (t[i-1][j]%mod + t[i-1][j-arr[i-1]]%mod)%mod; } else{ t[i][j] = t[i-1][j]%mod; } } } return t[n][sum];} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 389, "s": 238, "text": "Given an array arr[] of non-negative integers and an integer sum, the task is to count all subsets of the given array with a sum equal to a given sum." }, { "code": null, "e": 452, "s": 389, "text": "Note: Answer can be very large, so, output answer modulo 109+7" }, { "code": null, "e": 463, "s": 452, "text": "Example 1:" }, { "code": null, "e": 568, "s": 463, "text": "Input: N = 6, arr[] = {2, 3, 5, 6, 8, 10}\n sum = 10\nOutput: 3\nExplanation: {2, 3, 5}, {2, 8}, {10}" }, { "code": null, "e": 694, "s": 568, "text": "Input: N = 5, arr[] = {1, 2, 3, 4, 5}\n sum = 10\nOutput: 3\nExplanation: {1, 2, 3, 4}, {1, 4, 5}, \n {2, 3, 5}" }, { "code": null, "e": 696, "s": 694, "text": "0" }, { "code": null, "e": 718, "s": 696, "text": "shiva109013 hours ago" }, { "code": null, "e": 1254, "s": 718, "text": "int mod = (int)(1e9 + 7);\nint count(int arr[],int n,int sum,vector<vector<int>>&dp){\n\t if(sum == 0 && n == 0)return 1;\n\t if(sum < 0 || n <= 0)return 0;\n\t \n\t if(dp[n][sum] != -1)return dp[n][sum]%mod;\n\t \n\t return dp[n][sum] = (count(arr,n - 1,sum - arr[n - 1],dp)%mod\n\t + count(arr,n- 1,sum,dp)%mod)%mod;\n}\nint perfectSum(int arr[], int n, int sum)\n{\n // Your code goes here\n vector<vector<int>> dp(n+1,vector<int>(sum+1,-1));\n \n return count(arr,n,sum,dp)%mod;\n}" }, { "code": null, "e": 1256, "s": 1254, "text": "0" }, { "code": null, "e": 1285, "s": 1256, "text": "akkeshri1404200114 hours ago" }, { "code": null, "e": 2018, "s": 1285, "text": "int perfectSum(int arr[], int n, int sum)\n{\n // Your code goes here\n int mod=1e9+7;\n vector<vector<int>>dp(n+1,vector<int>(sum+1));\n for(int i=0;i<n+1;i++){\n for(int j=0;j<sum+1;j++){\n if(i==0){\n dp[i][j]=0;\n }\n else if(j==0){\n dp[i][j]=1;\n }\n }\n }\n dp[0][0]=1;\n for(int i=1;i<n+1;i++){\n for(int j=0;j<sum+1;j++){\n if(j>=arr[i-1]){\n dp[i][j]=(dp[i-1][j]+dp[i-1][j-arr[i-1]])%mod;\n }\n else{\n dp[i][j]=dp[i-1][j]%mod;\n }\n }\n }\n return dp[n][sum];\n \n}" }, { "code": null, "e": 2021, "s": 2018, "text": "+1" }, { "code": null, "e": 2043, "s": 2021, "text": "shrishmishra1 day ago" }, { "code": null, "e": 2087, "s": 2043, "text": "Someone Please figure out error in my code." }, { "code": null, "e": 2095, "s": 2087, "text": "public:" }, { "code": null, "e": 2626, "s": 2095, "text": "int mod=1000000007;int perfectSum(int arr[], int n, int sum){ int t[n+1][sum+1]; for(int i=0;i<=n;i++) { t[i][0]=1; } for(int j=1;j<=sum;j++) { t[0][j]=0; } for(int i=1;i<=n;i++) { for(int j=1;i<=sum;j++) { if(arr[i-1]>j) { t[i][j]=t[i-1][j]%mod; } else{ t[i][j]=(t[i-1][j]%mod+t[i-1][j-arr[i-1]]%mod)%mod; } } } return (t[n][sum]); }" }, { "code": null, "e": 2629, "s": 2626, "text": "+1" }, { "code": null, "e": 2650, "s": 2629, "text": "cyrusthapa2 days ago" }, { "code": null, "e": 2677, "s": 2650, "text": "Both recursive + bottom up" }, { "code": null, "e": 3552, "s": 2677, "text": "public:\n\tint mod = (int)(1e9 + 7);\n\tint count(int arr[],int n,int sum,vector<vector<int>>&dp){\n\t if(sum == 0 && n == 0)return 1;\n\t if(sum < 0 || n <= 0)return 0;\n\t \n\t if(dp[n][sum] != -1)return dp[n][sum]%mod;\n\t \n\t return dp[n][sum] = (count(arr,n - 1,sum - arr[n - 1],dp)%mod\n\t + count(arr,n- 1,sum,dp)%mod)%mod;\n\t}\n\tint perfectSum(int arr[], int n, int sum){\n\t \n\t vector<vector<int>>dp(n + 1, vector<int>(sum + 1,0));\n\t // return count(arr,n,sum,dp)%mod;\n\t \n\t for(int i = 0 ;i <= n;i++)\n\t dp[i][ 0 ] = 1;\n\t \n\t for(int i = 1 ;i <= n;i++){\n\t for(int summ = 0 ;summ <= sum ;summ++){\n\t dp[i][summ] = dp[i - 1][summ]%mod;\n\t if( summ >= arr[i - 1] )\n\t dp[i][summ] = (dp[i][summ]%mod + dp[i - 1][summ - arr[i - 1]]%mod)%mod;\n\t }\n\t }\n\t \n\t \n\t return dp[n][sum]%mod;\n\t}" }, { "code": null, "e": 3554, "s": 3552, "text": "0" }, { "code": null, "e": 3580, "s": 3554, "text": "ramanbansal98762 days ago" }, { "code": null, "e": 4325, "s": 3580, "text": "Please find out the mistake in my code.int perfectSum(int arr[], int n, int sum){ int dp[sum+1][n+1]; for(int i=0;i<=sum;i++){ for(int j=0;j<=n;j++){ if(i==0 && j==0){ dp[i][j] = 1; } else if(i==0 && j!=0){ dp[i][j] = 1; } else if(i!=0 && j==0){ dp[i][j] = 0; } else{ if(i>=arr[j-1]){ dp[i][j] = dp[i-arr[j-1]][j-1] + dp[i][j-1]; } else{ dp[i][j] = dp[i][j-1]; } } } } return dp[sum][n];}" }, { "code": null, "e": 4328, "s": 4325, "text": "+1" }, { "code": null, "e": 4351, "s": 4328, "text": "soumya1107993 days ago" }, { "code": null, "e": 4405, "s": 4351, "text": "dp = [[-1 for i in range(1001)] for j in range(1001)]" }, { "code": null, "e": 4843, "s": 4405, "text": "def subset_sum_K_count(arr, target, n): mod= 1000000009 if n== 0: if target == 0: return 1 else: return 0 if dp[n][target] != -1: return dp[n][target] if arr[n-1] <= target: return subset_sum_K_count(arr, target - arr[n-1], n-1)%mod + subset_sum_K_count(arr, target, n-1)%mod else: return subset_sum_K_count(arr, target, n-1)%mod" }, { "code": null, "e": 4845, "s": 4843, "text": "0" }, { "code": null, "e": 4868, "s": 4845, "text": "mitashiv01013 days ago" }, { "code": null, "e": 4905, "s": 4868, "text": "Memoization and Tabular method both " }, { "code": null, "e": 6053, "s": 4907, "text": " int m=1000000007;//memoization methodint perfect(int arr[],int n,int sum,vector<vector<int>>&dp){ // if(sum==0)return 1; if(n==0){ // if(sum==arr[0])return 1; if(sum==0&&arr[0]==0)return 2; if(sum==0||arr[0]==sum)return 1; return 0; } if(dp[n][sum]!=-1)return dp[n][sum]; if(sum>=arr[n])return dp[n][sum] = (perfect(arr,n-1,sum-arr[n],dp)%m+perfect(arr,n-1,sum,dp)%m)%m; else return dp[n][sum] = perfect(arr,n-1,sum,dp)%m; }int perfectSum(int arr[], int n, int sum){ // Your code goes here vector<vector<int>>dp(n+1,vector<int>(sum+1,-1)); // table method for(int i=0;i<=n;i++){ for(int j=0;j<=sum;j++){ if(i==0 && j==0)dp[i][j]=1; else if(i==0 && j!=0) dp[i][j]=0; else if(j>=arr[i-1])dp[i][j] = ((dp[i-1][j-arr[i-1]])%m+dp[i-1][j]%m)%m; else dp[i][j] = dp[i-1][j]%m; } } return dp[n][sum]; // to call memoization/recursion function // memset(dp,-1,sizeof(dp)); // return perfect(arr,n-1,sum,dp)%m; }" }, { "code": null, "e": 6056, "s": 6053, "text": "+1" }, { "code": null, "e": 6078, "s": 6056, "text": "chessnoobdj4 days ago" }, { "code": null, "e": 6104, "s": 6078, "text": "C++ dp space optimization" }, { "code": null, "e": 6393, "s": 6104, "text": "int perfectSum(int arr[], int n, int sum)\n\t{\n\t int dp[sum+1] = {0}, mod = 1e9+7;\n\t dp[0] = 1;\n\t for(int i=0; i<n; i++){\n\t for(int j=sum; j>=0; j--){\n\t if(j-arr[i] >= 0)\n\t dp[j] = (dp[j]+dp[j-arr[i]])%mod;\n\t }\n\t }\n\t return dp[sum];\n\t}" }, { "code": null, "e": 6395, "s": 6393, "text": "0" }, { "code": null, "e": 6416, "s": 6395, "text": "aditya_njr4 days ago" }, { "code": null, "e": 6424, "s": 6416, "text": "// memo" }, { "code": null, "e": 7050, "s": 6424, "text": "int m = 1000000007; int solve(int arr[], int sum, int ind, vector<vector<int>>&t) { if(ind == 0){ if(sum==0 && arr[0]==0) return 2; if(sum==0 || sum == arr[0]) return 1; return 0; } if (t[ind][sum] != -1) { return t[ind][sum] % m; } int notTake = solve(arr, sum, ind - 1, t) % m; int take = 0; if (arr[ind] <= sum) { take = solve(arr, sum - arr[ind], ind - 1, t) % m; } return t[ind][sum] = (take + notTake) % m; } int perfectSum(int arr[], int n, int sum) { vector<vector<int>>t(n, vector<int>(sum + 1, -1)); return solve(arr, sum, n-1, t); }" }, { "code": null, "e": 7053, "s": 7050, "text": "+1" }, { "code": null, "e": 7071, "s": 7053, "text": "dajulal5 days ago" }, { "code": null, "e": 7086, "s": 7071, "text": "//dp bottom up" }, { "code": null, "e": 7599, "s": 7086, "text": "int perfectSum(int arr[], int n, int sum){ // Your code goes here int mod=1000000007; int t[n+1][sum+1]; t[0][0] = 1; for (int i = 1; i <= sum; i++) t[0][i] = 0; for(int i=1;i<=n;i++){ for(int j=0;j<=sum;j++){ if(arr[i-1]<=j){ t[i][j] = (t[i-1][j]%mod + t[i-1][j-arr[i-1]]%mod)%mod; } else{ t[i][j] = t[i-1][j]%mod; } } } return t[n][sum];} " }, { "code": null, "e": 7745, "s": 7599, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7781, "s": 7745, "text": " Login to access your submissions. " }, { "code": null, "e": 7791, "s": 7781, "text": "\nProblem\n" }, { "code": null, "e": 7801, "s": 7791, "text": "\nContest\n" }, { "code": null, "e": 7864, "s": 7801, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8049, "s": 7864, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8333, "s": 8049, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 8479, "s": 8333, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 8556, "s": 8479, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 8597, "s": 8556, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 8625, "s": 8597, "text": "Disable browser extensions." }, { "code": null, "e": 8696, "s": 8625, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8883, "s": 8696, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
JavaScript Array findIndex() Method
10 Jun, 2022 This article will help us to understand all the facts as well as required information in detail along with the implementation of the Array.findIndex() Method. Let us start with an example of the method Array findIndex() which is used to find the first index of positive number from an array. Example: JavaScript <script> // input array contain some elements. var array = [-10, -0.20, 0.30, -40, -50]; // function (return element > 0). var found = array.findIndex(function (element) { return element > 0; }); // Printing desired values. document.write(found);</script> Output: 2 The Array.findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by user while calling). Otherwise, if no data is found then value of -1 is returned. It does not execute the method once it finds an element satisfying the testing method. It does not change the original array. Syntax: array.findIndex(function(currentValue, index, arr), thisValue) Parameters: This method accepts five parameters as mentioned above and described below: function: It is the function of the array that works on each element. currentValue: This parameter holds the current element. index: It is an optional parameter that holds the index of the current element. arr: It is an optional parameter that holds the array object the current element belongs to. thisValue: This parameter is optional, if a value to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value. Return value: It returns the array element index if any of the elements in the array pass the test, otherwise, it returns -1. Below examples illustrate the Array findIndex() function in JavaScript: Example 1: In this example the method findIndex() finds all the indices that contain odd numbers. Since no odd numbers are present therefore it returns -1. function isOdd(element, index, array) { return (element%2 == 1); } print([4, 6, 8, 12].findIndex(isOdd)); Output: -1 Example 2: In this example the method findIndex() finds all the indices that contain odd numbers. Since 7 is odd number therefore it returns its index . function isOdd(element, index, array) { return (element%2 == 1); } print([4, 6, 7, 12].findIndex(isOdd)); Output: 2 Codes for the above function are defined as follows: Program 1: html <script> // Input array contain elements var array = [10, 20, 30, 110, 60]; // Testing method (element > 25). function finding_index(element) { return element > 25; } // Printing the index of element which is satisfies document.write(array.findIndex(finding_index));</script> Output: 2 Program 2: JavaScript <script> // Number is prime or not prime. function isPrime(n) { if (n === 1) { return false; } else if (n === 2) { return true; } else { for (var x = 2; x < n; x++) { if (n % x === 0) { return false; } } return true; } } // Printing -1 because prime number is not found. document.write([4, 6, 8, 12].findIndex(isPrime)); document.write("<br />") // Printing 2 the index of prime number (7) found. document.write([4, 6, 7, 12].findIndex(isPrime));</script> Output: -1 2 Example-3: In this example we will use arrow functions to find out the index of an element from an array. Javascript let fruits_array = ["apple", "banana", "mango", "banana", "grapes"]; let searching_index = fruits_array.findIndex(fruit => fruit === "mango"); console.log(searching_index);console.log(fruits_array[searching_index]); Output: 2 mango Supported Browsers: The browsers supported by JavaScript Array findIndex() method are listed below: Google Chrome 45 Microsoft Edge 12.0 Mozilla Firefox 25.0 Safari 7.1 Opera 32.0 amansingla javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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 ?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2022" }, { "code": null, "e": 187, "s": 28, "text": "This article will help us to understand all the facts as well as required information in detail along with the implementation of the Array.findIndex() Method." }, { "code": null, "e": 320, "s": 187, "text": "Let us start with an example of the method Array findIndex() which is used to find the first index of positive number from an array." }, { "code": null, "e": 330, "s": 320, "text": "Example: " }, { "code": null, "e": 341, "s": 330, "text": "JavaScript" }, { "code": "<script> // input array contain some elements. var array = [-10, -0.20, 0.30, -40, -50]; // function (return element > 0). var found = array.findIndex(function (element) { return element > 0; }); // Printing desired values. document.write(found);</script> ", "e": 646, "s": 341, "text": null }, { "code": null, "e": 654, "s": 646, "text": "Output:" }, { "code": null, "e": 656, "s": 654, "text": "2" }, { "code": null, "e": 892, "s": 656, "text": "The Array.findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by user while calling). Otherwise, if no data is found then value of -1 is returned." }, { "code": null, "e": 979, "s": 892, "text": "It does not execute the method once it finds an element satisfying the testing method." }, { "code": null, "e": 1018, "s": 979, "text": "It does not change the original array." }, { "code": null, "e": 1026, "s": 1018, "text": "Syntax:" }, { "code": null, "e": 1089, "s": 1026, "text": "array.findIndex(function(currentValue, index, arr), thisValue)" }, { "code": null, "e": 1177, "s": 1089, "text": "Parameters: This method accepts five parameters as mentioned above and described below:" }, { "code": null, "e": 1247, "s": 1177, "text": "function: It is the function of the array that works on each element." }, { "code": null, "e": 1303, "s": 1247, "text": "currentValue: This parameter holds the current element." }, { "code": null, "e": 1383, "s": 1303, "text": "index: It is an optional parameter that holds the index of the current element." }, { "code": null, "e": 1476, "s": 1383, "text": "arr: It is an optional parameter that holds the array object the current element belongs to." }, { "code": null, "e": 1649, "s": 1476, "text": "thisValue: This parameter is optional, if a value to be passed to the function to be used as its “this” value else the value “undefined” will be passed as its “this” value." }, { "code": null, "e": 1847, "s": 1649, "text": "Return value: It returns the array element index if any of the elements in the array pass the test, otherwise, it returns -1. Below examples illustrate the Array findIndex() function in JavaScript:" }, { "code": null, "e": 2003, "s": 1847, "text": "Example 1: In this example the method findIndex() finds all the indices that contain odd numbers. Since no odd numbers are present therefore it returns -1." }, { "code": null, "e": 2113, "s": 2003, "text": "function isOdd(element, index, array) {\n return (element%2 == 1);\n}\n\nprint([4, 6, 8, 12].findIndex(isOdd)); " }, { "code": null, "e": 2121, "s": 2113, "text": "Output:" }, { "code": null, "e": 2124, "s": 2121, "text": "-1" }, { "code": null, "e": 2277, "s": 2124, "text": "Example 2: In this example the method findIndex() finds all the indices that contain odd numbers. Since 7 is odd number therefore it returns its index ." }, { "code": null, "e": 2387, "s": 2277, "text": "function isOdd(element, index, array) {\n return (element%2 == 1);\n}\n\nprint([4, 6, 7, 12].findIndex(isOdd)); " }, { "code": null, "e": 2395, "s": 2387, "text": "Output:" }, { "code": null, "e": 2397, "s": 2395, "text": "2" }, { "code": null, "e": 2451, "s": 2397, "text": "Codes for the above function are defined as follows: " }, { "code": null, "e": 2463, "s": 2451, "text": "Program 1: " }, { "code": null, "e": 2468, "s": 2463, "text": "html" }, { "code": "<script> // Input array contain elements var array = [10, 20, 30, 110, 60]; // Testing method (element > 25). function finding_index(element) { return element > 25; } // Printing the index of element which is satisfies document.write(array.findIndex(finding_index));</script>", "e": 2774, "s": 2468, "text": null }, { "code": null, "e": 2782, "s": 2774, "text": "Output:" }, { "code": null, "e": 2784, "s": 2782, "text": "2" }, { "code": null, "e": 2796, "s": 2784, "text": "Program 2: " }, { "code": null, "e": 2807, "s": 2796, "text": "JavaScript" }, { "code": "<script> // Number is prime or not prime. function isPrime(n) { if (n === 1) { return false; } else if (n === 2) { return true; } else { for (var x = 2; x < n; x++) { if (n % x === 0) { return false; } } return true; } } // Printing -1 because prime number is not found. document.write([4, 6, 8, 12].findIndex(isPrime)); document.write(\"<br />\") // Printing 2 the index of prime number (7) found. document.write([4, 6, 7, 12].findIndex(isPrime));</script>", "e": 3420, "s": 2807, "text": null }, { "code": null, "e": 3428, "s": 3420, "text": "Output:" }, { "code": null, "e": 3433, "s": 3428, "text": "-1\n2" }, { "code": null, "e": 3539, "s": 3433, "text": "Example-3: In this example we will use arrow functions to find out the index of an element from an array." }, { "code": null, "e": 3550, "s": 3539, "text": "Javascript" }, { "code": "let fruits_array = [\"apple\", \"banana\", \"mango\", \"banana\", \"grapes\"]; let searching_index = fruits_array.findIndex(fruit => fruit === \"mango\"); console.log(searching_index);console.log(fruits_array[searching_index]);", "e": 3767, "s": 3550, "text": null }, { "code": null, "e": 3775, "s": 3767, "text": "Output:" }, { "code": null, "e": 3783, "s": 3775, "text": "2\nmango" }, { "code": null, "e": 3883, "s": 3783, "text": "Supported Browsers: The browsers supported by JavaScript Array findIndex() method are listed below:" }, { "code": null, "e": 3900, "s": 3883, "text": "Google Chrome 45" }, { "code": null, "e": 3920, "s": 3900, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 3941, "s": 3920, "text": "Mozilla Firefox 25.0" }, { "code": null, "e": 3952, "s": 3941, "text": "Safari 7.1" }, { "code": null, "e": 3963, "s": 3952, "text": "Opera 32.0" }, { "code": null, "e": 3974, "s": 3963, "text": "amansingla" }, { "code": null, "e": 3991, "s": 3974, "text": "javascript-array" }, { "code": null, "e": 4010, "s": 3991, "text": "JavaScript-Methods" }, { "code": null, "e": 4021, "s": 4010, "text": "JavaScript" }, { "code": null, "e": 4038, "s": 4021, "text": "Web Technologies" }, { "code": null, "e": 4136, "s": 4038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4197, "s": 4136, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4269, "s": 4197, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4309, "s": 4269, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4350, "s": 4309, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4392, "s": 4350, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4454, "s": 4392, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4487, "s": 4454, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4548, "s": 4487, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4598, "s": 4548, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Apply Operations To Groups In Pandas
09 Mar, 2022 Prerequisites: Pandas Pandas is a Python library for data analysis and data manipulation. Often data analysis requires data to be broken into groups to perform various operations on these groups. The GroupBy function in Pandas employs the split-apply-combine strategy meaning it performs a combination of — splitting an object, applying functions to the object and combining the results. In this article, we will use the groupby() function to perform various operations on grouped data. Aggregation involves creating statistical summaries of data with methods such as mean, median, mode, min (minimum), max (maximum), std (standard deviation), var (variance), sum, count, etc. To perform the aggregation operation on groups: Import module Create or load data Create a GroupBy object which groups data along a key or multiple keys Apply a statistical operation. Example 1: Calculate the mean salaries and age of male and female groups. It gives the mean of numeric columns and adds a prefix to the column names. Python3 # Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({"dept": np.random.choice(["IT", "HR", "Sales", "Production"], size=50), "gender": np.random.choice(["F", "M"], size=50), "age": np.random.randint(22, 60, size=50), "salary": np.random.randint(20000, 90000, size=50)})df.index.name = "emp_id" # Calculate mean data of gender groupsdf.groupby('gender').mean().add_prefix('mean_') Output: Example 2: Performing multiple aggregate operations using the aggregate function (DataFrameGroupBy.agg) which accepts a string, function or a list of functions. Python3 # Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({"dept": np.random.choice(["IT", "HR", "Sales", "Production"], size=50), "gender": np.random.choice(["F", "M"], size=50), "age": np.random.randint(22, 60, size=50), "salary": np.random.randint(20000, 90000, size=50)})df.index.name = "emp_id" # Calculate min, max, mean and count of salaries# in different departments for males and femalesdf.groupby(['dept', 'gender'])['salary'].agg(["min", "max", "mean", "count"]) Output: Example 3: Specifying multiple columns and their corresponding aggregate operations as follows. Python3 # Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({"dept": np.random.choice(["IT", "HR", "Sales", "Production"], size=50), "gender": np.random.choice(["F", "M"], size=50), "age": np.random.randint(22, 60, size=50), "salary": np.random.randint(20000, 90000, size=50)})df.index.name = "emp_id" # Calculate mean salaries and min-max age of employees# in different departments for gender groupsdf.groupby(['dept', 'gender']).agg({'salary': 'mean', 'age': ['min', 'max']}) Output: Example 4: Display common statistics for any group. Python3 # Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({"dept": np.random.choice(["IT", "HR", "Sales", "Production"], size=50), "gender": np.random.choice(["F", "M"], size=50), "age": np.random.randint(22, 60, size=50), "salary": np.random.randint(20000, 90000, size=50)})df.index.name = "emp_id" # Statistics of employee age grouped by departmentsdf["age"].groupby(df['dept']).describe() Output: Create bins or groups and apply operations The cut method of Pandas sorts values into bin intervals creating groups or categories. Aggregation or other functions can then be performed on these groups. Implementation of this is shown below: Example : Age is divided into age ranges and the count of observations in the sample data is calculated. Python3 # Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({"dept": np.random.choice(["IT", "HR", "Sales", "Production"], size=50), "gender": np.random.choice(["F", "M"], size=50), "age": np.random.randint(22, 60, size=50), "salary": np.random.randint(20000, 90000, size=50)})df.index.name = "emp_id" # Create bin intervalsbins = [20, 30, 45, 60] # Segregate ages into bins of age groupsdf['categories'] = pd.cut(df['age'], bins, labels=['Young', 'Middle', 'Old']) # Calculate number of observations in each age categorydf['age'].groupby(df['categories']).count() Output: Transformation is performing a group-specific operation where the individual values are changed while the shape of the data remains same. We use the transform() function to do so. Example : Python3 # Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({"dept": np.random.choice(["IT", "HR", "Sales", "Production"], size=50), "gender": np.random.choice(["F", "M"], size=50), "age": np.random.randint(22, 60, size=50), "salary": np.random.randint(20000, 90000, size=50)})df.index.name = "emp_id" # Calculate mean difference by transforming each salary valuedf['mean_sal_diff'] = df['salary'].groupby( df['dept']).transform(lambda x: x - x.mean())df.head() Output: sumitgumber28 Picked Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2022" }, { "code": null, "e": 52, "s": 28, "text": "Prerequisites: Pandas " }, { "code": null, "e": 518, "s": 52, "text": "Pandas is a Python library for data analysis and data manipulation. Often data analysis requires data to be broken into groups to perform various operations on these groups. The GroupBy function in Pandas employs the split-apply-combine strategy meaning it performs a combination of — splitting an object, applying functions to the object and combining the results. In this article, we will use the groupby() function to perform various operations on grouped data. " }, { "code": null, "e": 756, "s": 518, "text": "Aggregation involves creating statistical summaries of data with methods such as mean, median, mode, min (minimum), max (maximum), std (standard deviation), var (variance), sum, count, etc. To perform the aggregation operation on groups:" }, { "code": null, "e": 770, "s": 756, "text": "Import module" }, { "code": null, "e": 790, "s": 770, "text": "Create or load data" }, { "code": null, "e": 861, "s": 790, "text": "Create a GroupBy object which groups data along a key or multiple keys" }, { "code": null, "e": 892, "s": 861, "text": "Apply a statistical operation." }, { "code": null, "e": 1042, "s": 892, "text": "Example 1: Calculate the mean salaries and age of male and female groups. It gives the mean of numeric columns and adds a prefix to the column names." }, { "code": null, "e": 1050, "s": 1042, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({\"dept\": np.random.choice([\"IT\", \"HR\", \"Sales\", \"Production\"], size=50), \"gender\": np.random.choice([\"F\", \"M\"], size=50), \"age\": np.random.randint(22, 60, size=50), \"salary\": np.random.randint(20000, 90000, size=50)})df.index.name = \"emp_id\" # Calculate mean data of gender groupsdf.groupby('gender').mean().add_prefix('mean_')", "e": 1542, "s": 1050, "text": null }, { "code": null, "e": 1550, "s": 1542, "text": "Output:" }, { "code": null, "e": 1713, "s": 1550, "text": "Example 2: Performing multiple aggregate operations using the aggregate function (DataFrameGroupBy.agg) which accepts a string, function or a list of functions. " }, { "code": null, "e": 1721, "s": 1713, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({\"dept\": np.random.choice([\"IT\", \"HR\", \"Sales\", \"Production\"], size=50), \"gender\": np.random.choice([\"F\", \"M\"], size=50), \"age\": np.random.randint(22, 60, size=50), \"salary\": np.random.randint(20000, 90000, size=50)})df.index.name = \"emp_id\" # Calculate min, max, mean and count of salaries# in different departments for males and femalesdf.groupby(['dept', 'gender'])['salary'].agg([\"min\", \"max\", \"mean\", \"count\"])", "e": 2301, "s": 1721, "text": null }, { "code": null, "e": 2309, "s": 2301, "text": "Output:" }, { "code": null, "e": 2405, "s": 2309, "text": "Example 3: Specifying multiple columns and their corresponding aggregate operations as follows." }, { "code": null, "e": 2413, "s": 2405, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({\"dept\": np.random.choice([\"IT\", \"HR\", \"Sales\", \"Production\"], size=50), \"gender\": np.random.choice([\"F\", \"M\"], size=50), \"age\": np.random.randint(22, 60, size=50), \"salary\": np.random.randint(20000, 90000, size=50)})df.index.name = \"emp_id\" # Calculate mean salaries and min-max age of employees# in different departments for gender groupsdf.groupby(['dept', 'gender']).agg({'salary': 'mean', 'age': ['min', 'max']})", "e": 2995, "s": 2413, "text": null }, { "code": null, "e": 3003, "s": 2995, "text": "Output:" }, { "code": null, "e": 3056, "s": 3003, "text": "Example 4: Display common statistics for any group. " }, { "code": null, "e": 3064, "s": 3056, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({\"dept\": np.random.choice([\"IT\", \"HR\", \"Sales\", \"Production\"], size=50), \"gender\": np.random.choice([\"F\", \"M\"], size=50), \"age\": np.random.randint(22, 60, size=50), \"salary\": np.random.randint(20000, 90000, size=50)})df.index.name = \"emp_id\" # Statistics of employee age grouped by departmentsdf[\"age\"].groupby(df['dept']).describe()", "e": 3562, "s": 3064, "text": null }, { "code": null, "e": 3570, "s": 3562, "text": "Output:" }, { "code": null, "e": 3613, "s": 3570, "text": "Create bins or groups and apply operations" }, { "code": null, "e": 3810, "s": 3613, "text": "The cut method of Pandas sorts values into bin intervals creating groups or categories. Aggregation or other functions can then be performed on these groups. Implementation of this is shown below:" }, { "code": null, "e": 3916, "s": 3810, "text": "Example : Age is divided into age ranges and the count of observations in the sample data is calculated. " }, { "code": null, "e": 3924, "s": 3916, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({\"dept\": np.random.choice([\"IT\", \"HR\", \"Sales\", \"Production\"], size=50), \"gender\": np.random.choice([\"F\", \"M\"], size=50), \"age\": np.random.randint(22, 60, size=50), \"salary\": np.random.randint(20000, 90000, size=50)})df.index.name = \"emp_id\" # Create bin intervalsbins = [20, 30, 45, 60] # Segregate ages into bins of age groupsdf['categories'] = pd.cut(df['age'], bins, labels=['Young', 'Middle', 'Old']) # Calculate number of observations in each age categorydf['age'].groupby(df['categories']).count()", "e": 4618, "s": 3924, "text": null }, { "code": null, "e": 4626, "s": 4618, "text": "Output:" }, { "code": null, "e": 4806, "s": 4626, "text": "Transformation is performing a group-specific operation where the individual values are changed while the shape of the data remains same. We use the transform() function to do so." }, { "code": null, "e": 4816, "s": 4806, "text": "Example :" }, { "code": null, "e": 4824, "s": 4816, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Create a sample dataframedf = pd.DataFrame({\"dept\": np.random.choice([\"IT\", \"HR\", \"Sales\", \"Production\"], size=50), \"gender\": np.random.choice([\"F\", \"M\"], size=50), \"age\": np.random.randint(22, 60, size=50), \"salary\": np.random.randint(20000, 90000, size=50)})df.index.name = \"emp_id\" # Calculate mean difference by transforming each salary valuedf['mean_sal_diff'] = df['salary'].groupby( df['dept']).transform(lambda x: x - x.mean())df.head()", "e": 5393, "s": 4824, "text": null }, { "code": null, "e": 5401, "s": 5393, "text": "Output:" }, { "code": null, "e": 5415, "s": 5401, "text": "sumitgumber28" }, { "code": null, "e": 5422, "s": 5415, "text": "Picked" }, { "code": null, "e": 5444, "s": 5422, "text": "Python pandas-groupby" }, { "code": null, "e": 5458, "s": 5444, "text": "Python-pandas" }, { "code": null, "e": 5465, "s": 5458, "text": "Python" } ]
Java Program to Make a Rollback
08 Jun, 2022 Calling a rollback operation undoes all the effects or modifications that have been done by a Transaction(Ti) and terminate the Ti and all the variables get their previous values stored. Rollback is mainly called when you get one or more than one SQL exception in the statements of Transaction(Ti), then the Ti get aborted and start over from the beginning. This is the only way to know what has been committed and what hasn’t been committed. A SQL exception just signals out that something is wrong in your statement that you have written but doesn’t mention what and where wrong has been done. So the only option left to you is calling a rollback method. Procedure: It primarily deals with two steps. First, create a database and then dealing with transactions. Create a databaseExecute the transactions for rollbackImport the databaseLoad and register drivers if necessaryCreate a new connectionCreate a statement for commit/rollbackExecute the query for commit/rollbackProcess the resultsClose the connection else previous processing may lose if any. Create a database Execute the transactions for rollbackImport the databaseLoad and register drivers if necessaryCreate a new connectionCreate a statement for commit/rollbackExecute the query for commit/rollbackProcess the resultsClose the connection else previous processing may lose if any. Import the database Load and register drivers if necessary Create a new connection Create a statement for commit/rollback Execute the query for commit/rollback Process the results Close the connection else previous processing may lose if any. Step 1: We can also rollback the modifications in the database up to a particular flag or save point by just passing the needed Save points name as a parameter into this below method − // Set the Flag or Save point con.rollback("MysavePoint"); Step 2. To roll back a transaction: Load the JDBC driver, by using the API method forName(String className) of the Class. In this example, we are using the Oracle Register the required driver using the registerDriver( ) method // To register the needed Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Get the connection information using the getConnection() API method of the DriverManager: // For getting the connection String url = "jdbc:mysql://localhost/mydatabase/icpc"; Connection conn = DriverManager.getConnection(string url, String user, String password); Disable the auto-commit using the API method of off connection setAutoCommit(boolean auto-commit) method as: // Set the auto commit false. This will execute all // SQL statements as individual transactions con.setAutoCommit(false); Now, set the save point using the setSavepoint() or, commit the transaction using the API method commit( ) of connection as shown below− Savepoint savePoint = con.setSavepoint("MysavePoint"); Con.commit(); If any SQL exception is found then, in that case, invoke rollback( ) API method for the whole transaction to till the previously set savepoint: con.rollback() Or, con. rollback(my_Savepoint); Implementation: Java program to demonstrate both rollback() and commit() program is as follows Java // Importing generic java librariesimport java.io.*; // Retrieving SQL DB// javaconnector-linkage for JDBCimport java.sql.*;import java.sql.SQLException;import java.sql.DriverManager;import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;import java.sql.PreparedStatement;import java.sql.Date;// Importing drivers(if necessarily) // GFG class only to illustrate JDBC// not illustrating connection classclass GFG { /* Step 1: Importing DB */ // Database URL so as to create/fetch data from DB static String DB_URL = "jdbc:oracle:thin:@localhost/my_database_"; // DB userID static String DB_USER = "local"; // Remember randomly self createdDB password // to deal with above DB root static String DB_PASSWORD = "test"; // Main driver method public static void main(String args[]) { // Try block to check exceptions if occurs try { /* Step 2: Loading and registering drivers*/ Class.forName( "oracle.jdbc.driver.OracleDriver"); /* Step 3: Create the new connection */ Connection conn = DriverManager.getConnection( DB_URL, DB_USER, DB_PASSWORD); // set auto commit of the connection to false conn.setAutoCommit(false); /* Step 4: Create a statement */ // Input the info into record String sql_ = "INSERT INTO Employee (empid, empname) VALUES (?, ?)"; // Create a Statement_object PreparedStatement ps = conn.prepareStatement(sql_); /* Step 5: Execute a query */ // Take user input BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); while (true) { // Asking user to enter data(EmpID) System.out.print("Enter emp_Id: "); // Reading above user entered EmpID String s_1 = br.readLine(); int empid = Integer.parseInt(s_1); // Asking user to enter data(EmpName) System.out.print("Enter emp_name: "); // Reading above user entered EmpName String name = br.readLine(); // Creating entry in table // Set emp_id ps.setInt(1, empid); // Set emp_name ps.setString(2, name); // Execute the updation operation ps.executeUpdate(); /* Step 6: Process the results */ /* Displaying choice what user wants to do with updation, either Commit() or rollback() */ System.out.println("commit or rollback"); // Reading choice from user String answer = br.readLine(); /* Asking user's choice for condition * check*/ /* Checking if users want to commit or * rollback */ // If user wants to commit if (answer.equals("commit")) { conn.commit(); } // If user wants to rollback if (answer.equals("rollback")) { // Rollback the update in case if some // flaw in your record conn.rollback(); } /* Display message to user for inputing next record if user wants to add */ System.out.println( "Do you want to include more records"); /* Asking choice */ System.out.println("\n yes/no"); // Read user's choice String answ = br.readLine(); if (answ.equals("no")) { break; } } conn.commit(); // Print message System.out.println( "record is successfully saved"); /* Step 7: Close the connection */ // calling commit() before closing connection // else updation would be lost conn.close(); } // Exception handled if occurred by catch block catch (Exception exc) { // Highlighting line where exception occurred // as execution is equal exc.printStackTrace(); } }} Output: There are two sample outputs images covering both cases: commit and rollback or simply direct rollback as illustrated in the below outputs. clintra simranarora5sos nikhatkhan11 Picked Java Java Programs Java 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": "\n08 Jun, 2022" }, { "code": null, "e": 685, "s": 28, "text": "Calling a rollback operation undoes all the effects or modifications that have been done by a Transaction(Ti) and terminate the Ti and all the variables get their previous values stored. Rollback is mainly called when you get one or more than one SQL exception in the statements of Transaction(Ti), then the Ti get aborted and start over from the beginning. This is the only way to know what has been committed and what hasn’t been committed. A SQL exception just signals out that something is wrong in your statement that you have written but doesn’t mention what and where wrong has been done. So the only option left to you is calling a rollback method." }, { "code": null, "e": 792, "s": 685, "text": "Procedure: It primarily deals with two steps. First, create a database and then dealing with transactions." }, { "code": null, "e": 1083, "s": 792, "text": "Create a databaseExecute the transactions for rollbackImport the databaseLoad and register drivers if necessaryCreate a new connectionCreate a statement for commit/rollbackExecute the query for commit/rollbackProcess the resultsClose the connection else previous processing may lose if any." }, { "code": null, "e": 1101, "s": 1083, "text": "Create a database" }, { "code": null, "e": 1375, "s": 1101, "text": "Execute the transactions for rollbackImport the databaseLoad and register drivers if necessaryCreate a new connectionCreate a statement for commit/rollbackExecute the query for commit/rollbackProcess the resultsClose the connection else previous processing may lose if any." }, { "code": null, "e": 1395, "s": 1375, "text": "Import the database" }, { "code": null, "e": 1434, "s": 1395, "text": "Load and register drivers if necessary" }, { "code": null, "e": 1458, "s": 1434, "text": "Create a new connection" }, { "code": null, "e": 1497, "s": 1458, "text": "Create a statement for commit/rollback" }, { "code": null, "e": 1535, "s": 1497, "text": "Execute the query for commit/rollback" }, { "code": null, "e": 1555, "s": 1535, "text": "Process the results" }, { "code": null, "e": 1618, "s": 1555, "text": "Close the connection else previous processing may lose if any." }, { "code": null, "e": 1803, "s": 1618, "text": "Step 1: We can also rollback the modifications in the database up to a particular flag or save point by just passing the needed Save points name as a parameter into this below method −" }, { "code": null, "e": 1863, "s": 1803, "text": "// Set the Flag or Save point \ncon.rollback(\"MysavePoint\");" }, { "code": null, "e": 2026, "s": 1863, "text": "Step 2. To roll back a transaction: Load the JDBC driver, by using the API method forName(String className) of the Class. In this example, we are using the Oracle" }, { "code": null, "e": 2090, "s": 2026, "text": "Register the required driver using the registerDriver( ) method" }, { "code": null, "e": 2188, "s": 2090, "text": " // To register the needed Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());" }, { "code": null, "e": 2278, "s": 2188, "text": "Get the connection information using the getConnection() API method of the DriverManager:" }, { "code": null, "e": 2461, "s": 2278, "text": " // For getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase/icpc\";\n Connection conn = DriverManager.getConnection(string url, String user, String password);" }, { "code": null, "e": 2570, "s": 2461, "text": "Disable the auto-commit using the API method of off connection setAutoCommit(boolean auto-commit) method as:" }, { "code": null, "e": 2702, "s": 2570, "text": " // Set the auto commit false. This will execute all\n // SQL statements as individual transactions\n con.setAutoCommit(false);" }, { "code": null, "e": 2839, "s": 2702, "text": "Now, set the save point using the setSavepoint() or, commit the transaction using the API method commit( ) of connection as shown below−" }, { "code": null, "e": 2914, "s": 2839, "text": " Savepoint savePoint = con.setSavepoint(\"MysavePoint\");\n Con.commit();" }, { "code": null, "e": 3058, "s": 2914, "text": "If any SQL exception is found then, in that case, invoke rollback( ) API method for the whole transaction to till the previously set savepoint:" }, { "code": null, "e": 3112, "s": 3058, "text": " con.rollback() Or,\n con. rollback(my_Savepoint);" }, { "code": null, "e": 3207, "s": 3112, "text": "Implementation: Java program to demonstrate both rollback() and commit() program is as follows" }, { "code": null, "e": 3212, "s": 3207, "text": "Java" }, { "code": "// Importing generic java librariesimport java.io.*; // Retrieving SQL DB// javaconnector-linkage for JDBCimport java.sql.*;import java.sql.SQLException;import java.sql.DriverManager;import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;import java.sql.PreparedStatement;import java.sql.Date;// Importing drivers(if necessarily) // GFG class only to illustrate JDBC// not illustrating connection classclass GFG { /* Step 1: Importing DB */ // Database URL so as to create/fetch data from DB static String DB_URL = \"jdbc:oracle:thin:@localhost/my_database_\"; // DB userID static String DB_USER = \"local\"; // Remember randomly self createdDB password // to deal with above DB root static String DB_PASSWORD = \"test\"; // Main driver method public static void main(String args[]) { // Try block to check exceptions if occurs try { /* Step 2: Loading and registering drivers*/ Class.forName( \"oracle.jdbc.driver.OracleDriver\"); /* Step 3: Create the new connection */ Connection conn = DriverManager.getConnection( DB_URL, DB_USER, DB_PASSWORD); // set auto commit of the connection to false conn.setAutoCommit(false); /* Step 4: Create a statement */ // Input the info into record String sql_ = \"INSERT INTO Employee (empid, empname) VALUES (?, ?)\"; // Create a Statement_object PreparedStatement ps = conn.prepareStatement(sql_); /* Step 5: Execute a query */ // Take user input BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); while (true) { // Asking user to enter data(EmpID) System.out.print(\"Enter emp_Id: \"); // Reading above user entered EmpID String s_1 = br.readLine(); int empid = Integer.parseInt(s_1); // Asking user to enter data(EmpName) System.out.print(\"Enter emp_name: \"); // Reading above user entered EmpName String name = br.readLine(); // Creating entry in table // Set emp_id ps.setInt(1, empid); // Set emp_name ps.setString(2, name); // Execute the updation operation ps.executeUpdate(); /* Step 6: Process the results */ /* Displaying choice what user wants to do with updation, either Commit() or rollback() */ System.out.println(\"commit or rollback\"); // Reading choice from user String answer = br.readLine(); /* Asking user's choice for condition * check*/ /* Checking if users want to commit or * rollback */ // If user wants to commit if (answer.equals(\"commit\")) { conn.commit(); } // If user wants to rollback if (answer.equals(\"rollback\")) { // Rollback the update in case if some // flaw in your record conn.rollback(); } /* Display message to user for inputing next record if user wants to add */ System.out.println( \"Do you want to include more records\"); /* Asking choice */ System.out.println(\"\\n yes/no\"); // Read user's choice String answ = br.readLine(); if (answ.equals(\"no\")) { break; } } conn.commit(); // Print message System.out.println( \"record is successfully saved\"); /* Step 7: Close the connection */ // calling commit() before closing connection // else updation would be lost conn.close(); } // Exception handled if occurred by catch block catch (Exception exc) { // Highlighting line where exception occurred // as execution is equal exc.printStackTrace(); } }}", "e": 7633, "s": 3212, "text": null }, { "code": null, "e": 7782, "s": 7633, "text": "Output: There are two sample outputs images covering both cases: commit and rollback or simply direct rollback as illustrated in the below outputs. " }, { "code": null, "e": 7790, "s": 7782, "text": "clintra" }, { "code": null, "e": 7806, "s": 7790, "text": "simranarora5sos" }, { "code": null, "e": 7819, "s": 7806, "text": "nikhatkhan11" }, { "code": null, "e": 7826, "s": 7819, "text": "Picked" }, { "code": null, "e": 7831, "s": 7826, "text": "Java" }, { "code": null, "e": 7845, "s": 7831, "text": "Java Programs" }, { "code": null, "e": 7850, "s": 7845, "text": "Java" }, { "code": null, "e": 7948, "s": 7850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7963, "s": 7948, "text": "Stream In Java" }, { "code": null, "e": 7984, "s": 7963, "text": "Introduction to Java" }, { "code": null, "e": 8005, "s": 7984, "text": "Constructors in Java" }, { "code": null, "e": 8024, "s": 8005, "text": "Exceptions in Java" }, { "code": null, "e": 8041, "s": 8024, "text": "Generics in Java" }, { "code": null, "e": 8067, "s": 8041, "text": "Java Programming Examples" }, { "code": null, "e": 8101, "s": 8067, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 8148, "s": 8101, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 8186, "s": 8148, "text": "Factory method design pattern in Java" } ]
Soroco India Interview Experience
04 Oct, 2021 Round 1: Coding Assessment Maximum subarray sum Sliding window maximum Round 2: Video Call Interview Coding round : Find the kth largest element in a given array (using heaps) List out the unique elements present in a string (use sets) Round 3: video call interview System Design Round + coding Maximum subarray product( input can have negative numbers as well) HLD for Whatsapp ( should know about communication protocols and web sockets ) Verdict: Rejected though I performed well in the two rounds didn’t do well in the system design round. Marketing Soroco Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Oct, 2021" }, { "code": null, "e": 80, "s": 53, "text": "Round 1: Coding Assessment" }, { "code": null, "e": 101, "s": 80, "text": "Maximum subarray sum" }, { "code": null, "e": 124, "s": 101, "text": "Sliding window maximum" }, { "code": null, "e": 154, "s": 124, "text": "Round 2: Video Call Interview" }, { "code": null, "e": 169, "s": 154, "text": "Coding round :" }, { "code": null, "e": 229, "s": 169, "text": "Find the kth largest element in a given array (using heaps)" }, { "code": null, "e": 289, "s": 229, "text": "List out the unique elements present in a string (use sets)" }, { "code": null, "e": 319, "s": 289, "text": "Round 3: video call interview" }, { "code": null, "e": 348, "s": 319, "text": "System Design Round + coding" }, { "code": null, "e": 415, "s": 348, "text": "Maximum subarray product( input can have negative numbers as well)" }, { "code": null, "e": 494, "s": 415, "text": "HLD for Whatsapp ( should know about communication protocols and web sockets )" }, { "code": null, "e": 597, "s": 494, "text": "Verdict: Rejected though I performed well in the two rounds didn’t do well in the system design round." }, { "code": null, "e": 607, "s": 597, "text": "Marketing" }, { "code": null, "e": 614, "s": 607, "text": "Soroco" }, { "code": null, "e": 636, "s": 614, "text": "Interview Experiences" } ]
Comparator function of qsort() in C
02 Jun, 2017 Standard C library provides qsort() that can be used for sorting an array. As the name suggests, the function uses QuickSort algorithm to sort the given array. Following is prototype of qsort() void qsort (void* base, size_t num, size_t size, int (*comparator)(const void*,const void*)); The key point about qsort() is comparator function comparator. The comparator function takes two arguments and contains logic to decide their relative order in sorted output. The idea is to provide flexibility so that qsort() can be used for any type (including user defined types) and can be used to obtain any desired order (increasing, decreasing or any other). The comparator function takes two pointers as arguments (both type-casted to const void*) and defines the order of the elements by returning (in a stable and transitive manner int comparator(const void* p1, const void* p2); Return value meaning <0 The element pointed by p1 goes before the element pointed by p2 0 The element pointed by p1 is equivalent to the element pointed by p2 >0 The element pointed by p1 goes after the element pointed by p2 Source: http://www.cplusplus.com/reference/cstdlib/qsort/ For example, let there be an array of students where following is type of student. struct Student{ int age, marks; char name[20];}; Lets say we need to sort the students based on marks in ascending order. The comparator function will look like: int comparator(const void *p, const void *q) { int l = ((struct Student *)p)->marks; int r = ((struct Student *)q)->marks; return (l - r);} See following posts for more sample uses of qsort().Given a sequence of words, print all anagrams togetherBox Stacking ProblemClosest Pair of Points Following is an interesting problem that can be easily solved with the help of qsort() and comparator function.Given an array of integers, sort it in such a way that the odd numbers appear first and the even numbers appear later. The odd numbers should be sorted in descending order and the even numbers should be sorted in ascending order. The simple approach is to first modify the input array such that the even and odd numbers are segregated followed by applying some sorting algorithm on both parts(odd and even) separately. However, there exists an interesting approach with a little modification in comparator function of Quick Sort. The idea is to write a comparator function that takes two addresses p and q as arguments. Let l and r be the number pointed by p and q. The function uses following logic:1) If both (l and r) are odd, put the greater of two first.2) If both (l and r) are even, put the smaller of two first.3) If one of them is even and other is odd, put the odd number first. Following is C implementation of the above approach. #include <stdio.h>#include <stdlib.h> // This function is used in qsort to decide the relative order// of elements at addresses p and q.int comparator(const void *p, const void *q){ // Get the values at given addresses int l = *(const int *)p; int r = *(const int *)q; // both odd, put the greater of two first. if ((l&1) && (r&1)) return (r-l); // both even, put the smaller of two first if ( !(l&1) && !(r&1) ) return (l-r); // l is even, put r first if (!(l&1)) return 1; // l is odd, put l first return -1;} // A utility function to print an arrayvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf("%d ", arr[i]);} // Driver program to test above functionint main(){ int arr[] = {1, 6, 5, 2, 3, 9, 4, 7, 8}; int size = sizeof(arr) / sizeof(arr[0]); qsort((void*)arr, size, sizeof(arr[0]), comparator); printf("Output array is\n"); printArr(arr, size); return 0;} Output: Output array is 9 7 5 3 1 2 4 6 8 Exercise:Given an array of integers, sort it in alternate fashion. Alternate fashion means that the elements at even indices are sorted separately and elements at odd indices are sorted separately. This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Library CPP-Library Quick Sort Sorting Quiz C Language C++ Sorting Sorting CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Arrays in C/C++ Substring in C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Function Pointer in C Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Bitwise Operators in C/C++ Arrays in C/C++
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jun, 2017" }, { "code": null, "e": 248, "s": 54, "text": "Standard C library provides qsort() that can be used for sorting an array. As the name suggests, the function uses QuickSort algorithm to sort the given array. Following is prototype of qsort()" }, { "code": "void qsort (void* base, size_t num, size_t size, int (*comparator)(const void*,const void*));", "e": 354, "s": 248, "text": null }, { "code": null, "e": 719, "s": 354, "text": "The key point about qsort() is comparator function comparator. The comparator function takes two arguments and contains logic to decide their relative order in sorted output. The idea is to provide flexibility so that qsort() can be used for any type (including user defined types) and can be used to obtain any desired order (increasing, decreasing or any other)." }, { "code": null, "e": 895, "s": 719, "text": "The comparator function takes two pointers as arguments (both type-casted to const void*) and defines the order of the elements by returning (in a stable and transitive manner" }, { "code": null, "e": 1229, "s": 895, "text": "int comparator(const void* p1, const void* p2);\nReturn value meaning\n<0 The element pointed by p1 goes before the element pointed by p2\n0 The element pointed by p1 is equivalent to the element pointed by p2\n>0 The element pointed by p1 goes after the element pointed by p2\n\nSource: http://www.cplusplus.com/reference/cstdlib/qsort/\n" }, { "code": null, "e": 1312, "s": 1229, "text": "For example, let there be an array of students where following is type of student." }, { "code": "struct Student{ int age, marks; char name[20];};", "e": 1367, "s": 1312, "text": null }, { "code": null, "e": 1480, "s": 1367, "text": "Lets say we need to sort the students based on marks in ascending order. The comparator function will look like:" }, { "code": "int comparator(const void *p, const void *q) { int l = ((struct Student *)p)->marks; int r = ((struct Student *)q)->marks; return (l - r);}", "e": 1630, "s": 1480, "text": null }, { "code": null, "e": 1779, "s": 1630, "text": "See following posts for more sample uses of qsort().Given a sequence of words, print all anagrams togetherBox Stacking ProblemClosest Pair of Points" }, { "code": null, "e": 2120, "s": 1779, "text": "Following is an interesting problem that can be easily solved with the help of qsort() and comparator function.Given an array of integers, sort it in such a way that the odd numbers appear first and the even numbers appear later. The odd numbers should be sorted in descending order and the even numbers should be sorted in ascending order." }, { "code": null, "e": 2309, "s": 2120, "text": "The simple approach is to first modify the input array such that the even and odd numbers are segregated followed by applying some sorting algorithm on both parts(odd and even) separately." }, { "code": null, "e": 2779, "s": 2309, "text": "However, there exists an interesting approach with a little modification in comparator function of Quick Sort. The idea is to write a comparator function that takes two addresses p and q as arguments. Let l and r be the number pointed by p and q. The function uses following logic:1) If both (l and r) are odd, put the greater of two first.2) If both (l and r) are even, put the smaller of two first.3) If one of them is even and other is odd, put the odd number first." }, { "code": null, "e": 2832, "s": 2779, "text": "Following is C implementation of the above approach." }, { "code": "#include <stdio.h>#include <stdlib.h> // This function is used in qsort to decide the relative order// of elements at addresses p and q.int comparator(const void *p, const void *q){ // Get the values at given addresses int l = *(const int *)p; int r = *(const int *)q; // both odd, put the greater of two first. if ((l&1) && (r&1)) return (r-l); // both even, put the smaller of two first if ( !(l&1) && !(r&1) ) return (l-r); // l is even, put r first if (!(l&1)) return 1; // l is odd, put l first return -1;} // A utility function to print an arrayvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf(\"%d \", arr[i]);} // Driver program to test above functionint main(){ int arr[] = {1, 6, 5, 2, 3, 9, 4, 7, 8}; int size = sizeof(arr) / sizeof(arr[0]); qsort((void*)arr, size, sizeof(arr[0]), comparator); printf(\"Output array is\\n\"); printArr(arr, size); return 0;}", "e": 3821, "s": 2832, "text": null }, { "code": null, "e": 3829, "s": 3821, "text": "Output:" }, { "code": null, "e": 3863, "s": 3829, "text": "Output array is\n9 7 5 3 1 2 4 6 8" }, { "code": null, "e": 4061, "s": 3863, "text": "Exercise:Given an array of integers, sort it in alternate fashion. Alternate fashion means that the elements at even indices are sorted separately and elements at odd indices are sorted separately." }, { "code": null, "e": 4231, "s": 4061, "text": "This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4241, "s": 4231, "text": "C-Library" }, { "code": null, "e": 4253, "s": 4241, "text": "CPP-Library" }, { "code": null, "e": 4264, "s": 4253, "text": "Quick Sort" }, { "code": null, "e": 4277, "s": 4264, "text": "Sorting Quiz" }, { "code": null, "e": 4288, "s": 4277, "text": "C Language" }, { "code": null, "e": 4292, "s": 4288, "text": "C++" }, { "code": null, "e": 4300, "s": 4292, "text": "Sorting" }, { "code": null, "e": 4308, "s": 4300, "text": "Sorting" }, { "code": null, "e": 4312, "s": 4308, "text": "CPP" }, { "code": null, "e": 4410, "s": 4312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4437, "s": 4410, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4453, "s": 4437, "text": "Arrays in C/C++" }, { "code": null, "e": 4470, "s": 4453, "text": "Substring in C++" }, { "code": null, "e": 4548, "s": 4470, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 4570, "s": 4548, "text": "Function Pointer in C" }, { "code": null, "e": 4588, "s": 4570, "text": "Vector in C++ STL" }, { "code": null, "e": 4631, "s": 4588, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 4677, "s": 4631, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 4704, "s": 4677, "text": "Bitwise Operators in C/C++" } ]
C program to sort an array in an ascending order
Sort the given array in descending or ascending order based on the code that has been written. An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its "index number". The syntax for declaring an array is as follows − datatype array_name [size]; For example, float marks [50] It declares ‘marks’ to be an array containing 50 float elements. int number[10] It declares the ‘number’ as an array to contain a maximum of 10 integer constants. Each element is identified by using an "array index". Accessing array elements is easy by using the array index. The logic we use to sort the array elements in ascending order is as follows − for (i = 0; i < n; ++i){ for (j = i + 1; j < n; ++j){ if (num[i] > num[j]){ a = num[i]; num[i] = num[j]; num[j] = a; } } } Following is the C program to sort an array in an ascending order − Live Demo #include <stdio.h> void main (){ int num[20]; int i, j, a, n; printf("enter number of elements in an array\n"); scanf("%d", &n); printf("Enter the elements\n"); for (i = 0; i < n; ++i) scanf("%d", &num[i]); for (i = 0; i < n; ++i){ for (j = i + 1; j < n; ++j){ if (num[i] > num[j]){ a = num[i]; num[i] = num[j]; num[j] = a; } } } printf("The numbers in ascending order is:\n"); for (i = 0; i < n; ++i){ printf("%d\n", num[i]); } } When the above program is executed, it produces the following result − enter number of elements in an array 5 Enter the elements 12 23 89 11 22 The numbers in ascending order is: 11 12 22 23 89
[ { "code": null, "e": 1157, "s": 1062, "text": "Sort the given array in descending or ascending order based on the code that has been written." }, { "code": null, "e": 1310, "s": 1157, "text": "An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its \"index number\"." }, { "code": null, "e": 1360, "s": 1310, "text": "The syntax for declaring an array is as follows −" }, { "code": null, "e": 1388, "s": 1360, "text": "datatype array_name [size];" }, { "code": null, "e": 1401, "s": 1388, "text": "For example," }, { "code": null, "e": 1418, "s": 1401, "text": "float marks [50]" }, { "code": null, "e": 1483, "s": 1418, "text": "It declares ‘marks’ to be an array containing 50 float elements." }, { "code": null, "e": 1498, "s": 1483, "text": "int number[10]" }, { "code": null, "e": 1581, "s": 1498, "text": "It declares the ‘number’ as an array to contain a maximum of 10 integer constants." }, { "code": null, "e": 1635, "s": 1581, "text": "Each element is identified by using an \"array index\"." }, { "code": null, "e": 1694, "s": 1635, "text": "Accessing array elements is easy by using the array index." }, { "code": null, "e": 1773, "s": 1694, "text": "The logic we use to sort the array elements in ascending order is as follows −" }, { "code": null, "e": 1941, "s": 1773, "text": "for (i = 0; i < n; ++i){\n for (j = i + 1; j < n; ++j){\n if (num[i] > num[j]){\n a = num[i];\n num[i] = num[j];\n num[j] = a;\n }\n }\n}" }, { "code": null, "e": 2009, "s": 1941, "text": "Following is the C program to sort an array in an ascending order −" }, { "code": null, "e": 2020, "s": 2009, "text": " Live Demo" }, { "code": null, "e": 2562, "s": 2020, "text": "#include <stdio.h>\nvoid main (){\n int num[20];\n int i, j, a, n;\n printf(\"enter number of elements in an array\\n\");\n scanf(\"%d\", &n);\n printf(\"Enter the elements\\n\");\n for (i = 0; i < n; ++i)\n scanf(\"%d\", &num[i]);\n for (i = 0; i < n; ++i){\n for (j = i + 1; j < n; ++j){\n if (num[i] > num[j]){\n a = num[i];\n num[i] = num[j];\n num[j] = a;\n }\n }\n }\n printf(\"The numbers in ascending order is:\\n\");\n for (i = 0; i < n; ++i){\n printf(\"%d\\n\", num[i]);\n }\n}" }, { "code": null, "e": 2633, "s": 2562, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2756, "s": 2633, "text": "enter number of elements in an array\n5\nEnter the elements\n12\n23\n89\n11\n22\nThe numbers in ascending order is:\n11\n12\n22\n23\n89" } ]
Geopandas Hands-on: Introduction to Geospatial Machine Learning | by Juan Nathaniel | Towards Data Science
Part 1: Introduction to geospatial concepts (this post)Part 2: Geospatial visualization and geometry creation (follow here)Part 3: Geospatial operations (follow here)Part 4: Building geospatial machine learning pipeline (follow here) In this post we are going to cover the preliminary ground of basic geospatial datatypes, attributes, and how to use geopandas to achieve these. What is GeopandasInstallationGeospatial conceptsIntroduction to basic geometric attributes What is Geopandas Installation Geospatial concepts Introduction to basic geometric attributes Geopandas is open-sourced library and enables the use and manipulation of geospatial data in Python. It extends the common datatype used in pandas to allow for the many and unique geometric operations: GeoSeries and GeoDataFrame. Geopandas is also built on top of shapely for its geometric operation; its underlying datatype allows Geopandas to run blazingly fast and is appropriate for many machine learning pipelines that require large geospatial datasets. Now that we are acquainted slightly with Geopandas, lets begin the installation process. There are many options, but I would recommend installating using conda as it creates a new environment for your project without affecting other libraries in your system. To install conda, follow this link: installing conda. Create a new conda environment and setup some configs Create a new conda environment and setup some configs conda create -n geo_envconda activate geo_envconda config --env --add channels conda-forgeconda config --env --set channel_priority strict 2. Install with conda conda install python=3 geopandas There are some common geospatial datatypes that you need to be familiar with: Shapefile (.shp) and GeoJSON (.geojson). Shapefile is a vector data format that is developed and maintained mostly by a company called ESRI. It stores many important geospatial information including the topology, shape geometry, etc. GeoJSON, similar to JSON, stores geometry information (coordinates, projection, etc) in addition to your typical attributes relevant to the object (index, name, etc). Once you load either of these dataformat using Geopandas, the library will create a DataFrame with the additional geometry column. This is how you import the default geodata built-in within the Geopandas library that we are going to use in this and subsequent posts. import geopandaspath_to_data = geopandas.datasets.get_path("nybb")gdf = geopandas.read_file(path_to_data)gdf Now that we have some ideas of geospatial data and how to import our very first one using Geopandas, lets perform some basic methods to further cement our understanding. First, lets make the boroughs name as index to make our explorations easier. gdf = gdf.set_index("BoroName") From the geometry column, we can measure the areas (if they are of type POLYGON or MULTIPOLYGON: since we can’t measure the area of lines or points) gdf["area"] = gdf.areagdf["area"]>>BoroName>>Staten Island 1.623822e+09>>Queens 3.045214e+09>>Brooklyn 1.937478e+09>>Manhattan 6.364712e+08>>Bronx 1.186926e+09>>Name: area, dtype: float64 Since our geometry is of type polygon or multipolygon, we can extract out the line coordinates of the objects. This can be useful when, say, we want to measure the perimeter of the polygon objects, etc. gdf['boundary'] = gdf.boundary>>gdf['boundary']>>BoroName>>Staten Island MULTILINESTRING ((970217.022 145643.332, 97022...>>Queens MULTILINESTRING ((1029606.077 156073.814, 1029...>>Brooklyn MULTILINESTRING ((1021176.479 151374.797, 1021...>>Manhattan MULTILINESTRING ((981219.056 188655.316, 98094...>>Bronx MULTILINESTRING ((1012821.806 229228.265, 1012...>>Name: boundary, dtype: geometry If you want to find the centroid point of the given polygons, you can call the gdf attribute as follows. gdf['centroid'] = gdf.centroid>>gdf['centroid']>>BoroName>>Staten Island POINT (941639.450 150931.991)>>Queens POINT (1034578.078 197116.604)>>Brooklyn POINT (998769.115 174169.761)>>Manhattan POINT (993336.965 222451.437)>>Bronx POINT (1021174.790 249937.980)>>Name: centroid, dtype: geometry Now that wealready know the positions of the centroids and wanted to find out where the distance between Queens and everywhere else, this can be done easily using the distance() method: queens_point = gdf['centroid'].iloc[1]gdf['distance'] = gdf['centroid'].distance(queens_point) You can then perform many spatial aggregates function to find out the mean, max, or min distances. gdf['distance'].mean() #To find the mean distancegdf['distance'].max() #To find the maximum distancegdf['distance'].min() #To find the minimum distance That’s it! Hope you learn something new today. In the next post, we will dig deeper into how these geospatial data can be visualized and created from scratch. Stay tuned! Do subscribe to my Email newsletter: https://tinyurl.com/2npw2fnz where I regularly summarize AI research papers in plain English and beautiful visualization.
[ { "code": null, "e": 406, "s": 172, "text": "Part 1: Introduction to geospatial concepts (this post)Part 2: Geospatial visualization and geometry creation (follow here)Part 3: Geospatial operations (follow here)Part 4: Building geospatial machine learning pipeline (follow here)" }, { "code": null, "e": 550, "s": 406, "text": "In this post we are going to cover the preliminary ground of basic geospatial datatypes, attributes, and how to use geopandas to achieve these." }, { "code": null, "e": 641, "s": 550, "text": "What is GeopandasInstallationGeospatial conceptsIntroduction to basic geometric attributes" }, { "code": null, "e": 659, "s": 641, "text": "What is Geopandas" }, { "code": null, "e": 672, "s": 659, "text": "Installation" }, { "code": null, "e": 692, "s": 672, "text": "Geospatial concepts" }, { "code": null, "e": 735, "s": 692, "text": "Introduction to basic geometric attributes" }, { "code": null, "e": 1194, "s": 735, "text": "Geopandas is open-sourced library and enables the use and manipulation of geospatial data in Python. It extends the common datatype used in pandas to allow for the many and unique geometric operations: GeoSeries and GeoDataFrame. Geopandas is also built on top of shapely for its geometric operation; its underlying datatype allows Geopandas to run blazingly fast and is appropriate for many machine learning pipelines that require large geospatial datasets." }, { "code": null, "e": 1283, "s": 1194, "text": "Now that we are acquainted slightly with Geopandas, lets begin the installation process." }, { "code": null, "e": 1507, "s": 1283, "text": "There are many options, but I would recommend installating using conda as it creates a new environment for your project without affecting other libraries in your system. To install conda, follow this link: installing conda." }, { "code": null, "e": 1561, "s": 1507, "text": "Create a new conda environment and setup some configs" }, { "code": null, "e": 1615, "s": 1561, "text": "Create a new conda environment and setup some configs" }, { "code": null, "e": 1754, "s": 1615, "text": "conda create -n geo_envconda activate geo_envconda config --env --add channels conda-forgeconda config --env --set channel_priority strict" }, { "code": null, "e": 1776, "s": 1754, "text": "2. Install with conda" }, { "code": null, "e": 1809, "s": 1776, "text": "conda install python=3 geopandas" }, { "code": null, "e": 1928, "s": 1809, "text": "There are some common geospatial datatypes that you need to be familiar with: Shapefile (.shp) and GeoJSON (.geojson)." }, { "code": null, "e": 2121, "s": 1928, "text": "Shapefile is a vector data format that is developed and maintained mostly by a company called ESRI. It stores many important geospatial information including the topology, shape geometry, etc." }, { "code": null, "e": 2288, "s": 2121, "text": "GeoJSON, similar to JSON, stores geometry information (coordinates, projection, etc) in addition to your typical attributes relevant to the object (index, name, etc)." }, { "code": null, "e": 2419, "s": 2288, "text": "Once you load either of these dataformat using Geopandas, the library will create a DataFrame with the additional geometry column." }, { "code": null, "e": 2555, "s": 2419, "text": "This is how you import the default geodata built-in within the Geopandas library that we are going to use in this and subsequent posts." }, { "code": null, "e": 2664, "s": 2555, "text": "import geopandaspath_to_data = geopandas.datasets.get_path(\"nybb\")gdf = geopandas.read_file(path_to_data)gdf" }, { "code": null, "e": 2834, "s": 2664, "text": "Now that we have some ideas of geospatial data and how to import our very first one using Geopandas, lets perform some basic methods to further cement our understanding." }, { "code": null, "e": 2911, "s": 2834, "text": "First, lets make the boroughs name as index to make our explorations easier." }, { "code": null, "e": 2943, "s": 2911, "text": "gdf = gdf.set_index(\"BoroName\")" }, { "code": null, "e": 3092, "s": 2943, "text": "From the geometry column, we can measure the areas (if they are of type POLYGON or MULTIPOLYGON: since we can’t measure the area of lines or points)" }, { "code": null, "e": 3319, "s": 3092, "text": "gdf[\"area\"] = gdf.areagdf[\"area\"]>>BoroName>>Staten Island 1.623822e+09>>Queens 3.045214e+09>>Brooklyn 1.937478e+09>>Manhattan 6.364712e+08>>Bronx 1.186926e+09>>Name: area, dtype: float64" }, { "code": null, "e": 3522, "s": 3319, "text": "Since our geometry is of type polygon or multipolygon, we can extract out the line coordinates of the objects. This can be useful when, say, we want to measure the perimeter of the polygon objects, etc." }, { "code": null, "e": 3953, "s": 3522, "text": "gdf['boundary'] = gdf.boundary>>gdf['boundary']>>BoroName>>Staten Island MULTILINESTRING ((970217.022 145643.332, 97022...>>Queens MULTILINESTRING ((1029606.077 156073.814, 1029...>>Brooklyn MULTILINESTRING ((1021176.479 151374.797, 1021...>>Manhattan MULTILINESTRING ((981219.056 188655.316, 98094...>>Bronx MULTILINESTRING ((1012821.806 229228.265, 1012...>>Name: boundary, dtype: geometry" }, { "code": null, "e": 4058, "s": 3953, "text": "If you want to find the centroid point of the given polygons, you can call the gdf attribute as follows." }, { "code": null, "e": 4394, "s": 4058, "text": "gdf['centroid'] = gdf.centroid>>gdf['centroid']>>BoroName>>Staten Island POINT (941639.450 150931.991)>>Queens POINT (1034578.078 197116.604)>>Brooklyn POINT (998769.115 174169.761)>>Manhattan POINT (993336.965 222451.437)>>Bronx POINT (1021174.790 249937.980)>>Name: centroid, dtype: geometry" }, { "code": null, "e": 4580, "s": 4394, "text": "Now that wealready know the positions of the centroids and wanted to find out where the distance between Queens and everywhere else, this can be done easily using the distance() method:" }, { "code": null, "e": 4675, "s": 4580, "text": "queens_point = gdf['centroid'].iloc[1]gdf['distance'] = gdf['centroid'].distance(queens_point)" }, { "code": null, "e": 4774, "s": 4675, "text": "You can then perform many spatial aggregates function to find out the mean, max, or min distances." }, { "code": null, "e": 4926, "s": 4774, "text": "gdf['distance'].mean() #To find the mean distancegdf['distance'].max() #To find the maximum distancegdf['distance'].min() #To find the minimum distance" }, { "code": null, "e": 5097, "s": 4926, "text": "That’s it! Hope you learn something new today. In the next post, we will dig deeper into how these geospatial data can be visualized and created from scratch. Stay tuned!" } ]
10x Faster Parallel Python Without Python Multiprocessing | by Robert Nishihara | Towards Data Science
While Python’s multiprocessing library has been used successfully for a wide range of applications, in this blog post, we show that it falls short for several important classes of applications including numerical data processing, stateful computation, and computation with expensive initialization. There are two main reasons: Inefficient handling of numerical data. Missing abstractions for stateful computation (i.e., an inability to share variables between separate “tasks”). Ray is a fast, simple framework for building and running distributed applications that addresses these issues. For an introduction to some of the basic concepts, see this blog post. Ray leverages Apache Arrow for efficient data handling and provides task and actor abstractions for distributed computing. This blog post benchmarks three workloads that aren’t easily expressed with Python multiprocessing and compares Ray, Python multiprocessing, and serial Python code. Note that it’s important to always compare to optimized single-threaded code. In these benchmarks, Ray is 10–30x faster than serial Python, 5–25x faster than multiprocessing, and 5–15x faster than the faster of these two on a large machine. The benchmarks were run on EC2 using the m5 instance types (m5.large for 1 physical core and m5.24xlarge for 48 physical cores). Code for running all of the benchmarks is available here. Abbreviated snippets are included in this post. The main differences are that the full benchmarks include 1) timing and printing code, 2) code for warming up the Ray object store, and 3) code for adapting the benchmark to smaller machines. Many machine learning, scientific computing, and data analysis workloads make heavy use of large arrays of data. For example, an array may represent a large image or dataset, and an application may wish to have multiple tasks analyze the image. Handling numerical data efficiently is critical. Each pass through the for loop below takes 0.84s with Ray, 7.5s with Python multiprocessing, and 24s with serial Python (on 48 physical cores). This performance gap explains why it is possible to build libraries like Modin on top of Ray but not on top of other libraries. The code looks as follows with Ray. By calling ray.put(image), the large array is stored in shared memory and can be accessed by all of the worker processes without creating copies. This works not just with arrays but also with objects that contain arrays (like lists of arrays). When the workers execute the f task, the results are again stored in shared memory. Then when the script calls ray.get([...]), it creates numpy arrays backed by shared memory without having to deserialize or copy the values. These optimizations are made possible by Ray’s use of Apache Arrow as the underlying data layout and serialization format as well as the Plasma shared-memory object store. The code looks as follows with Python multiprocessing. The difference here is that Python multiprocessing uses pickle to serialize large objects when passing them between processes. This approach requires each process to create its own copy of the data, which adds substantial memory usage as well as overhead for expensive deserialization, which Ray avoids by using the Apache Arrow data layout for zero-copy serialization along with the Plasma store. Workloads that require substantial “state” to be shared between many small units of work are another category of workloads that pose a challenge for Python multiprocessing. This pattern is extremely common, and I illustrate it here with a toy stream processing application. State is often encapsulated in Python classes, and Ray provides an actor abstraction so that classes can be used in the parallel and distributed setting. In contrast, Python multiprocessing doesn’t provide a natural way to parallelize Python classes, and so the user often needs to pass the relevant state around between map calls. This strategy can be tricky to implement in practice (many Python variables are not easily serializable) and it can be slow when it does work. Below is a toy example that uses parallel tasks to process one document at a time, extract the prefixes of each word, and return the most common prefixes at the end. The prefix counts are stored in the actor state and mutated by the different tasks. This example takes 3.2s with Ray, 21s with Python multiprocessing, and 54s with serial Python (on 48 physical cores). The Ray version looks as follows. Ray performs well here because Ray’s abstractions fit the problem at hand. This application needs a way to encapsulate and mutate state in the distributed setting, and actors fit the bill. The multiprocessing version looks as follows. The challenge here is that pool.map executes stateless functions meaning that any variables produced in one pool.map call that you want to use in another pool.map call need to be returned from the first call and passed into the second call. For small objects, this approach is acceptable, but when large intermediate results needs to be shared, the cost of passing them around is prohibitive (note that this wouldn’t be true if the variables were being shared between threads, but because they are being shared across process boundaries, the variables must be serialized into a string of bytes using a library like pickle). Because it has to pass so much state around, the multiprocessing version looks extremely awkward, and in the end only achieves a small speedup over serial Python. In reality, you wouldn’t write code like this because you simply wouldn’t use Python multiprocessing for stream processing. Instead, you’d probably use a dedicated stream-processing framework. This example shows that Ray is well-suited for building such a framework or application. One caveat is that there are many ways to use Python multiprocessing. In this example, we compare to Pool.map because it gives the closest API comparison. It should be possible to achieve better performance in this example by starting distinct processes and setting up multiple multiprocessing queues between them, however that leads to a complex and brittle design. In contrast to the previous example, many parallel computations don’t necessarily require intermediate computation to be shared between tasks, but benefit from it anyway. Even stateless computation can benefit from sharing state when the state is expensive to initialize. Below is an example in which we want to load a saved neural net from disk and use it to classify a bunch of images in parallel. This example takes 5s with Ray, 126s with Python multiprocessing, and 64s with serial Python (on 48 physical cores). In this case, the serial Python version uses many cores (via TensorFlow) to parallelize the computation and so it is not actually single threaded. Suppose we’ve initially created the model by running the following. Now we wish to load the model and use it to classify a bunch of images. We do this in batches because in the application the images may not all become available simultaneously and the image classification may need to be done in parallel with the data loading. The Ray version looks as follows. Loading the model is slow enough that we only want to do it once. The Ray version amortizes this cost by loading the model once in the actor’s constructor. If the model needs to be placed on a GPU, then initialization will be even more expensive. The multiprocessing version is slower because it needs to reload the model in every map call because the mapped functions are assumed to be stateless. The multiprocessing version looks as follows. Note that in some cases, it is possible to achieve this using the initializer argument to multiprocessing.Pool. However, this is limited to the setting in which the initialization is the same for each process and doesn’t allow for different processes to perform different setup functions (e.g., loading different neural network models), and doesn’t allow for different tasks to be targeted to different workers. What we’ve seen in all of these examples is that Ray’s performance comes not just from its performance optimizations but also from having abstractions that are appropriate for the tasks at hand. Stateful computation is important for many many applications, and coercing stateful computation into stateless abstractions comes at a cost. Before running these benchmarks, you will need to install the following. pip install numpy psutil ray scipy tensorflow Then all of the numbers above can be reproduced by running these scripts. If you have trouble installing psutil, then try using Anaconda Python. The original benchmarks were run on EC2 using the m5 instance types (m5.large for 1 physical core and m5.24xlarge for 48 physical cores). In order to launch an instance on AWS or GCP with the right configuration, you can use the Ray cluster launcher and run the following command. ray up config.yaml An example config.yaml is provided here (for starting an m5.4xlarge instance). While this blog post focuses on benchmarks between Ray and Python multiprocessing, an apples-to-apples comparison is challenging because these libraries are not very similar. Differences include the following. Ray is designed for scalability and can run the same code on a laptop as well as a cluster (multiprocessing only runs on a single machine). Ray workloads automatically recover from machine and process failures. Ray is designed in a language-agnostic manner and has preliminary support for Java. More relevant links are below. The codebase on GitHub. The Ray documentation. Ask questions on the Ray forum. Ray includes libraries for scaling reinforcement learning, scaling hyperparameter tuning, scaling model serving, and scaling data processing. Ray includes a cluster launcher for launching clusters on AWS and GCP.
[ { "code": null, "e": 499, "s": 172, "text": "While Python’s multiprocessing library has been used successfully for a wide range of applications, in this blog post, we show that it falls short for several important classes of applications including numerical data processing, stateful computation, and computation with expensive initialization. There are two main reasons:" }, { "code": null, "e": 539, "s": 499, "text": "Inefficient handling of numerical data." }, { "code": null, "e": 651, "s": 539, "text": "Missing abstractions for stateful computation (i.e., an inability to share variables between separate “tasks”)." }, { "code": null, "e": 956, "s": 651, "text": "Ray is a fast, simple framework for building and running distributed applications that addresses these issues. For an introduction to some of the basic concepts, see this blog post. Ray leverages Apache Arrow for efficient data handling and provides task and actor abstractions for distributed computing." }, { "code": null, "e": 1199, "s": 956, "text": "This blog post benchmarks three workloads that aren’t easily expressed with Python multiprocessing and compares Ray, Python multiprocessing, and serial Python code. Note that it’s important to always compare to optimized single-threaded code." }, { "code": null, "e": 1362, "s": 1199, "text": "In these benchmarks, Ray is 10–30x faster than serial Python, 5–25x faster than multiprocessing, and 5–15x faster than the faster of these two on a large machine." }, { "code": null, "e": 1789, "s": 1362, "text": "The benchmarks were run on EC2 using the m5 instance types (m5.large for 1 physical core and m5.24xlarge for 48 physical cores). Code for running all of the benchmarks is available here. Abbreviated snippets are included in this post. The main differences are that the full benchmarks include 1) timing and printing code, 2) code for warming up the Ray object store, and 3) code for adapting the benchmark to smaller machines." }, { "code": null, "e": 2083, "s": 1789, "text": "Many machine learning, scientific computing, and data analysis workloads make heavy use of large arrays of data. For example, an array may represent a large image or dataset, and an application may wish to have multiple tasks analyze the image. Handling numerical data efficiently is critical." }, { "code": null, "e": 2355, "s": 2083, "text": "Each pass through the for loop below takes 0.84s with Ray, 7.5s with Python multiprocessing, and 24s with serial Python (on 48 physical cores). This performance gap explains why it is possible to build libraries like Modin on top of Ray but not on top of other libraries." }, { "code": null, "e": 2391, "s": 2355, "text": "The code looks as follows with Ray." }, { "code": null, "e": 2635, "s": 2391, "text": "By calling ray.put(image), the large array is stored in shared memory and can be accessed by all of the worker processes without creating copies. This works not just with arrays but also with objects that contain arrays (like lists of arrays)." }, { "code": null, "e": 2860, "s": 2635, "text": "When the workers execute the f task, the results are again stored in shared memory. Then when the script calls ray.get([...]), it creates numpy arrays backed by shared memory without having to deserialize or copy the values." }, { "code": null, "e": 3032, "s": 2860, "text": "These optimizations are made possible by Ray’s use of Apache Arrow as the underlying data layout and serialization format as well as the Plasma shared-memory object store." }, { "code": null, "e": 3087, "s": 3032, "text": "The code looks as follows with Python multiprocessing." }, { "code": null, "e": 3485, "s": 3087, "text": "The difference here is that Python multiprocessing uses pickle to serialize large objects when passing them between processes. This approach requires each process to create its own copy of the data, which adds substantial memory usage as well as overhead for expensive deserialization, which Ray avoids by using the Apache Arrow data layout for zero-copy serialization along with the Plasma store." }, { "code": null, "e": 3759, "s": 3485, "text": "Workloads that require substantial “state” to be shared between many small units of work are another category of workloads that pose a challenge for Python multiprocessing. This pattern is extremely common, and I illustrate it here with a toy stream processing application." }, { "code": null, "e": 4234, "s": 3759, "text": "State is often encapsulated in Python classes, and Ray provides an actor abstraction so that classes can be used in the parallel and distributed setting. In contrast, Python multiprocessing doesn’t provide a natural way to parallelize Python classes, and so the user often needs to pass the relevant state around between map calls. This strategy can be tricky to implement in practice (many Python variables are not easily serializable) and it can be slow when it does work." }, { "code": null, "e": 4484, "s": 4234, "text": "Below is a toy example that uses parallel tasks to process one document at a time, extract the prefixes of each word, and return the most common prefixes at the end. The prefix counts are stored in the actor state and mutated by the different tasks." }, { "code": null, "e": 4602, "s": 4484, "text": "This example takes 3.2s with Ray, 21s with Python multiprocessing, and 54s with serial Python (on 48 physical cores)." }, { "code": null, "e": 4636, "s": 4602, "text": "The Ray version looks as follows." }, { "code": null, "e": 4825, "s": 4636, "text": "Ray performs well here because Ray’s abstractions fit the problem at hand. This application needs a way to encapsulate and mutate state in the distributed setting, and actors fit the bill." }, { "code": null, "e": 4871, "s": 4825, "text": "The multiprocessing version looks as follows." }, { "code": null, "e": 5495, "s": 4871, "text": "The challenge here is that pool.map executes stateless functions meaning that any variables produced in one pool.map call that you want to use in another pool.map call need to be returned from the first call and passed into the second call. For small objects, this approach is acceptable, but when large intermediate results needs to be shared, the cost of passing them around is prohibitive (note that this wouldn’t be true if the variables were being shared between threads, but because they are being shared across process boundaries, the variables must be serialized into a string of bytes using a library like pickle)." }, { "code": null, "e": 5940, "s": 5495, "text": "Because it has to pass so much state around, the multiprocessing version looks extremely awkward, and in the end only achieves a small speedup over serial Python. In reality, you wouldn’t write code like this because you simply wouldn’t use Python multiprocessing for stream processing. Instead, you’d probably use a dedicated stream-processing framework. This example shows that Ray is well-suited for building such a framework or application." }, { "code": null, "e": 6307, "s": 5940, "text": "One caveat is that there are many ways to use Python multiprocessing. In this example, we compare to Pool.map because it gives the closest API comparison. It should be possible to achieve better performance in this example by starting distinct processes and setting up multiple multiprocessing queues between them, however that leads to a complex and brittle design." }, { "code": null, "e": 6579, "s": 6307, "text": "In contrast to the previous example, many parallel computations don’t necessarily require intermediate computation to be shared between tasks, but benefit from it anyway. Even stateless computation can benefit from sharing state when the state is expensive to initialize." }, { "code": null, "e": 6707, "s": 6579, "text": "Below is an example in which we want to load a saved neural net from disk and use it to classify a bunch of images in parallel." }, { "code": null, "e": 6971, "s": 6707, "text": "This example takes 5s with Ray, 126s with Python multiprocessing, and 64s with serial Python (on 48 physical cores). In this case, the serial Python version uses many cores (via TensorFlow) to parallelize the computation and so it is not actually single threaded." }, { "code": null, "e": 7039, "s": 6971, "text": "Suppose we’ve initially created the model by running the following." }, { "code": null, "e": 7299, "s": 7039, "text": "Now we wish to load the model and use it to classify a bunch of images. We do this in batches because in the application the images may not all become available simultaneously and the image classification may need to be done in parallel with the data loading." }, { "code": null, "e": 7333, "s": 7299, "text": "The Ray version looks as follows." }, { "code": null, "e": 7580, "s": 7333, "text": "Loading the model is slow enough that we only want to do it once. The Ray version amortizes this cost by loading the model once in the actor’s constructor. If the model needs to be placed on a GPU, then initialization will be even more expensive." }, { "code": null, "e": 7731, "s": 7580, "text": "The multiprocessing version is slower because it needs to reload the model in every map call because the mapped functions are assumed to be stateless." }, { "code": null, "e": 8189, "s": 7731, "text": "The multiprocessing version looks as follows. Note that in some cases, it is possible to achieve this using the initializer argument to multiprocessing.Pool. However, this is limited to the setting in which the initialization is the same for each process and doesn’t allow for different processes to perform different setup functions (e.g., loading different neural network models), and doesn’t allow for different tasks to be targeted to different workers." }, { "code": null, "e": 8525, "s": 8189, "text": "What we’ve seen in all of these examples is that Ray’s performance comes not just from its performance optimizations but also from having abstractions that are appropriate for the tasks at hand. Stateful computation is important for many many applications, and coercing stateful computation into stateless abstractions comes at a cost." }, { "code": null, "e": 8598, "s": 8525, "text": "Before running these benchmarks, you will need to install the following." }, { "code": null, "e": 8644, "s": 8598, "text": "pip install numpy psutil ray scipy tensorflow" }, { "code": null, "e": 8718, "s": 8644, "text": "Then all of the numbers above can be reproduced by running these scripts." }, { "code": null, "e": 8789, "s": 8718, "text": "If you have trouble installing psutil, then try using Anaconda Python." }, { "code": null, "e": 8927, "s": 8789, "text": "The original benchmarks were run on EC2 using the m5 instance types (m5.large for 1 physical core and m5.24xlarge for 48 physical cores)." }, { "code": null, "e": 9070, "s": 8927, "text": "In order to launch an instance on AWS or GCP with the right configuration, you can use the Ray cluster launcher and run the following command." }, { "code": null, "e": 9089, "s": 9070, "text": "ray up config.yaml" }, { "code": null, "e": 9168, "s": 9089, "text": "An example config.yaml is provided here (for starting an m5.4xlarge instance)." }, { "code": null, "e": 9378, "s": 9168, "text": "While this blog post focuses on benchmarks between Ray and Python multiprocessing, an apples-to-apples comparison is challenging because these libraries are not very similar. Differences include the following." }, { "code": null, "e": 9518, "s": 9378, "text": "Ray is designed for scalability and can run the same code on a laptop as well as a cluster (multiprocessing only runs on a single machine)." }, { "code": null, "e": 9589, "s": 9518, "text": "Ray workloads automatically recover from machine and process failures." }, { "code": null, "e": 9673, "s": 9589, "text": "Ray is designed in a language-agnostic manner and has preliminary support for Java." }, { "code": null, "e": 9704, "s": 9673, "text": "More relevant links are below." }, { "code": null, "e": 9728, "s": 9704, "text": "The codebase on GitHub." }, { "code": null, "e": 9751, "s": 9728, "text": "The Ray documentation." }, { "code": null, "e": 9783, "s": 9751, "text": "Ask questions on the Ray forum." }, { "code": null, "e": 9925, "s": 9783, "text": "Ray includes libraries for scaling reinforcement learning, scaling hyperparameter tuning, scaling model serving, and scaling data processing." } ]
Count and display vowels in a string in Python
Given a string of characters let's analyse how many of the characters are vowels. We first find out all the individual and unique characters and then test if they are present in the string representing the vowels. Live Demo stringA = "Tutorialspoint is best" print("Given String: \n",stringA) vowels = "AaEeIiOoUu" # Get vowels res = set([each for each in stringA if each in vowels]) print("The vlowels present in the string:\n ",res) Running the above code gives us the following result − Given String: Tutorialspoint is best The vlowels present in the string: {'e', 'i', 'a', 'o', 'u'} This function enables to extract the vowels form the string by treating it as a dictionary. stringA = "Tutorialspoint is best" #ignore cases stringA = stringA.casefold() vowels = "aeiou" def vowel_count(string, vowels): # Take dictionary key as a vowel count = {}.fromkeys(vowels, 0) # To count the vowels for v in string: if v in count: # Increasing count for each occurence count[v] += 1 return count print("Given String: \n", stringA) print ("The count of vlowels in the string:\n ",vowel_count(stringA, vowels)) Running the above code gives us the following result − Given String: tutorialspoint is best The count of vlowels in the string: {'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}
[ { "code": null, "e": 1144, "s": 1062, "text": "Given a string of characters let's analyse how many of the characters are vowels." }, { "code": null, "e": 1276, "s": 1144, "text": "We first find out all the individual and unique characters and then test if they are present in the string representing the vowels." }, { "code": null, "e": 1287, "s": 1276, "text": " Live Demo" }, { "code": null, "e": 1498, "s": 1287, "text": "stringA = \"Tutorialspoint is best\"\nprint(\"Given String: \\n\",stringA)\nvowels = \"AaEeIiOoUu\"\n# Get vowels\nres = set([each for each in stringA if each in vowels])\nprint(\"The vlowels present in the string:\\n \",res)" }, { "code": null, "e": 1553, "s": 1498, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1651, "s": 1553, "text": "Given String:\nTutorialspoint is best\nThe vlowels present in the string:\n{'e', 'i', 'a', 'o', 'u'}" }, { "code": null, "e": 1743, "s": 1651, "text": "This function enables to extract the vowels form the string by treating it as a dictionary." }, { "code": null, "e": 2199, "s": 1743, "text": "stringA = \"Tutorialspoint is best\"\n#ignore cases\nstringA = stringA.casefold()\nvowels = \"aeiou\"\ndef vowel_count(string, vowels):\n\n # Take dictionary key as a vowel\n count = {}.fromkeys(vowels, 0)\n\n # To count the vowels\n for v in string:\n if v in count:\n # Increasing count for each occurence\n count[v] += 1\n return count\nprint(\"Given String: \\n\", stringA)\nprint (\"The count of vlowels in the string:\\n \",vowel_count(stringA, vowels))" }, { "code": null, "e": 2254, "s": 2199, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2368, "s": 2254, "text": "Given String:\ntutorialspoint is best\nThe count of vlowels in the string:\n{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}" } ]
How to update Python on Windows? - GeeksforGeeks
31 Aug, 2021 In this article, we are going to see how to update Python in the Windows system. For the sake of example, we will be upgrading from Python 3.6.8 to Python 3.9.6. To check the current version of python on your system, use the following command in the command prompt: python -V This will show you your current python version as shown below: Follow the below steps to update your python version: Step 1: Go to Python’s official site. Step 2: Click on the Downloads tab. Here you will get a list of available releases. Step 3: Download the version you need to upgrade to based on your system specifications(ie, 32-bit or 64-bit). Here we will be downloading the 64-bit installer for 3.9.6. Step 4: Click on the installer and it will begin the installation. Make sure to select the “Add Python 3.9 to PATH” option. and click on “Install Now”. This will start the installation as shown below: After the installation is successful you will get the following message: Now if you open up your cmd and use the below command: python -V You’ll see your version of Python has been updated to 3.9.6 as shown below: Picked python-basics 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24374, "s": 24212, "text": "In this article, we are going to see how to update Python in the Windows system. For the sake of example, we will be upgrading from Python 3.6.8 to Python 3.9.6." }, { "code": null, "e": 24478, "s": 24374, "text": "To check the current version of python on your system, use the following command in the command prompt:" }, { "code": null, "e": 24488, "s": 24478, "text": "python -V" }, { "code": null, "e": 24551, "s": 24488, "text": "This will show you your current python version as shown below:" }, { "code": null, "e": 24605, "s": 24551, "text": "Follow the below steps to update your python version:" }, { "code": null, "e": 24643, "s": 24605, "text": "Step 1: Go to Python’s official site." }, { "code": null, "e": 24679, "s": 24643, "text": "Step 2: Click on the Downloads tab." }, { "code": null, "e": 24727, "s": 24679, "text": "Here you will get a list of available releases." }, { "code": null, "e": 24898, "s": 24727, "text": "Step 3: Download the version you need to upgrade to based on your system specifications(ie, 32-bit or 64-bit). Here we will be downloading the 64-bit installer for 3.9.6." }, { "code": null, "e": 25050, "s": 24898, "text": "Step 4: Click on the installer and it will begin the installation. Make sure to select the “Add Python 3.9 to PATH” option. and click on “Install Now”." }, { "code": null, "e": 25099, "s": 25050, "text": "This will start the installation as shown below:" }, { "code": null, "e": 25172, "s": 25099, "text": "After the installation is successful you will get the following message:" }, { "code": null, "e": 25227, "s": 25172, "text": "Now if you open up your cmd and use the below command:" }, { "code": null, "e": 25237, "s": 25227, "text": "python -V" }, { "code": null, "e": 25313, "s": 25237, "text": "You’ll see your version of Python has been updated to 3.9.6 as shown below:" }, { "code": null, "e": 25320, "s": 25313, "text": "Picked" }, { "code": null, "e": 25334, "s": 25320, "text": "python-basics" }, { "code": null, "e": 25341, "s": 25334, "text": "Python" }, { "code": null, "e": 25439, "s": 25341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25448, "s": 25439, "text": "Comments" }, { "code": null, "e": 25461, "s": 25448, "text": "Old Comments" }, { "code": null, "e": 25493, "s": 25461, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25548, "s": 25493, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25604, "s": 25548, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25643, "s": 25604, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25685, "s": 25643, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25727, "s": 25685, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25758, "s": 25727, "text": "Python | os.path.join() method" }, { "code": null, "e": 25780, "s": 25758, "text": "Defaultdict in Python" }, { "code": null, "e": 25809, "s": 25780, "text": "Create a directory in Python" } ]
Predictive Modeling: Picking the Best Model | by Kailey Smith | Towards Data Science
Whether you are working on predicting data in an office setting or just competing in a Kaggle competition, it’s important to test out different models to find the best fit for the data you are working with. I recently had the opportunity to compete with some very smart colleagues in a private Kaggle competition predicting faulty water pumps in Tanzania. I ran the following models after doing some data cleaning and I’ll show you the results. Logistic Regression Random Forest Ridge Regression K-nearest Neighbors XGBoost First, we need to take a look at the data we’re working with. In this particular data set, the features were in a separate file than the labels. import pandas as pdpd.set_option('display.max_columns', None)X_df = pd.read_csv('./train_features.csv')X_df.head() y_df = pd.read_csv('./train_labels.csv')y_df.head() We can see that the status_group or target label is a string, some models are able to work without having to modify that, but others don’t. We’ll do something about that when we get to it later. Let’s check out our distribution of the target label. y_df['status_group'].value_counts(normalize=True) This split shows that we have exactly 3 classes in the label, so we have a multiclass classification. The majority class is ‘functional’, so if we were to just assign functional to all of the instances our model would be .54 on this training set. This is called the majority class baseline and is our target to beat with the models we run. There are a lot of features in this data set, so I’m not going to go into detail on every single thing I did, but I’ll go through high level, step by step. First, we want to check things out by looking at all the features and data types. X_df.info() There are 30 object features that we’ll need to work with in order to be able to use them in a model. The int and float objects can just be used as is. Another thing to look at is high cardinality features. If we have more than 100 categories for each of these features, it won’t be very useful to use them. It would add dimensions to our dataset and we don’t want to do that. Before we drop these high cardinality columns though, I see that the date_recorded is an object and that will most definitely get dropped with our high cardinality features, so I created some features off of that. #So date doesn't get dropped in next stepX_df['date_recorded'] = pd.to_datetime(X_df['date_recorded'])X_df['YearMonth'] = X_df['date_recorded'].map(lambda x: 100*x.year + x.month)X_df['Year'] = X_df['date_recorded'].map(lambda x: x.year)X_df['Month'] = X_df['date_recorded'].map(lambda x: x.month) Now that we’ve got the date sorted out we can check for high cardinality and drop those features. max_cardinality = 100high_cardinality = [col for col in X_df.select_dtypes(exclude=np.number) if X_df[col].nunique() > max_cardinality]X_df = X_df.drop(columns=high_cardinality)X_df.info() So, we dropped 8 features with high cardinality. Now we can use OneHotEncoder or Pandas get_dummies() to change these objects to ints. Now that all our features are now numerical, let’s get into the models! Logistic Regression is great for multiclass classification because Scikit-learn encodes encodes the target labels automatically if they are strings. First, we need to split our data into train and test. from sklearn.preprocessing import scalefrom sklearn.model_selection import train_test_splitX = X.drop(columns='id') #id is our index and won't help our modelX = scale(X) X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.75, test_size=0.25, random_state=42, shuffle=True) When you’re working with a learning model, it is important to scale the features to a range which is centered around zero. Scaling will make sure the variance of the features are in the same range. Now, we’ll run the model on both train and test and see what our accuracy score is. from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scorelogreg = LogisticRegression()logreg.fit(X_train,y_train)y_pred = logreg.predict(X_train)print('Train accuracy score:',accuracy_score(y_train,y_pred))print('Test accuracy score:', accuracy_score(y_test,logreg.predict(X_test))) We’re definitely beating our majority class baseline of .54 here with .73 for train and test. Let’s see if another model can do better. Random Forest can also take strings as our target labels, so we can just run the model with the same train test split. from sklearn.ensemble import RandomForestClassifier as RFCrfc_b = RFC()rfc_b.fit(X_train,y_train)y_pred = rfc_b.predict(X_train)print('Train accuracy score:',accuracy_score(y_train,y_pred))print('Test accuracy score:', accuracy_score(y_test,rfc_b.predict(X_test))) Random Forest beats Logistic Regression on train and test with .97 on train and .79 on test. For Ridge Regression we’ll need to encode the target labels before running the model. X = X_df.drop(columns=['id'])X = scale(X)y = y_df.drop(columns='id')y = y.replace({'functional':0, 'non functional':2,'functional needs repair':1 })X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.75, test_size=0.25, random_state=42, shuffle=True) Now we run the model. Ridge outputs a probability in it’s predict() method, so we’ll have to update that with numpy in order to get the actual predictions. from sklearn.linear_model import Ridgeimport numpy as npridge = Ridge()ridge.fit(X_train,y_train)y_prob = ridge.predict(X_train)y_pred = np.asarray([np.argmax(line) for line in y_prob])yp_test = ridge.predict(X_test)test_preds = np.asarray([np.argmax(line) for line in yp_test])print(accuracy_score(y_train,y_pred))print(accuracy_score(y_test,test_preds)) So, Ridge Regression is not a good model for this data. We’ll use the same train test split as Ridge for K-Nearest Neighbors. from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier()knn.fit(X_train,y_train)y_pred = knn.predict(X_train)print('Train accuracy score:',accuracy_score(y_train,y_pred))print('Test accuracy score:',accuracy_score(y_test,knn.predict(X_test))) These scores look a lot better than Ridge, but still aren’t our best scores. XGBoost is an algorithm that has been pretty popular in applied machine learning and Kaggle competitions for structured or tabular data. It is an implementation of gradient boosted decision trees designed for speed and performance. If you want to read more about it, check out there documentation here. I played with these parameters quite a bit when running this model and these were the best for the data I was running. xg_train = xgb.DMatrix(X_train, label=y_train)xg_test = xgb.DMatrix(X_test, label=y_test)xg_train.save_binary('train.buffer')xg_test.save_binary('train.buffer')# setup parameters for xgboostparam = {}# use softmax multi-class classificationparam['objective'] = 'multi:softmax'param['silent'] = 1 # cleans up the outputparam['num_class'] = 3 # number of classes in target labelwatchlist = [(xg_train, 'train'), (xg_test, 'test')]num_round = 30bst = xgb.train(param, xg_train, num_round, watchlist) The output of the XGBoost classifier outputs an merror which is defined as merror: Multiclass classification error rate. It is calculated as #(wrong cases)/#(all cases) # get predictiony_pred1 = bst.predict(xg_train)y_pred2 = bst.predict(xg_test)print('Train accuracy score:',accuracy_score(y_train,y_pred1))print('Test accuracy score:',accuracy_score(y_test,bst.predict(xg_test))) We get .79 for train and .78 for test, which also isn’t our best score but is up there with Random Forest. For my purposes, I chose to go with XGBoost and modified the parameters. My scores with the train test split data used above was .97 on train and .81 on test. My Kaggle score ended with .795 on the test data given. Once you’ve found the model that works best with the data you have, you can play with the parameters the model takes in and see if you can get an even better score. I hope this helps in your predictive modeling endeavors!
[ { "code": null, "e": 378, "s": 171, "text": "Whether you are working on predicting data in an office setting or just competing in a Kaggle competition, it’s important to test out different models to find the best fit for the data you are working with." }, { "code": null, "e": 616, "s": 378, "text": "I recently had the opportunity to compete with some very smart colleagues in a private Kaggle competition predicting faulty water pumps in Tanzania. I ran the following models after doing some data cleaning and I’ll show you the results." }, { "code": null, "e": 636, "s": 616, "text": "Logistic Regression" }, { "code": null, "e": 650, "s": 636, "text": "Random Forest" }, { "code": null, "e": 667, "s": 650, "text": "Ridge Regression" }, { "code": null, "e": 687, "s": 667, "text": "K-nearest Neighbors" }, { "code": null, "e": 695, "s": 687, "text": "XGBoost" }, { "code": null, "e": 840, "s": 695, "text": "First, we need to take a look at the data we’re working with. In this particular data set, the features were in a separate file than the labels." }, { "code": null, "e": 955, "s": 840, "text": "import pandas as pdpd.set_option('display.max_columns', None)X_df = pd.read_csv('./train_features.csv')X_df.head()" }, { "code": null, "e": 1007, "s": 955, "text": "y_df = pd.read_csv('./train_labels.csv')y_df.head()" }, { "code": null, "e": 1256, "s": 1007, "text": "We can see that the status_group or target label is a string, some models are able to work without having to modify that, but others don’t. We’ll do something about that when we get to it later. Let’s check out our distribution of the target label." }, { "code": null, "e": 1306, "s": 1256, "text": "y_df['status_group'].value_counts(normalize=True)" }, { "code": null, "e": 1646, "s": 1306, "text": "This split shows that we have exactly 3 classes in the label, so we have a multiclass classification. The majority class is ‘functional’, so if we were to just assign functional to all of the instances our model would be .54 on this training set. This is called the majority class baseline and is our target to beat with the models we run." }, { "code": null, "e": 1802, "s": 1646, "text": "There are a lot of features in this data set, so I’m not going to go into detail on every single thing I did, but I’ll go through high level, step by step." }, { "code": null, "e": 1884, "s": 1802, "text": "First, we want to check things out by looking at all the features and data types." }, { "code": null, "e": 1896, "s": 1884, "text": "X_df.info()" }, { "code": null, "e": 2048, "s": 1896, "text": "There are 30 object features that we’ll need to work with in order to be able to use them in a model. The int and float objects can just be used as is." }, { "code": null, "e": 2273, "s": 2048, "text": "Another thing to look at is high cardinality features. If we have more than 100 categories for each of these features, it won’t be very useful to use them. It would add dimensions to our dataset and we don’t want to do that." }, { "code": null, "e": 2487, "s": 2273, "text": "Before we drop these high cardinality columns though, I see that the date_recorded is an object and that will most definitely get dropped with our high cardinality features, so I created some features off of that." }, { "code": null, "e": 2785, "s": 2487, "text": "#So date doesn't get dropped in next stepX_df['date_recorded'] = pd.to_datetime(X_df['date_recorded'])X_df['YearMonth'] = X_df['date_recorded'].map(lambda x: 100*x.year + x.month)X_df['Year'] = X_df['date_recorded'].map(lambda x: x.year)X_df['Month'] = X_df['date_recorded'].map(lambda x: x.month)" }, { "code": null, "e": 2883, "s": 2785, "text": "Now that we’ve got the date sorted out we can check for high cardinality and drop those features." }, { "code": null, "e": 3090, "s": 2883, "text": "max_cardinality = 100high_cardinality = [col for col in X_df.select_dtypes(exclude=np.number) if X_df[col].nunique() > max_cardinality]X_df = X_df.drop(columns=high_cardinality)X_df.info()" }, { "code": null, "e": 3225, "s": 3090, "text": "So, we dropped 8 features with high cardinality. Now we can use OneHotEncoder or Pandas get_dummies() to change these objects to ints." }, { "code": null, "e": 3297, "s": 3225, "text": "Now that all our features are now numerical, let’s get into the models!" }, { "code": null, "e": 3446, "s": 3297, "text": "Logistic Regression is great for multiclass classification because Scikit-learn encodes encodes the target labels automatically if they are strings." }, { "code": null, "e": 3500, "s": 3446, "text": "First, we need to split our data into train and test." }, { "code": null, "e": 3800, "s": 3500, "text": "from sklearn.preprocessing import scalefrom sklearn.model_selection import train_test_splitX = X.drop(columns='id') #id is our index and won't help our modelX = scale(X) X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.75, test_size=0.25, random_state=42, shuffle=True)" }, { "code": null, "e": 3998, "s": 3800, "text": "When you’re working with a learning model, it is important to scale the features to a range which is centered around zero. Scaling will make sure the variance of the features are in the same range." }, { "code": null, "e": 4082, "s": 3998, "text": "Now, we’ll run the model on both train and test and see what our accuracy score is." }, { "code": null, "e": 4401, "s": 4082, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scorelogreg = LogisticRegression()logreg.fit(X_train,y_train)y_pred = logreg.predict(X_train)print('Train accuracy score:',accuracy_score(y_train,y_pred))print('Test accuracy score:', accuracy_score(y_test,logreg.predict(X_test)))" }, { "code": null, "e": 4537, "s": 4401, "text": "We’re definitely beating our majority class baseline of .54 here with .73 for train and test. Let’s see if another model can do better." }, { "code": null, "e": 4656, "s": 4537, "text": "Random Forest can also take strings as our target labels, so we can just run the model with the same train test split." }, { "code": null, "e": 4921, "s": 4656, "text": "from sklearn.ensemble import RandomForestClassifier as RFCrfc_b = RFC()rfc_b.fit(X_train,y_train)y_pred = rfc_b.predict(X_train)print('Train accuracy score:',accuracy_score(y_train,y_pred))print('Test accuracy score:', accuracy_score(y_test,rfc_b.predict(X_test)))" }, { "code": null, "e": 5014, "s": 4921, "text": "Random Forest beats Logistic Regression on train and test with .97 on train and .79 on test." }, { "code": null, "e": 5100, "s": 5014, "text": "For Ridge Regression we’ll need to encode the target labels before running the model." }, { "code": null, "e": 5378, "s": 5100, "text": "X = X_df.drop(columns=['id'])X = scale(X)y = y_df.drop(columns='id')y = y.replace({'functional':0, 'non functional':2,'functional needs repair':1 })X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.75, test_size=0.25, random_state=42, shuffle=True)" }, { "code": null, "e": 5534, "s": 5378, "text": "Now we run the model. Ridge outputs a probability in it’s predict() method, so we’ll have to update that with numpy in order to get the actual predictions." }, { "code": null, "e": 5890, "s": 5534, "text": "from sklearn.linear_model import Ridgeimport numpy as npridge = Ridge()ridge.fit(X_train,y_train)y_prob = ridge.predict(X_train)y_pred = np.asarray([np.argmax(line) for line in y_prob])yp_test = ridge.predict(X_test)test_preds = np.asarray([np.argmax(line) for line in yp_test])print(accuracy_score(y_train,y_pred))print(accuracy_score(y_test,test_preds))" }, { "code": null, "e": 5946, "s": 5890, "text": "So, Ridge Regression is not a good model for this data." }, { "code": null, "e": 6016, "s": 5946, "text": "We’ll use the same train test split as Ridge for K-Nearest Neighbors." }, { "code": null, "e": 6281, "s": 6016, "text": "from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier()knn.fit(X_train,y_train)y_pred = knn.predict(X_train)print('Train accuracy score:',accuracy_score(y_train,y_pred))print('Test accuracy score:',accuracy_score(y_test,knn.predict(X_test)))" }, { "code": null, "e": 6358, "s": 6281, "text": "These scores look a lot better than Ridge, but still aren’t our best scores." }, { "code": null, "e": 6495, "s": 6358, "text": "XGBoost is an algorithm that has been pretty popular in applied machine learning and Kaggle competitions for structured or tabular data." }, { "code": null, "e": 6590, "s": 6495, "text": "It is an implementation of gradient boosted decision trees designed for speed and performance." }, { "code": null, "e": 6780, "s": 6590, "text": "If you want to read more about it, check out there documentation here. I played with these parameters quite a bit when running this model and these were the best for the data I was running." }, { "code": null, "e": 7277, "s": 6780, "text": "xg_train = xgb.DMatrix(X_train, label=y_train)xg_test = xgb.DMatrix(X_test, label=y_test)xg_train.save_binary('train.buffer')xg_test.save_binary('train.buffer')# setup parameters for xgboostparam = {}# use softmax multi-class classificationparam['objective'] = 'multi:softmax'param['silent'] = 1 # cleans up the outputparam['num_class'] = 3 # number of classes in target labelwatchlist = [(xg_train, 'train'), (xg_test, 'test')]num_round = 30bst = xgb.train(param, xg_train, num_round, watchlist)" }, { "code": null, "e": 7352, "s": 7277, "text": "The output of the XGBoost classifier outputs an merror which is defined as" }, { "code": null, "e": 7446, "s": 7352, "text": "merror: Multiclass classification error rate. It is calculated as #(wrong cases)/#(all cases)" }, { "code": null, "e": 7659, "s": 7446, "text": "# get predictiony_pred1 = bst.predict(xg_train)y_pred2 = bst.predict(xg_test)print('Train accuracy score:',accuracy_score(y_train,y_pred1))print('Test accuracy score:',accuracy_score(y_test,bst.predict(xg_test)))" }, { "code": null, "e": 7766, "s": 7659, "text": "We get .79 for train and .78 for test, which also isn’t our best score but is up there with Random Forest." }, { "code": null, "e": 7981, "s": 7766, "text": "For my purposes, I chose to go with XGBoost and modified the parameters. My scores with the train test split data used above was .97 on train and .81 on test. My Kaggle score ended with .795 on the test data given." }, { "code": null, "e": 8146, "s": 7981, "text": "Once you’ve found the model that works best with the data you have, you can play with the parameters the model takes in and see if you can get an even better score." } ]
C++ Set Library - set() Function
The C++ constructor std::set::set() (Initializer-List Constructor) constructs a set container with the contents of the initializer list init Following is the declaration for std::set::set() Initializer-list constructor from std::set header. set (initializer_list<value_type> init, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); set (initializer_list<value_type> init, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()); set (initializer_list<value_type> init, const allocator_type& alloc = allocator_type()); alloc − Input iterator to initial position. alloc − Input iterator to initial position. comp − comparison function object to use for all comparisons of keys comp − comparison function object to use for all comparisons of keys init − init is a initializer_list object which initializes the set container elements. Elements present in the set container are of value_type (Member Type) init − init is a initializer_list object which initializes the set container elements. Elements present in the set container are of value_type (Member Type) Constructor never returns any value. This member function has no effect in case any exception is thrown. N log(N) in general, where N = init.size(); else, linear in N, i.e., O(N) if init is already sorted. The following example shows the usage of std::set::set() (initializer_list) constructor. #include <iostream> #include <set> #include <string> using namespace std; int main() { // Initializer list constructor std::set<std::string> fruit { "orange", "apple", "mango", "peach", "grape" }; std::cout << "Size of set container fruit is : " << fruit.size(); return 0; } Let us compile and run the above program, this will produce the following result − Size of set container fruit is : 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2744, "s": 2603, "text": "The C++ constructor std::set::set() (Initializer-List Constructor) constructs a set container with the contents of the initializer list init" }, { "code": null, "e": 2844, "s": 2744, "text": "Following is the declaration for std::set::set() Initializer-list constructor from std::set header." }, { "code": null, "e": 2985, "s": 2844, "text": "set (initializer_list<value_type> init,\n const key_compare& comp = key_compare(),\n const allocator_type& alloc = allocator_type());\n" }, { "code": null, "e": 3219, "s": 2985, "text": "set (initializer_list<value_type> init,\n const key_compare& comp = key_compare(),\n const allocator_type& alloc = allocator_type());\nset (initializer_list<value_type> init,\n const allocator_type& alloc = allocator_type());" }, { "code": null, "e": 3263, "s": 3219, "text": "alloc − Input iterator to initial position." }, { "code": null, "e": 3307, "s": 3263, "text": "alloc − Input iterator to initial position." }, { "code": null, "e": 3376, "s": 3307, "text": "comp − comparison function object to use for all comparisons of keys" }, { "code": null, "e": 3445, "s": 3376, "text": "comp − comparison function object to use for all comparisons of keys" }, { "code": null, "e": 3602, "s": 3445, "text": "init − init is a initializer_list object which initializes the set container elements. Elements present in the set container are of value_type (Member Type)" }, { "code": null, "e": 3759, "s": 3602, "text": "init − init is a initializer_list object which initializes the set container elements. Elements present in the set container are of value_type (Member Type)" }, { "code": null, "e": 3796, "s": 3759, "text": "Constructor never returns any value." }, { "code": null, "e": 3864, "s": 3796, "text": "This member function has no effect in case any exception is thrown." }, { "code": null, "e": 3908, "s": 3864, "text": "N log(N) in general, where N = init.size();" }, { "code": null, "e": 3965, "s": 3908, "text": "else, linear in N, i.e., O(N) if init is already sorted." }, { "code": null, "e": 4054, "s": 3965, "text": "The following example shows the usage of std::set::set() (initializer_list) constructor." }, { "code": null, "e": 4353, "s": 4054, "text": "#include <iostream>\n#include <set>\n#include <string>\n\nusing namespace std;\n\nint main() {\n // Initializer list constructor\n std::set<std::string> fruit {\n \"orange\", \"apple\", \"mango\", \"peach\", \"grape\"\n };\n\n std::cout << \"Size of set container fruit is : \" << fruit.size();\n return 0;\n}" }, { "code": null, "e": 4436, "s": 4353, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4472, "s": 4436, "text": "Size of set container fruit is : 5\n" }, { "code": null, "e": 4479, "s": 4472, "text": " Print" }, { "code": null, "e": 4490, "s": 4479, "text": " Add Notes" } ]
Concatenate null to a string in Java
To concatenate null to a string, use the + operator. Let’s say the following is our string. String str = "Demo Text"; We will now see how to effortlessly concatenate null to string. String strNULL = str + "null"; The following is the final example. Live Demo public class Demo { public static void main(String[] args) { String str = "Demo Text"; System.out.println("String = "+str); String strNULL = str + "null"; System.out.println("String concatenated with NULL: "+strNULL); } } String = Demo Text String concatenated with NULL: Demo Textnull
[ { "code": null, "e": 1115, "s": 1062, "text": "To concatenate null to a string, use the + operator." }, { "code": null, "e": 1154, "s": 1115, "text": "Let’s say the following is our string." }, { "code": null, "e": 1180, "s": 1154, "text": "String str = \"Demo Text\";" }, { "code": null, "e": 1244, "s": 1180, "text": "We will now see how to effortlessly concatenate null to string." }, { "code": null, "e": 1275, "s": 1244, "text": "String strNULL = str + \"null\";" }, { "code": null, "e": 1311, "s": 1275, "text": "The following is the final example." }, { "code": null, "e": 1322, "s": 1311, "text": " Live Demo" }, { "code": null, "e": 1580, "s": 1322, "text": "public class Demo {\n public static void main(String[] args) {\n String str = \"Demo Text\";\n System.out.println(\"String = \"+str);\n String strNULL = str + \"null\";\n System.out.println(\"String concatenated with NULL: \"+strNULL);\n }\n}" }, { "code": null, "e": 1644, "s": 1580, "text": "String = Demo Text\nString concatenated with NULL: Demo Textnull" } ]
Express.js res.headersSent Property - GeeksforGeeks
08 Jul, 2020 The res.headersSent property is a boolean property that indicates if the app sent HTTP headers for the response. Syntax: res.headersSent Parameter: No parameters. Return Value: This property returns a Boolean value either True or False. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { // Before res.send() console.log(res.headersSent); res.send('OK');}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000 false The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000 false Server listening on PORT 3000 false Example 2: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { res.send('OK'); // After res.send() console.log(res.headersSent); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Output:Now open your browser and make GET request to http://localhost:3000, now you can see the following output on your console: Server listening on PORT 3000 true Reference: https://expressjs.com/en/4x/api.html#res.headersSent Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.readFile() Method Node.js fs.writeFile() Method Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 29590, "s": 29562, "text": "\n08 Jul, 2020" }, { "code": null, "e": 29703, "s": 29590, "text": "The res.headersSent property is a boolean property that indicates if the app sent HTTP headers for the response." }, { "code": null, "e": 29711, "s": 29703, "text": "Syntax:" }, { "code": null, "e": 29727, "s": 29711, "text": "res.headersSent" }, { "code": null, "e": 29753, "s": 29727, "text": "Parameter: No parameters." }, { "code": null, "e": 29827, "s": 29753, "text": "Return Value: This property returns a Boolean value either True or False." }, { "code": null, "e": 29859, "s": 29827, "text": "Installation of express module:" }, { "code": null, "e": 30254, "s": 29859, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 30375, "s": 30254, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 30395, "s": 30375, "text": "npm install express" }, { "code": null, "e": 30523, "s": 30395, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 30543, "s": 30523, "text": "npm version express" }, { "code": null, "e": 30691, "s": 30543, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 30705, "s": 30691, "text": "node index.js" }, { "code": null, "e": 30735, "s": 30705, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { // Before res.send() console.log(res.headersSent); res.send('OK');}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 31041, "s": 30735, "text": null }, { "code": null, "e": 31067, "s": 31041, "text": "Steps to run the program:" }, { "code": null, "e": 31434, "s": 31067, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000\nfalse\n" }, { "code": null, "e": 31477, "s": 31434, "text": "The project structure will look like this:" }, { "code": null, "e": 31569, "s": 31477, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 31589, "s": 31569, "text": "npm install express" }, { "code": null, "e": 31678, "s": 31589, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 31692, "s": 31678, "text": "node index.js" }, { "code": null, "e": 31700, "s": 31692, "text": "Output:" }, { "code": null, "e": 31731, "s": 31700, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 31877, "s": 31731, "text": "Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:Server listening on PORT 3000\nfalse\n" }, { "code": null, "e": 31914, "s": 31877, "text": "Server listening on PORT 3000\nfalse\n" }, { "code": null, "e": 31944, "s": 31914, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { res.send('OK'); // After res.send() console.log(res.headersSent); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 32249, "s": 31944, "text": null }, { "code": null, "e": 32288, "s": 32249, "text": "Run index.js file using below command:" }, { "code": null, "e": 32302, "s": 32288, "text": "node index.js" }, { "code": null, "e": 32432, "s": 32302, "text": "Output:Now open your browser and make GET request to http://localhost:3000, now you can see the following output on your console:" }, { "code": null, "e": 32468, "s": 32432, "text": "Server listening on PORT 3000\ntrue\n" }, { "code": null, "e": 32532, "s": 32468, "text": "Reference: https://expressjs.com/en/4x/api.html#res.headersSent" }, { "code": null, "e": 32543, "s": 32532, "text": "Express.js" }, { "code": null, "e": 32551, "s": 32543, "text": "Node.js" }, { "code": null, "e": 32568, "s": 32551, "text": "Web Technologies" }, { "code": null, "e": 32666, "s": 32568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32675, "s": 32666, "text": "Comments" }, { "code": null, "e": 32688, "s": 32675, "text": "Old Comments" }, { "code": null, "e": 32721, "s": 32688, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32769, "s": 32721, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32802, "s": 32769, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 32831, "s": 32802, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 32861, "s": 32831, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 32903, "s": 32861, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32936, "s": 32903, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32998, "s": 32936, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33041, "s": 32998, "text": "How to fetch data from an API in ReactJS ?" } ]
Reader close() method in Java with Examples - GeeksforGeeks
13 Feb, 2019 The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources If the stream is already closed, it will have no effect. If any read or other similar operation is performed on the stream, after closing, it raises IOException Syntax: public abstract void close() Parameters: This method does not accepts any parameters Return Value: This method do not returns any value. Exception: This method throws IOException if some error occurs while input output. Below methods illustrates the working of close() method: Program 1: // Java program to demonstrate// Reader close() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 5 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.println("\nInteger value " + "of character read: " + ch); System.out.println("Actual " + "character read: " + (char)ch); } // Close the stream using close() reader.close(); System.out.println("Stream Closed."); } catch (Exception e) { System.out.println(e); } }} Integer value of character read: 71 Actual character read: G Integer value of character read: 101 Actual character read: e Integer value of character read: 101 Actual character read: e Integer value of character read: 107 Actual character read: k Integer value of character read: 115 Actual character read: s Stream Closed. Program 2: // Java program to demonstrate// Reader close() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Close the stream using close() reader.close(); System.out.println("Stream Closed."); // Check if the Reader is // ready to be read using ready() System.out.println("Is Reader ready " + "to be read" + reader.ready()); } catch (Exception e) { System.out.println(e); } }} Stream Closed. java.io.IOException: Stream closed Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#close– Java-Functions Java-IO package Java-Reader Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples Introduction to Java HashMap get() Method in Java Strings in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n13 Feb, 2019" }, { "code": null, "e": 24118, "s": 23948, "text": "The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results:" }, { "code": null, "e": 24186, "s": 24118, "text": "If the stream is open, it closes the stream releasing the resources" }, { "code": null, "e": 24243, "s": 24186, "text": "If the stream is already closed, it will have no effect." }, { "code": null, "e": 24347, "s": 24243, "text": "If any read or other similar operation is performed on the stream, after closing, it raises IOException" }, { "code": null, "e": 24355, "s": 24347, "text": "Syntax:" }, { "code": null, "e": 24384, "s": 24355, "text": "public abstract void close()" }, { "code": null, "e": 24440, "s": 24384, "text": "Parameters: This method does not accepts any parameters" }, { "code": null, "e": 24492, "s": 24440, "text": "Return Value: This method do not returns any value." }, { "code": null, "e": 24575, "s": 24492, "text": "Exception: This method throws IOException if some error occurs while input output." }, { "code": null, "e": 24632, "s": 24575, "text": "Below methods illustrates the working of close() method:" }, { "code": null, "e": 24643, "s": 24632, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Reader close() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 5 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.println(\"\\nInteger value \" + \"of character read: \" + ch); System.out.println(\"Actual \" + \"character read: \" + (char)ch); } // Close the stream using close() reader.close(); System.out.println(\"Stream Closed.\"); } catch (Exception e) { System.out.println(e); } }}", "e": 25838, "s": 24643, "text": null }, { "code": null, "e": 26167, "s": 25838, "text": "Integer value of character read: 71\nActual character read: G\n\nInteger value of character read: 101\nActual character read: e\n\nInteger value of character read: 101\nActual character read: e\n\nInteger value of character read: 107\nActual character read: k\n\nInteger value of character read: 115\nActual character read: s\nStream Closed.\n" }, { "code": null, "e": 26178, "s": 26167, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Reader close() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Close the stream using close() reader.close(); System.out.println(\"Stream Closed.\"); // Check if the Reader is // ready to be read using ready() System.out.println(\"Is Reader ready \" + \"to be read\" + reader.ready()); } catch (Exception e) { System.out.println(e); } }}", "e": 26930, "s": 26178, "text": null }, { "code": null, "e": 26981, "s": 26930, "text": "Stream Closed.\njava.io.IOException: Stream closed\n" }, { "code": null, "e": 27061, "s": 26981, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#close–" }, { "code": null, "e": 27076, "s": 27061, "text": "Java-Functions" }, { "code": null, "e": 27092, "s": 27076, "text": "Java-IO package" }, { "code": null, "e": 27104, "s": 27092, "text": "Java-Reader" }, { "code": null, "e": 27109, "s": 27104, "text": "Java" }, { "code": null, "e": 27114, "s": 27109, "text": "Java" }, { "code": null, "e": 27212, "s": 27114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27227, "s": 27212, "text": "Stream In Java" }, { "code": null, "e": 27248, "s": 27227, "text": "Constructors in Java" }, { "code": null, "e": 27294, "s": 27248, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27313, "s": 27294, "text": "Exceptions in Java" }, { "code": null, "e": 27343, "s": 27313, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27360, "s": 27343, "text": "Generics in Java" }, { "code": null, "e": 27403, "s": 27360, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27424, "s": 27403, "text": "Introduction to Java" }, { "code": null, "e": 27453, "s": 27424, "text": "HashMap get() Method in Java" } ]
Custom neural networks in Keras: a street fighter’s guide to build a graphCNN | by Shuyi Yang | Towards Data Science
At a certain point in our lives, predefined layers in Tensorflow Keras are not enough anymore! We want more! We want to build custom neural networks with creative structures and bizarre layers! Luckily for us, we can easily perform this task within Keras by defining our custom layers and models. In this step-by-step tutorial we are going to build a neural network with parallel layers including graph convolutional one. Wait a minute! What is the convolution on a graph? In a traditional neural network layer we perform a matrix multiplication between the layer input matrix X and the trainable weights matrix W. Then we apply an activation function f. Hence, the input of the next layer (output of the current layer) can be represented as f(XW). In a graph convolutional neural network, we suppose that similar instances are connected in a graph (eg. citation network, distance-based networks, etc.) and the features coming from the neighborhood could be useful in a (un)supervised task. Let A be the adjacency matrix of the graph, then the operation we are going to perform in a convolutional layer is f(AXW). For each node of the graph, we are going to aggregate the features from other connected nodes and then multiply this aggregation by the weights matrix and then apply the activation. This formulation of graph convolution is the simplest one. It’s fine for our tutorial but graphCNN is much more! Ok! Now, we are ready! Firstly, we need to import some packages. # Import packagesfrom tensorflow import __version__ as tf_version, float32 as tf_float32, Variablefrom tensorflow.keras import Sequential, Modelfrom tensorflow.keras.backend import variable, dot as k_dot, sigmoid, relufrom tensorflow.keras.layers import Dense, Input, Concatenate, Layerfrom tensorflow.keras.losses import SparseCategoricalCrossentropyfrom tensorflow.keras.utils import plot_modelfrom tensorflow.random import set_seed as tf_set_seedfrom numpy import __version__ as np_version, unique, array, mean, argmaxfrom numpy.random import seed as np_seed, choicefrom pandas import __version__ as pd_version, read_csv, DataFrame, concatfrom sklearn import __version__ as sk_versionfrom sklearn.preprocessing import normalizeprint("tensorflow version:", tf_version)print("numpy version:", np_version)print("pandas version:", pd_version)print("scikit-learn version:", sk_version) You should receive as output the versions of the imported packages. In my case the output is: tensorflow version: 2.2.0 numpy version: 1.18.5 pandas version: 1.0.4 scikit-learn version: 0.22.2.post1 In this tutorial, we are going to use the CORA dataset: The Cora dataset consists of 2708 scientific publications classified into one of seven classes. The citation network consists of 5429 links. Each publication in the dataset is described by a 0/1-valued word vector indicating the absence/presence of the corresponding word from the dictionary. The dictionary consists of 1433 unique words. Let’s load the data, create the adjacency matrix and prepare the features matrix. # Load cora datadtf_data = read_csv("https://raw.githubusercontent.com/ngshya/datasets/master/cora/cora_content.csv").sort_values(["paper_id"], ascending=True)dtf_graph = read_csv("https://raw.githubusercontent.com/ngshya/datasets/master/cora/cora_cites.csv")# Adjacency matrixarray_papers_id = unique(dtf_data["paper_id"])dtf_graph["connection"] = 1dtf_graph_tmp = DataFrame({"cited_paper_id": array_papers_id, "citing_paper_id": array_papers_id, "connection": 0})dtf_graph = concat((dtf_graph, dtf_graph_tmp)).sort_values(["cited_paper_id", "citing_paper_id"], ascending=True)dtf_graph = dtf_graph.pivot_table(index="cited_paper_id", columns="citing_paper_id", values="connection", fill_value=0).reset_index(drop=True)A = array(dtf_graph)A = normalize(A, norm='l1', axis=1)A = variable(A, dtype=tf_float32)# Feature matrixdata = array(dtf_data.iloc[:, 1:1434])# Labelslabels = array( dtf_data["label"].map({ 'Case_Based': 0, 'Genetic_Algorithms': 1, 'Neural_Networks': 2, 'Probabilistic_Methods': 3, 'Reinforcement_Learning': 4, 'Rule_Learning': 5, 'Theory': 6 }))# Check dimensionsprint("Features matrix dimension:", data.shape, "| Label array dimension:", labels.shape, "| Adjacency matrix dimension:", A.shape) Lastly, let’s define some parameters useful for the training of neural networks. # Training parametersinput_shape = (data.shape[1], )output_classes = len(unique(labels))iterations = 50epochs = 100batch_size = data.shape[0]labeled_portion = 0.10 As you can deduce from the code above, for each model, we are going to perform 50 iterations and in each iteration we will randomly choose a 10% labeled set (training set) and train the model for 100 epochs. It is important to point out that the scope of this tutorial is not training the most accurate model on CORA dataset. Instead, we just want to provide an example of implementing custom models with keras custom layers! As baseline, we use a standard neural network with sequential layers (a familiar keras sequential model). # Model 1: standard sequential neural networktf_set_seed(1102)np_seed(1102)model1 = Sequential([ Dense(32, input_shape=input_shape, activation='relu'), Dense(16, activation='relu'), Dense(output_classes, activation='softmax')], name="Model_1")model1.save_weights("model1_initial_weights.h5")model1.summary()plot_model(model1, 'model1.png', show_shapes=True) We can plot the model to see the sequential structure. Let’s see how this model perform. # Testing model 1tf_set_seed(1102)np_seed(1102)acc_model1 = []for _ in range(iterations): mask = choice([True, False], size=data.shape[0], replace=True, p=[labeled_portion, 1-labeled_portion]) labeled_data = data[mask, :] unlabeled_data = data[~mask, :] labeled_data_labels = labels[mask] unlabeled_data_labels = labels[~mask] model1.load_weights("model1_initial_weights.h5") model1.compile( optimizer='adam', loss=SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy'] ) model1.fit(labeled_data, labeled_data_labels, epochs=epochs, batch_size=batch_size, verbose=0) acc_model1.append(sum(argmax(model1.predict(unlabeled_data, batch_size=batch_size), axis=1) == unlabeled_data_labels) / len(unlabeled_data_labels) * 100)print("\nAverage accuracy on unlabeled set:", mean(acc_model1), "%") You should obtain an average accuracy of 55%. Let’s introduce a small modification to the previous model. This time we want to have a network with two parallel hidden layers. We use Keras Functional API. With the functional API we can build models with non-linear topology, models with shared layers, and models with multiple inputs or outputs. Basically, we need to assign each layer to a variable and then refer to the variable to concatenate different layers in order to create a directed acyclic graph (DAG). Then the model can be built by passing the input layer(s) and the output layer(s). # Model 2: neural network with parallel layerstf_set_seed(1102)np_seed(1102)m2_input_layer = Input(shape=input_shape)m2_dense_layer_1 = Dense(32, activation='relu')(m2_input_layer)m2_dense_layer_2 = Dense(16, activation='relu')(m2_input_layer)m2_merged_layer = Concatenate()([m2_dense_layer_1, m2_dense_layer_2])m2_final_layer = Dense(output_classes, activation='softmax')(m2_merged_layer)model2 = Model(inputs=m2_input_layer, outputs=m2_final_layer, name="Model_2")model2.save_weights("model2_initial_weights.h5")model2.summary()plot_model(model2, 'model2.png', show_shapes=True) The parallel layers m2_dense_layer_1 and m2_dense_layer_2 depend on the same input layer m2_input_layer, and are then concatenated to form a unique layer in m2_merged_layer. This neural network should look like: Let’s test this model. # Testing model 2tf_set_seed(1102)np_seed(1102)acc_model2 = []for _ in range(iterations): mask = choice([True, False], size=data.shape[0], replace=True, p=[labeled_portion, 1-labeled_portion]) labeled_data = data[mask, :] unlabeled_data = data[~mask, :] labeled_data_labels = labels[mask] unlabeled_data_labels = labels[~mask] model2.load_weights("model2_initial_weights.h5") model2.compile( optimizer='adam', loss=SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy'] ) model2.fit(labeled_data, labeled_data_labels, epochs=epochs, batch_size=batch_size, shuffle=False, verbose=0) acc_model2.append(sum(argmax(model2.predict(unlabeled_data, batch_size=batch_size), axis=1) == unlabeled_data_labels) / len(unlabeled_data_labels) * 100)print("\nAverage accuracy on unlabeled set:", mean(acc_model2), "%") The average accuracy is nearly 60% (+5)! So far, we have seen how to create custom network structure with Keras Functional API. What if we need to define custom layers with user-defined operations? In our case, we would like to define a simple graph convolutional layer as explained at the beginning of this tutorial. To this end, we need to create a subclass from the class Layer and define the methods __init__, build and call. # Graph convolutional layerclass GraphConv(Layer): def __init__(self, num_outputs, A, activation="sigmoid", **kwargs): super(GraphConv, self).__init__(**kwargs) self.num_outputs = num_outputs self.activation_function = activation self.A = Variable(A, trainable=False) def build(self, input_shape): # Weights self.W = self.add_weight("W", shape=[int(input_shape[-1]), self.num_outputs]) # bias self.bias = self.add_weight("bias", shape=[self.num_outputs]) def call(self, input): if self.activation_function == 'relu': return relu(k_dot(k_dot(self.A, input), self.W) + self.bias) else: return sigmoid(k_dot(k_dot(self.A, input), self.W) + self.bias) During the inititialization, you can require and save any useful parameter (eg. activation function, number of output neurons). In our example, we require also the adjacency matrix A. In the build method, the trainable weights of the layer are initialized. In the call method, the forward pass computation is declared. As in the previous model, we define a network with parallel layers. # Model 3: neural network with graph convolutional layertf_set_seed(1102)np_seed(1102)m3_input_layer = Input(shape=input_shape)m3_dense_layer = Dense(32, activation='relu')(m3_input_layer)m3_gc_layer = GraphConv(16, A=A, activation='relu')(m3_input_layer)m3_merged_layer = Concatenate()([m3_dense_layer, m3_gc_layer])m3_final_layer = Dense(output_classes, activation='softmax')(m3_merged_layer)model3 = Model(inputs=m3_input_layer, outputs=m3_final_layer, name="Model_3")model3.save_weights("model3_initial_weights.h5")model3.summary()plot_model(model3, 'model3.png', show_shapes=True) It looks like the previous model but one layer is convolutional: intrinsict features of each instance are concatenated with the aggregated features computed from the neighbourhood. Further attention should be paid when compiling this model. Since the convolutional layer requires the entire adjacency matrix, we need to pass the entire features matrix (labeled and unlabeled instances) but the model should be trained only on labeled instances. Therefore, we define a custom loss function where the sparse categorical cossentropy is computed only on the labeled instances. Additionally, we randomize the labels of unlabaled instances in order to be sure that they are not used during the training. # Testing model 3tf_set_seed(1102)np_seed(1102)acc_model3 = []for i in range(iterations): mask = choice([True, False], size=data.shape[0], replace=True, p=[labeled_portion, 1-labeled_portion]) unlabeled_data_labels = labels[~mask] # Randomize the labels of unlabeled instances masked_labels = labels.copy() masked_labels[~mask] = choice(range(7), size=sum(~mask), replace=True) model3.load_weights("model3_initial_weights.h5") model3.compile( optimizer='adam', loss=lambda y_true, y_pred: SparseCategoricalCrossentropy(from_logits=False)(y_true[mask], y_pred[mask]), metrics=['accuracy'] ) model3.fit(data, masked_labels, epochs=epochs, batch_size=batch_size, shuffle=False, verbose=0) predictions = argmax(model3.predict(data, batch_size=batch_size), axis=1) acc_model3.append(sum(predictions[~mask] == unlabeled_data_labels) / len(unlabeled_data_labels) * 100)print("\nAverage accuracy on unlabeled set:", mean(acc_model3), "%") This experiment produces an average accuracy of 63% (+3). Interestingly, in this last experiment we are basically performing a semi-supervised learning with graphCNN: information from the unlabeled instances are used altogether with the labeled ones to build a graph-based transductive model. The complete Jupyter Notebook containing the code can be found here. https://tkipf.github.io/graph-convolutional-networks/ https://www.tensorflow.org/api_docs/python/tf/keras Contacts: LinkedIn | Twitter
[ { "code": null, "e": 645, "s": 172, "text": "At a certain point in our lives, predefined layers in Tensorflow Keras are not enough anymore! We want more! We want to build custom neural networks with creative structures and bizarre layers! Luckily for us, we can easily perform this task within Keras by defining our custom layers and models. In this step-by-step tutorial we are going to build a neural network with parallel layers including graph convolutional one. Wait a minute! What is the convolution on a graph?" }, { "code": null, "e": 1581, "s": 645, "text": "In a traditional neural network layer we perform a matrix multiplication between the layer input matrix X and the trainable weights matrix W. Then we apply an activation function f. Hence, the input of the next layer (output of the current layer) can be represented as f(XW). In a graph convolutional neural network, we suppose that similar instances are connected in a graph (eg. citation network, distance-based networks, etc.) and the features coming from the neighborhood could be useful in a (un)supervised task. Let A be the adjacency matrix of the graph, then the operation we are going to perform in a convolutional layer is f(AXW). For each node of the graph, we are going to aggregate the features from other connected nodes and then multiply this aggregation by the weights matrix and then apply the activation. This formulation of graph convolution is the simplest one. It’s fine for our tutorial but graphCNN is much more!" }, { "code": null, "e": 1604, "s": 1581, "text": "Ok! Now, we are ready!" }, { "code": null, "e": 1646, "s": 1604, "text": "Firstly, we need to import some packages." }, { "code": null, "e": 2530, "s": 1646, "text": "# Import packagesfrom tensorflow import __version__ as tf_version, float32 as tf_float32, Variablefrom tensorflow.keras import Sequential, Modelfrom tensorflow.keras.backend import variable, dot as k_dot, sigmoid, relufrom tensorflow.keras.layers import Dense, Input, Concatenate, Layerfrom tensorflow.keras.losses import SparseCategoricalCrossentropyfrom tensorflow.keras.utils import plot_modelfrom tensorflow.random import set_seed as tf_set_seedfrom numpy import __version__ as np_version, unique, array, mean, argmaxfrom numpy.random import seed as np_seed, choicefrom pandas import __version__ as pd_version, read_csv, DataFrame, concatfrom sklearn import __version__ as sk_versionfrom sklearn.preprocessing import normalizeprint(\"tensorflow version:\", tf_version)print(\"numpy version:\", np_version)print(\"pandas version:\", pd_version)print(\"scikit-learn version:\", sk_version)" }, { "code": null, "e": 2624, "s": 2530, "text": "You should receive as output the versions of the imported packages. In my case the output is:" }, { "code": null, "e": 2729, "s": 2624, "text": "tensorflow version: 2.2.0 numpy version: 1.18.5 pandas version: 1.0.4 scikit-learn version: 0.22.2.post1" }, { "code": null, "e": 2785, "s": 2729, "text": "In this tutorial, we are going to use the CORA dataset:" }, { "code": null, "e": 3124, "s": 2785, "text": "The Cora dataset consists of 2708 scientific publications classified into one of seven classes. The citation network consists of 5429 links. Each publication in the dataset is described by a 0/1-valued word vector indicating the absence/presence of the corresponding word from the dictionary. The dictionary consists of 1433 unique words." }, { "code": null, "e": 3206, "s": 3124, "text": "Let’s load the data, create the adjacency matrix and prepare the features matrix." }, { "code": null, "e": 4477, "s": 3206, "text": "# Load cora datadtf_data = read_csv(\"https://raw.githubusercontent.com/ngshya/datasets/master/cora/cora_content.csv\").sort_values([\"paper_id\"], ascending=True)dtf_graph = read_csv(\"https://raw.githubusercontent.com/ngshya/datasets/master/cora/cora_cites.csv\")# Adjacency matrixarray_papers_id = unique(dtf_data[\"paper_id\"])dtf_graph[\"connection\"] = 1dtf_graph_tmp = DataFrame({\"cited_paper_id\": array_papers_id, \"citing_paper_id\": array_papers_id, \"connection\": 0})dtf_graph = concat((dtf_graph, dtf_graph_tmp)).sort_values([\"cited_paper_id\", \"citing_paper_id\"], ascending=True)dtf_graph = dtf_graph.pivot_table(index=\"cited_paper_id\", columns=\"citing_paper_id\", values=\"connection\", fill_value=0).reset_index(drop=True)A = array(dtf_graph)A = normalize(A, norm='l1', axis=1)A = variable(A, dtype=tf_float32)# Feature matrixdata = array(dtf_data.iloc[:, 1:1434])# Labelslabels = array( dtf_data[\"label\"].map({ 'Case_Based': 0, 'Genetic_Algorithms': 1, 'Neural_Networks': 2, 'Probabilistic_Methods': 3, 'Reinforcement_Learning': 4, 'Rule_Learning': 5, 'Theory': 6 }))# Check dimensionsprint(\"Features matrix dimension:\", data.shape, \"| Label array dimension:\", labels.shape, \"| Adjacency matrix dimension:\", A.shape)" }, { "code": null, "e": 4558, "s": 4477, "text": "Lastly, let’s define some parameters useful for the training of neural networks." }, { "code": null, "e": 4722, "s": 4558, "text": "# Training parametersinput_shape = (data.shape[1], )output_classes = len(unique(labels))iterations = 50epochs = 100batch_size = data.shape[0]labeled_portion = 0.10" }, { "code": null, "e": 4930, "s": 4722, "text": "As you can deduce from the code above, for each model, we are going to perform 50 iterations and in each iteration we will randomly choose a 10% labeled set (training set) and train the model for 100 epochs." }, { "code": null, "e": 5148, "s": 4930, "text": "It is important to point out that the scope of this tutorial is not training the most accurate model on CORA dataset. Instead, we just want to provide an example of implementing custom models with keras custom layers!" }, { "code": null, "e": 5254, "s": 5148, "text": "As baseline, we use a standard neural network with sequential layers (a familiar keras sequential model)." }, { "code": null, "e": 5621, "s": 5254, "text": "# Model 1: standard sequential neural networktf_set_seed(1102)np_seed(1102)model1 = Sequential([ Dense(32, input_shape=input_shape, activation='relu'), Dense(16, activation='relu'), Dense(output_classes, activation='softmax')], name=\"Model_1\")model1.save_weights(\"model1_initial_weights.h5\")model1.summary()plot_model(model1, 'model1.png', show_shapes=True)" }, { "code": null, "e": 5676, "s": 5621, "text": "We can plot the model to see the sequential structure." }, { "code": null, "e": 5710, "s": 5676, "text": "Let’s see how this model perform." }, { "code": null, "e": 6566, "s": 5710, "text": "# Testing model 1tf_set_seed(1102)np_seed(1102)acc_model1 = []for _ in range(iterations): mask = choice([True, False], size=data.shape[0], replace=True, p=[labeled_portion, 1-labeled_portion]) labeled_data = data[mask, :] unlabeled_data = data[~mask, :] labeled_data_labels = labels[mask] unlabeled_data_labels = labels[~mask] model1.load_weights(\"model1_initial_weights.h5\") model1.compile( optimizer='adam', loss=SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy'] ) model1.fit(labeled_data, labeled_data_labels, epochs=epochs, batch_size=batch_size, verbose=0) acc_model1.append(sum(argmax(model1.predict(unlabeled_data, batch_size=batch_size), axis=1) == unlabeled_data_labels) / len(unlabeled_data_labels) * 100)print(\"\\nAverage accuracy on unlabeled set:\", mean(acc_model1), \"%\")" }, { "code": null, "e": 6612, "s": 6566, "text": "You should obtain an average accuracy of 55%." }, { "code": null, "e": 7162, "s": 6612, "text": "Let’s introduce a small modification to the previous model. This time we want to have a network with two parallel hidden layers. We use Keras Functional API. With the functional API we can build models with non-linear topology, models with shared layers, and models with multiple inputs or outputs. Basically, we need to assign each layer to a variable and then refer to the variable to concatenate different layers in order to create a directed acyclic graph (DAG). Then the model can be built by passing the input layer(s) and the output layer(s)." }, { "code": null, "e": 7743, "s": 7162, "text": "# Model 2: neural network with parallel layerstf_set_seed(1102)np_seed(1102)m2_input_layer = Input(shape=input_shape)m2_dense_layer_1 = Dense(32, activation='relu')(m2_input_layer)m2_dense_layer_2 = Dense(16, activation='relu')(m2_input_layer)m2_merged_layer = Concatenate()([m2_dense_layer_1, m2_dense_layer_2])m2_final_layer = Dense(output_classes, activation='softmax')(m2_merged_layer)model2 = Model(inputs=m2_input_layer, outputs=m2_final_layer, name=\"Model_2\")model2.save_weights(\"model2_initial_weights.h5\")model2.summary()plot_model(model2, 'model2.png', show_shapes=True)" }, { "code": null, "e": 7955, "s": 7743, "text": "The parallel layers m2_dense_layer_1 and m2_dense_layer_2 depend on the same input layer m2_input_layer, and are then concatenated to form a unique layer in m2_merged_layer. This neural network should look like:" }, { "code": null, "e": 7978, "s": 7955, "text": "Let’s test this model." }, { "code": null, "e": 8849, "s": 7978, "text": "# Testing model 2tf_set_seed(1102)np_seed(1102)acc_model2 = []for _ in range(iterations): mask = choice([True, False], size=data.shape[0], replace=True, p=[labeled_portion, 1-labeled_portion]) labeled_data = data[mask, :] unlabeled_data = data[~mask, :] labeled_data_labels = labels[mask] unlabeled_data_labels = labels[~mask] model2.load_weights(\"model2_initial_weights.h5\") model2.compile( optimizer='adam', loss=SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy'] ) model2.fit(labeled_data, labeled_data_labels, epochs=epochs, batch_size=batch_size, shuffle=False, verbose=0) acc_model2.append(sum(argmax(model2.predict(unlabeled_data, batch_size=batch_size), axis=1) == unlabeled_data_labels) / len(unlabeled_data_labels) * 100)print(\"\\nAverage accuracy on unlabeled set:\", mean(acc_model2), \"%\")" }, { "code": null, "e": 8890, "s": 8849, "text": "The average accuracy is nearly 60% (+5)!" }, { "code": null, "e": 9279, "s": 8890, "text": "So far, we have seen how to create custom network structure with Keras Functional API. What if we need to define custom layers with user-defined operations? In our case, we would like to define a simple graph convolutional layer as explained at the beginning of this tutorial. To this end, we need to create a subclass from the class Layer and define the methods __init__, build and call." }, { "code": null, "e": 10028, "s": 9279, "text": "# Graph convolutional layerclass GraphConv(Layer): def __init__(self, num_outputs, A, activation=\"sigmoid\", **kwargs): super(GraphConv, self).__init__(**kwargs) self.num_outputs = num_outputs self.activation_function = activation self.A = Variable(A, trainable=False) def build(self, input_shape): # Weights self.W = self.add_weight(\"W\", shape=[int(input_shape[-1]), self.num_outputs]) # bias self.bias = self.add_weight(\"bias\", shape=[self.num_outputs]) def call(self, input): if self.activation_function == 'relu': return relu(k_dot(k_dot(self.A, input), self.W) + self.bias) else: return sigmoid(k_dot(k_dot(self.A, input), self.W) + self.bias)" }, { "code": null, "e": 10347, "s": 10028, "text": "During the inititialization, you can require and save any useful parameter (eg. activation function, number of output neurons). In our example, we require also the adjacency matrix A. In the build method, the trainable weights of the layer are initialized. In the call method, the forward pass computation is declared." }, { "code": null, "e": 10415, "s": 10347, "text": "As in the previous model, we define a network with parallel layers." }, { "code": null, "e": 11001, "s": 10415, "text": "# Model 3: neural network with graph convolutional layertf_set_seed(1102)np_seed(1102)m3_input_layer = Input(shape=input_shape)m3_dense_layer = Dense(32, activation='relu')(m3_input_layer)m3_gc_layer = GraphConv(16, A=A, activation='relu')(m3_input_layer)m3_merged_layer = Concatenate()([m3_dense_layer, m3_gc_layer])m3_final_layer = Dense(output_classes, activation='softmax')(m3_merged_layer)model3 = Model(inputs=m3_input_layer, outputs=m3_final_layer, name=\"Model_3\")model3.save_weights(\"model3_initial_weights.h5\")model3.summary()plot_model(model3, 'model3.png', show_shapes=True)" }, { "code": null, "e": 11182, "s": 11001, "text": "It looks like the previous model but one layer is convolutional: intrinsict features of each instance are concatenated with the aggregated features computed from the neighbourhood." }, { "code": null, "e": 11699, "s": 11182, "text": "Further attention should be paid when compiling this model. Since the convolutional layer requires the entire adjacency matrix, we need to pass the entire features matrix (labeled and unlabeled instances) but the model should be trained only on labeled instances. Therefore, we define a custom loss function where the sparse categorical cossentropy is computed only on the labeled instances. Additionally, we randomize the labels of unlabaled instances in order to be sure that they are not used during the training." }, { "code": null, "e": 12685, "s": 11699, "text": "# Testing model 3tf_set_seed(1102)np_seed(1102)acc_model3 = []for i in range(iterations): mask = choice([True, False], size=data.shape[0], replace=True, p=[labeled_portion, 1-labeled_portion]) unlabeled_data_labels = labels[~mask] # Randomize the labels of unlabeled instances masked_labels = labels.copy() masked_labels[~mask] = choice(range(7), size=sum(~mask), replace=True) model3.load_weights(\"model3_initial_weights.h5\") model3.compile( optimizer='adam', loss=lambda y_true, y_pred: SparseCategoricalCrossentropy(from_logits=False)(y_true[mask], y_pred[mask]), metrics=['accuracy'] ) model3.fit(data, masked_labels, epochs=epochs, batch_size=batch_size, shuffle=False, verbose=0) predictions = argmax(model3.predict(data, batch_size=batch_size), axis=1) acc_model3.append(sum(predictions[~mask] == unlabeled_data_labels) / len(unlabeled_data_labels) * 100)print(\"\\nAverage accuracy on unlabeled set:\", mean(acc_model3), \"%\")" }, { "code": null, "e": 12743, "s": 12685, "text": "This experiment produces an average accuracy of 63% (+3)." }, { "code": null, "e": 12978, "s": 12743, "text": "Interestingly, in this last experiment we are basically performing a semi-supervised learning with graphCNN: information from the unlabeled instances are used altogether with the labeled ones to build a graph-based transductive model." }, { "code": null, "e": 13047, "s": 12978, "text": "The complete Jupyter Notebook containing the code can be found here." }, { "code": null, "e": 13101, "s": 13047, "text": "https://tkipf.github.io/graph-convolutional-networks/" }, { "code": null, "e": 13153, "s": 13101, "text": "https://www.tensorflow.org/api_docs/python/tf/keras" } ]
Finding count of special characters in a string in JavaScript
Let’s say that we have a string that may contain any of the following characters. '!', "," ,"\'" ,";" ,"\"", ".", "-" ,"?" We are required to write a JavaScript function that takes in a string and count the number of appearances of these characters in the string and return that count. The code for this will be − const str = "This, is a-sentence;.Is this a sentence?"; const countSpecial = str => { const punct = "!,\;\.-?"; let count = 0; for(let i = 0; i < str.length; i++){ if(!punct.includes(str[i])){ continue; }; count++; }; return count; }; console.log(countSpecial(str)); The output in the console − 5
[ { "code": null, "e": 1144, "s": 1062, "text": "Let’s say that we have a string that may contain any of the following characters." }, { "code": null, "e": 1185, "s": 1144, "text": "'!', \",\" ,\"\\'\" ,\";\" ,\"\\\"\", \".\", \"-\" ,\"?\"" }, { "code": null, "e": 1348, "s": 1185, "text": "We are required to write a JavaScript function that takes in a string and count the number of\nappearances of these characters in the string and return that count." }, { "code": null, "e": 1376, "s": 1348, "text": "The code for this will be −" }, { "code": null, "e": 1685, "s": 1376, "text": "const str = \"This, is a-sentence;.Is this a sentence?\";\nconst countSpecial = str => {\n const punct = \"!,\\;\\.-?\";\n let count = 0;\n for(let i = 0; i < str.length; i++){\n if(!punct.includes(str[i])){\n continue;\n };\n count++;\n };\n return count;\n};\nconsole.log(countSpecial(str));" }, { "code": null, "e": 1713, "s": 1685, "text": "The output in the console −" }, { "code": null, "e": 1715, "s": 1713, "text": "5" } ]
jsoup - Set Attributes
Following example will showcase use of method to set attributes of a dom element, bulk updates and add/remove class methods after parsing an HTML String into a Document object. Document document = Jsoup.parse(html); Element link = document.select("a").first(); link.attr("href","www.yahoo.com"); link.addClass("header"); link.removeClass("header"); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to parse the given HTML String. Jsoup − main class to parse the given HTML String. html − HTML String. html − HTML String. link − Element object represent the html node element representing anchor tag. link − Element object represent the html node element representing anchor tag. link.attr() − attr(attribute,value) method set the element attribute the corresponding value. link.attr() − attr(attribute,value) method set the element attribute the corresponding value. link.addClass() − addClass(class) method add the class under class attribute. link.addClass() − addClass(class) method add the class under class attribute. link.removeClass() − removeClass(class) method remove the class under class attribute. link.removeClass() − removeClass(class) method remove the class under class attribute. Element object represent a dom elment and provides various method to get the attribute of a dom element. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<p>Sample Content</p>" + "<div id='sampleDiv'><a id='googleA' href='www.google.com'>Google</a></div>" + "<div class='comments'><a href='www.sample1.com'>Sample1</a>" + "<a href='www.sample2.com'>Sample2</a>" + "<a href='www.sample3.com'>Sample3</a><div>" +"</div>" + "<div id='imageDiv' class='header'><img name='google' src='google.png' />" + "<img name='yahoo' src='yahoo.jpg' />" +"</div>" +"</body></html>"; Document document = Jsoup.parse(html); //Example: set attribute Element link = document.getElementById("googleA"); System.out.println("Outer HTML Before Modification :" + link.outerHtml()); link.attr("href","www.yahoo.com"); System.out.println("Outer HTML After Modification :" + link.outerHtml()); System.out.println("---"); //Example: add class Element div = document.getElementById("sampleDiv"); System.out.println("Outer HTML Before Modification :" + div.outerHtml()); link.addClass("header"); System.out.println("Outer HTML After Modification :" + div.outerHtml()); System.out.println("---"); //Example: remove class Element div1 = document.getElementById("imageDiv"); System.out.println("Outer HTML Before Modification :" + div1.outerHtml()); div1.removeClass("header"); System.out.println("Outer HTML After Modification :" + div1.outerHtml()); System.out.println("---"); //Example: bulk update Elements links = document.select("div.comments a"); System.out.println("Outer HTML Before Modification :" + links.outerHtml()); links.attr("rel", "nofollow"); System.out.println("Outer HTML Before Modification :" + links.outerHtml()); } } Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Outer HTML Before Modification :<a id="googleA" href="www.google.com">Google</a> Outer HTML After Modification :<a id="googleA" href="www.yahoo.com">Google</a> --- Outer HTML Before Modification :<div id="sampleDiv"> <a id="googleA" href="www.yahoo.com">Google</a> </div> Outer HTML After Modification :<div id="sampleDiv"> <a id="googleA" href="www.yahoo.com" class="header">Google</a> </div> --- Outer HTML Before Modification :<div id="imageDiv" class="header"> <img name="google" src="google.png"> <img name="yahoo" src="yahoo.jpg"> </div> Outer HTML After Modification :<div id="imageDiv" class=""> <img name="google" src="google.png"> <img name="yahoo" src="yahoo.jpg"> </div> --- Outer HTML Before Modification :<a href="www.sample1.com">Sample1</a> <a href="www.sample2.com">Sample2</a> <a href="www.sample3.com">Sample3</a> Outer HTML Before Modification :<a href="www.sample1.com" rel="nofollow">Sample1</a> <a href="www.sample2.com" rel="nofollow">Sample2</a> <a href="www.sample3.com" rel="nofollow">Sample3</a> Print Add Notes Bookmark this page
[ { "code": null, "e": 2207, "s": 2030, "text": "Following example will showcase use of method to set attributes of a dom element, bulk updates and add/remove class methods after parsing an HTML String into a Document object." }, { "code": null, "e": 2399, "s": 2207, "text": "Document document = Jsoup.parse(html);\nElement link = document.select(\"a\").first(); \nlink.attr(\"href\",\"www.yahoo.com\"); \nlink.addClass(\"header\"); \nlink.removeClass(\"header\"); \n" }, { "code": null, "e": 2405, "s": 2399, "text": "Where" }, { "code": null, "e": 2457, "s": 2405, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2509, "s": 2457, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2560, "s": 2509, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2611, "s": 2560, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2631, "s": 2611, "text": "html − HTML String." }, { "code": null, "e": 2651, "s": 2631, "text": "html − HTML String." }, { "code": null, "e": 2730, "s": 2651, "text": "link − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2809, "s": 2730, "text": "link − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2903, "s": 2809, "text": "link.attr() − attr(attribute,value) method set the element attribute the corresponding value." }, { "code": null, "e": 2997, "s": 2903, "text": "link.attr() − attr(attribute,value) method set the element attribute the corresponding value." }, { "code": null, "e": 3075, "s": 2997, "text": "link.addClass() − addClass(class) method add the class under class attribute." }, { "code": null, "e": 3153, "s": 3075, "text": "link.addClass() − addClass(class) method add the class under class attribute." }, { "code": null, "e": 3240, "s": 3153, "text": "link.removeClass() − removeClass(class) method remove the class under class attribute." }, { "code": null, "e": 3327, "s": 3240, "text": "link.removeClass() − removeClass(class) method remove the class under class attribute." }, { "code": null, "e": 3432, "s": 3327, "text": "Element object represent a dom elment and provides various method to get the attribute of a dom element." }, { "code": null, "e": 3517, "s": 3432, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 3534, "s": 3517, "text": "JsoupTester.java" }, { "code": null, "e": 5662, "s": 3534, "text": "import org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\nimport org.jsoup.select.Elements;\n\npublic class JsoupTester {\n public static void main(String[] args) {\n \n String html = \"<html><head><title>Sample Title</title></head>\"\n + \"<body>\"\n + \"<p>Sample Content</p>\"\n + \"<div id='sampleDiv'><a id='googleA' href='www.google.com'>Google</a></div>\"\n + \"<div class='comments'><a href='www.sample1.com'>Sample1</a>\"\n + \"<a href='www.sample2.com'>Sample2</a>\"\n + \"<a href='www.sample3.com'>Sample3</a><div>\"\n +\"</div>\"\n + \"<div id='imageDiv' class='header'><img name='google' src='google.png' />\"\n + \"<img name='yahoo' src='yahoo.jpg' />\"\n +\"</div>\"\n +\"</body></html>\";\n Document document = Jsoup.parse(html);\n\n //Example: set attribute\n Element link = document.getElementById(\"googleA\");\n System.out.println(\"Outer HTML Before Modification :\" + link.outerHtml());\n link.attr(\"href\",\"www.yahoo.com\"); \n System.out.println(\"Outer HTML After Modification :\" + link.outerHtml());\n System.out.println(\"---\");\n \n //Example: add class\n Element div = document.getElementById(\"sampleDiv\");\n System.out.println(\"Outer HTML Before Modification :\" + div.outerHtml());\n link.addClass(\"header\"); \n System.out.println(\"Outer HTML After Modification :\" + div.outerHtml());\n System.out.println(\"---\");\n \n //Example: remove class\n Element div1 = document.getElementById(\"imageDiv\");\n System.out.println(\"Outer HTML Before Modification :\" + div1.outerHtml());\n div1.removeClass(\"header\"); \n System.out.println(\"Outer HTML After Modification :\" + div1.outerHtml());\n System.out.println(\"---\");\n \n //Example: bulk update\n Elements links = document.select(\"div.comments a\");\n System.out.println(\"Outer HTML Before Modification :\" + links.outerHtml());\n links.attr(\"rel\", \"nofollow\");\n System.out.println(\"Outer HTML Before Modification :\" + links.outerHtml());\n }\n}" }, { "code": null, "e": 5713, "s": 5662, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 5746, "s": 5713, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 5789, "s": 5746, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 5816, "s": 5789, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 5832, "s": 5816, "text": "See the result." }, { "code": null, "e": 6863, "s": 5832, "text": "Outer HTML Before Modification :<a id=\"googleA\" href=\"www.google.com\">Google</a>\nOuter HTML After Modification :<a id=\"googleA\" href=\"www.yahoo.com\">Google</a>\n---\nOuter HTML Before Modification :<div id=\"sampleDiv\">\n <a id=\"googleA\" href=\"www.yahoo.com\">Google</a>\n</div>\nOuter HTML After Modification :<div id=\"sampleDiv\">\n <a id=\"googleA\" href=\"www.yahoo.com\" class=\"header\">Google</a>\n</div>\n---\nOuter HTML Before Modification :<div id=\"imageDiv\" class=\"header\">\n <img name=\"google\" src=\"google.png\">\n <img name=\"yahoo\" src=\"yahoo.jpg\">\n</div>\nOuter HTML After Modification :<div id=\"imageDiv\" class=\"\">\n <img name=\"google\" src=\"google.png\">\n <img name=\"yahoo\" src=\"yahoo.jpg\">\n</div>\n---\nOuter HTML Before Modification :<a href=\"www.sample1.com\">Sample1</a>\n<a href=\"www.sample2.com\">Sample2</a>\n<a href=\"www.sample3.com\">Sample3</a>\nOuter HTML Before Modification :<a href=\"www.sample1.com\" rel=\"nofollow\">Sample1</a>\n<a href=\"www.sample2.com\" rel=\"nofollow\">Sample2</a>\n<a href=\"www.sample3.com\" rel=\"nofollow\">Sample3</a>\n" }, { "code": null, "e": 6870, "s": 6863, "text": " Print" }, { "code": null, "e": 6881, "s": 6870, "text": " Add Notes" } ]
How to filter non-null value in Java?
Let’s say the following is our List with string elements: List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL"); Now, create a stream and filter elements that end with a specific letter: Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L")); Now, use Objects::nonnull for non-null values: List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList()); The following is an example to filter non-null value in Java: import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { List<String> leagues = Arrays.asList("BBL", "IPL", "MLB", "FPL","NBA", "NFL"); Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith("L")); List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList()); System.out.println("League names ending with L = "+list); } } League names ending with L = [BBL, IPL, FPL, NFL]
[ { "code": null, "e": 1120, "s": 1062, "text": "Let’s say the following is our List with string elements:" }, { "code": null, "e": 1199, "s": 1120, "text": "List<String> leagues = Arrays.asList(\"BBL\", \"IPL\", \"MLB\", \"FPL\",\"NBA\", \"NFL\");" }, { "code": null, "e": 1273, "s": 1199, "text": "Now, create a stream and filter elements that end with a specific letter:" }, { "code": null, "e": 1362, "s": 1273, "text": "Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith(\"L\"));" }, { "code": null, "e": 1409, "s": 1362, "text": "Now, use Objects::nonnull for non-null values:" }, { "code": null, "e": 1491, "s": 1409, "text": "List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());" }, { "code": null, "e": 1553, "s": 1491, "text": "The following is an example to filter non-null value in Java:" }, { "code": null, "e": 2098, "s": 1553, "text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\npublic class Demo {\n public static void main(String[] args) {\n List<String> leagues = Arrays.asList(\"BBL\", \"IPL\", \"MLB\", \"FPL\",\"NBA\", \"NFL\");\n Stream<String> stream = leagues.stream().filter(leagueName -> leagueName.endsWith(\"L\"));\n List<String> list = stream.filter(Objects::nonNull).collect(Collectors.toList());\n System.out.println(\"League names ending with L = \"+list);\n }\n}" }, { "code": null, "e": 2148, "s": 2098, "text": "League names ending with L = [BBL, IPL, FPL, NFL]" } ]
Python - Uppercase Selective Substrings in String - GeeksforGeeks
30 Aug, 2020 Given a String, perform uppercase of particular Substrings from List. Input : test_str = ‘geeksforgeeks is best for cs’, sub_list = [“best”, “geeksforgeeks”]Output : GEEKSFORGEEKS is BEST for csExplanation : geeksforgeeks and best uppercased. Input : test_str = ‘geeksforgeeks is best for best’, sub_list = [“best”, “geeksforgeeks”]Output : GEEKSFORGEEKS is BEST for BESTExplanation : geeksforgeeks and best both occurrences uppercased. Method #1 : Using split() + join() + loop In this, we repeatedly split the string by substring and then perform join operation after joining the String with uppercased version of Substring. This is success only in cases of 1 occurrence of substring in String. Python3 # Python3 code to demonstrate working of # Uppercase Selective Substrings in String# Using split() + join() + loop # initializing stringstest_str = 'geeksforgeeks is best for cs' # printing original stringprint("The original string is : " + str(test_str)) # initializing substringssub_list = ["best", "cs", "geeksforgeeks"] for sub in sub_list: # splitting string temp = test_str.split(sub, -1) # joining after uppercase test_str = sub.upper().join(temp) # printing result print("The String after uppercasing : " + str(test_str)) The original string is : geeksforgeeks is best for cs The String after uppercasing : GEEKSFORGEEKS is BEST for CS Method #2 : Using re.sub() + upper() This uses regex to solve this problem. In this, we use appropriate regex, and perform uppercase of found Strings. Python3 # Python3 code to demonstrate working of # Uppercase Selective Substrings in String# Using re.sub() + upper()import re # initializing stringstest_str = 'geeksforgeeks is best for cs' # printing original stringprint("The original string is : " + str(test_str)) # initializing substringssub_list = ["best", "cs", "geeksforgeeks"] # constructing regexreg = '|'.join(sub_list)res = re.sub(reg, lambda ele: ele.group(0).upper(), test_str) # printing result print("The String after uppercasing : " + str(res)) The original string is : geeksforgeeks is best for cs The String after uppercasing : GEEKSFORGEEKS is BEST for CS Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Split string into list of characters
[ { "code": null, "e": 25449, "s": 25421, "text": "\n30 Aug, 2020" }, { "code": null, "e": 25519, "s": 25449, "text": "Given a String, perform uppercase of particular Substrings from List." }, { "code": null, "e": 25692, "s": 25519, "text": "Input : test_str = ‘geeksforgeeks is best for cs’, sub_list = [“best”, “geeksforgeeks”]Output : GEEKSFORGEEKS is BEST for csExplanation : geeksforgeeks and best uppercased." }, { "code": null, "e": 25886, "s": 25692, "text": "Input : test_str = ‘geeksforgeeks is best for best’, sub_list = [“best”, “geeksforgeeks”]Output : GEEKSFORGEEKS is BEST for BESTExplanation : geeksforgeeks and best both occurrences uppercased." }, { "code": null, "e": 25928, "s": 25886, "text": "Method #1 : Using split() + join() + loop" }, { "code": null, "e": 26146, "s": 25928, "text": "In this, we repeatedly split the string by substring and then perform join operation after joining the String with uppercased version of Substring. This is success only in cases of 1 occurrence of substring in String." }, { "code": null, "e": 26154, "s": 26146, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Uppercase Selective Substrings in String# Using split() + join() + loop # initializing stringstest_str = 'geeksforgeeks is best for cs' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing substringssub_list = [\"best\", \"cs\", \"geeksforgeeks\"] for sub in sub_list: # splitting string temp = test_str.split(sub, -1) # joining after uppercase test_str = sub.upper().join(temp) # printing result print(\"The String after uppercasing : \" + str(test_str)) ", "e": 26718, "s": 26154, "text": null }, { "code": null, "e": 26833, "s": 26718, "text": "The original string is : geeksforgeeks is best for cs\nThe String after uppercasing : GEEKSFORGEEKS is BEST for CS\n" }, { "code": null, "e": 26870, "s": 26833, "text": "Method #2 : Using re.sub() + upper()" }, { "code": null, "e": 26984, "s": 26870, "text": "This uses regex to solve this problem. In this, we use appropriate regex, and perform uppercase of found Strings." }, { "code": null, "e": 26992, "s": 26984, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Uppercase Selective Substrings in String# Using re.sub() + upper()import re # initializing stringstest_str = 'geeksforgeeks is best for cs' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing substringssub_list = [\"best\", \"cs\", \"geeksforgeeks\"] # constructing regexreg = '|'.join(sub_list)res = re.sub(reg, lambda ele: ele.group(0).upper(), test_str) # printing result print(\"The String after uppercasing : \" + str(res)) ", "e": 27502, "s": 26992, "text": null }, { "code": null, "e": 27617, "s": 27502, "text": "The original string is : geeksforgeeks is best for cs\nThe String after uppercasing : GEEKSFORGEEKS is BEST for CS\n" }, { "code": null, "e": 27640, "s": 27617, "text": "Python string-programs" }, { "code": null, "e": 27647, "s": 27640, "text": "Python" }, { "code": null, "e": 27663, "s": 27647, "text": "Python Programs" }, { "code": null, "e": 27761, "s": 27663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27779, "s": 27761, "text": "Python Dictionary" }, { "code": null, "e": 27814, "s": 27779, "text": "Read a file line by line in Python" }, { "code": null, "e": 27846, "s": 27814, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27868, "s": 27846, "text": "Enumerate() in Python" }, { "code": null, "e": 27910, "s": 27868, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27953, "s": 27910, "text": "Python program to convert a list to string" }, { "code": null, "e": 27975, "s": 27953, "text": "Defaultdict in Python" }, { "code": null, "e": 28014, "s": 27975, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28052, "s": 28014, "text": "Python | Convert a list to dictionary" } ]
Top 25 Interview Questions - GeeksforGeeks
07 Oct, 2021 Here is the collection of TOP 25 frequently asked questions based on experience (mine and friends) of interviews in multiple companies. 1) Lowest common Ancestor (https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/) 2) A unsorted array of integers is given; you need to find the max product formed by multiplying three numbers. (You cannot sort the array, watch out when there are negative numbers) (Maximum product of a triplet) 3) Left View of a tree (https://www.geeksforgeeks.org/print-left-view-binary-tree/) 4) Reversing of Arrays (https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array/) 5) Cache Line, Cache internal concept, RR scheduling 6) Print the middle of a given linked list (https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/) 7) Pair wise swap of elements in linked list (https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list/) 8) HashMap internals (http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html) 9) Double checking Singleton (http://javarevisited.blogspot.in/2014/05/double-checked-locking-on-singleton-in-java.html) 10) Factory Pattern (http://javarevisited.blogspot.in/2011/12/factory-design-pattern-java-example.html) 11) Print a given matrix in spiral form (https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/) 12) DFS on Graph and its representation (https://www.geeksforgeeks.org/graph-and-its-representations/, http://ideone.com/TA4ldc) 13) Object-Oriented concept, Polymorphism, Method overloading, method overriding, Difference between abstraction and encapsulation, Aggregation and Composition (oops interview questions) 14) Print nth last node in the linked list 15) Delete a given node in Linked List under given constraints (https://www.geeksforgeeks.org/delete-a-given-node-in-linked-list-under-given-constraints/) 16) Implement Stack using Queues(https://www.geeksforgeeks.org/implement-stack-using-queue/) 17) Find if two rectangles overlap (https://www.geeksforgeeks.org/find-two-rectangles-overlap/) 18) Multithreading concepts 19) Given an array of integers, update the index with the multiplication of previous and next integers. e.g. Input: 2 , 3, 4, 5, 6 Output: 2*3, 2*4, 3*5, 4*6, 5*6 20) Difference of creating threads in Java using Thread and Runnable 21) How hashset is implemented in Java internally. 22) DeadLock example code (Producer & Consumer Code) 23) Find the number which is not repeated in Array of integers, others are present for two times. (Non-Repeating Element) e.g. Input : 23, 34,56,21,21,56,78,23, 34 Output: 23 Hint: USE XOR 24) Serialization and related concepts. 25) Comparators in TreeSet Thanks to geeksforgeeks team for providing a nice platform. You guys are the best. This article is contributed by Rishi Verma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. acoder84 alishanlenovo placement preparation Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) fgets() and gets() in C language Association Rule Recursive Functions Activation Functions Java Math min() method with Examples Software Engineering | Prototyping Model Characteristics of Internet of Things OOPs | Object Oriented Design
[ { "code": null, "e": 26317, "s": 26289, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26454, "s": 26317, "text": "Here is the collection of TOP 25 frequently asked questions based on experience (mine and friends) of interviews in multiple companies. " }, { "code": null, "e": 26555, "s": 26454, "text": "1) Lowest common Ancestor (https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/) " }, { "code": null, "e": 26771, "s": 26555, "text": "2) A unsorted array of integers is given; you need to find the max product formed by multiplying three numbers. (You cannot sort the array, watch out when there are negative numbers) (Maximum product of a triplet) " }, { "code": null, "e": 26856, "s": 26771, "text": "3) Left View of a tree (https://www.geeksforgeeks.org/print-left-view-binary-tree/) " }, { "code": null, "e": 26949, "s": 26856, "text": "4) Reversing of Arrays (https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array/) " }, { "code": null, "e": 27003, "s": 26949, "text": "5) Cache Line, Cache internal concept, RR scheduling " }, { "code": null, "e": 27138, "s": 27003, "text": "6) Print the middle of a given linked list (https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/) " }, { "code": null, "e": 27263, "s": 27138, "text": "7) Pair wise swap of elements in linked list (https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list/) " }, { "code": null, "e": 27359, "s": 27263, "text": "8) HashMap internals (http://javarevisited.blogspot.in/2011/02/how-hashmap-works-in-java.html) " }, { "code": null, "e": 27481, "s": 27359, "text": "9) Double checking Singleton (http://javarevisited.blogspot.in/2014/05/double-checked-locking-on-singleton-in-java.html) " }, { "code": null, "e": 27586, "s": 27481, "text": "10) Factory Pattern (http://javarevisited.blogspot.in/2011/12/factory-design-pattern-java-example.html) " }, { "code": null, "e": 27696, "s": 27586, "text": "11) Print a given matrix in spiral form (https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/) " }, { "code": null, "e": 27826, "s": 27696, "text": "12) DFS on Graph and its representation (https://www.geeksforgeeks.org/graph-and-its-representations/, http://ideone.com/TA4ldc) " }, { "code": null, "e": 28014, "s": 27826, "text": "13) Object-Oriented concept, Polymorphism, Method overloading, method overriding, Difference between abstraction and encapsulation, Aggregation and Composition (oops interview questions)" }, { "code": null, "e": 28058, "s": 28014, "text": "14) Print nth last node in the linked list " }, { "code": null, "e": 28214, "s": 28058, "text": "15) Delete a given node in Linked List under given constraints (https://www.geeksforgeeks.org/delete-a-given-node-in-linked-list-under-given-constraints/) " }, { "code": null, "e": 28308, "s": 28214, "text": "16) Implement Stack using Queues(https://www.geeksforgeeks.org/implement-stack-using-queue/) " }, { "code": null, "e": 28405, "s": 28308, "text": "17) Find if two rectangles overlap (https://www.geeksforgeeks.org/find-two-rectangles-overlap/) " }, { "code": null, "e": 28434, "s": 28405, "text": "18) Multithreading concepts " }, { "code": null, "e": 28539, "s": 28434, "text": "19) Given an array of integers, update the index with the multiplication of previous and next integers. " }, { "code": null, "e": 28609, "s": 28539, "text": " e.g. Input: 2 , 3, 4, 5, 6\n Output: 2*3, 2*4, 3*5, 4*6, 5*6" }, { "code": null, "e": 28679, "s": 28609, "text": "20) Difference of creating threads in Java using Thread and Runnable " }, { "code": null, "e": 28731, "s": 28679, "text": "21) How hashset is implemented in Java internally. " }, { "code": null, "e": 28785, "s": 28731, "text": "22) DeadLock example code (Producer & Consumer Code) " }, { "code": null, "e": 28908, "s": 28785, "text": "23) Find the number which is not repeated in Array of integers, others are present for two times. (Non-Repeating Element)" }, { "code": null, "e": 28993, "s": 28908, "text": "e.g. Input : 23, 34,56,21,21,56,78,23, 34 \n Output: 23\n Hint: USE XOR" }, { "code": null, "e": 29034, "s": 28993, "text": "24) Serialization and related concepts. " }, { "code": null, "e": 29062, "s": 29034, "text": "25) Comparators in TreeSet " }, { "code": null, "e": 29146, "s": 29062, "text": "Thanks to geeksforgeeks team for providing a nice platform. You guys are the best. " }, { "code": null, "e": 29316, "s": 29146, "text": "This article is contributed by Rishi Verma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29325, "s": 29316, "text": "acoder84" }, { "code": null, "e": 29339, "s": 29325, "text": "alishanlenovo" }, { "code": null, "e": 29361, "s": 29339, "text": "placement preparation" }, { "code": null, "e": 29366, "s": 29361, "text": "Misc" }, { "code": null, "e": 29371, "s": 29366, "text": "Misc" }, { "code": null, "e": 29376, "s": 29371, "text": "Misc" }, { "code": null, "e": 29474, "s": 29376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29508, "s": 29474, "text": "How to write Regular Expressions?" }, { "code": null, "e": 29589, "s": 29508, "text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)" }, { "code": null, "e": 29622, "s": 29589, "text": "fgets() and gets() in C language" }, { "code": null, "e": 29639, "s": 29622, "text": "Association Rule" }, { "code": null, "e": 29659, "s": 29639, "text": "Recursive Functions" }, { "code": null, "e": 29680, "s": 29659, "text": "Activation Functions" }, { "code": null, "e": 29717, "s": 29680, "text": "Java Math min() method with Examples" }, { "code": null, "e": 29758, "s": 29717, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 29796, "s": 29758, "text": "Characteristics of Internet of Things" } ]
MATLAB | Complement colors in a Grayscale Image - GeeksforGeeks
22 Oct, 2018 In MATLAB, a Grayscale image is a 2-D Image array ( M*N ) of color pixel. When we complement colors in a Grayscale image, Each color pixel in grayscale image is replaced with their complementary color pixel. Dark areas become lighter and light areas become darker in the grayscale image as result of complement. Complementing colors of a Grayscale Image Using MATLAB Library Function : % read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg'); % complement colors of a Grayscale image % using imcomplement() functioncomp=imcomplement(img); % Display Complemented grayscale Image imshow(comp); Complementing colors of a Grayscale Image without Using MATLAB Library Function : Grayscale Images have their pixel value in the range 0 to 255. we can complement a grayscale image by subtracting each pixel value from maximum possible pixel value a Grayscale image pixel can have (i.e 255 ), and the difference is used as the pixel value in the complemented Grayscale image. It means if an image pixel have value 100 then, in complemented Grayscale image same pixel will have value ( 255 – 100 ) = 155.And if Grayscale image pixel have value 0 then, in complemented grayscale image same pixel will have value ( 255 – 0 ) = 255.Similarly, if Grayscale image pixel have value 255 then, in complemented grayscale image same pixel will have value ( 255 – 255 ) = 0. Below is the Implementation of above idea: % This function will take a Grayscale image as input% and will complement the colors in it. function [complement] = complementGray(img) % Determine the number of rows and columns % in the Grayscale image array [x, y]=size(img); % create a array of same number rows and % columns as original Grayscale image array complement=zeros(x, y); % loop to subtract 255 to each pixel. for i=1:x for j=1:y complement(i, j) = 255-img(i, j); end endend % Driver Code % read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg'); % call complementGray() function to% complement colors in the Grayscale Imagecomp=complementGray(img); % Display complemented Grayscale imageimshow(comp); Alternatively – Instead of using two loops to subtract 255 to each pixel of grayscale image. We can directly write it as comp = 255-image. Above code will subtract each value of image array from 255. Below code will also complement a Grayscale Image: % read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg'); % complement each pixel by subtracting it from 255.comp=255-img; % Display Complemented Grayscale Image imshow(comp); Input: Output: Image-Processing MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example System Design Tutorial Python | Decision tree implementation Copying Files to and from Docker Containers ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction
[ { "code": null, "e": 25895, "s": 25867, "text": "\n22 Oct, 2018" }, { "code": null, "e": 26103, "s": 25895, "text": "In MATLAB, a Grayscale image is a 2-D Image array ( M*N ) of color pixel. When we complement colors in a Grayscale image, Each color pixel in grayscale image is replaced with their complementary color pixel." }, { "code": null, "e": 26207, "s": 26103, "text": "Dark areas become lighter and light areas become darker in the grayscale image as result of complement." }, { "code": null, "e": 26281, "s": 26207, "text": "Complementing colors of a Grayscale Image Using MATLAB Library Function :" }, { "code": "% read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg'); % complement colors of a Grayscale image % using imcomplement() functioncomp=imcomplement(img); % Display Complemented grayscale Image imshow(comp);", "e": 26503, "s": 26281, "text": null }, { "code": null, "e": 26587, "s": 26505, "text": "Complementing colors of a Grayscale Image without Using MATLAB Library Function :" }, { "code": null, "e": 26880, "s": 26587, "text": "Grayscale Images have their pixel value in the range 0 to 255. we can complement a grayscale image by subtracting each pixel value from maximum possible pixel value a Grayscale image pixel can have (i.e 255 ), and the difference is used as the pixel value in the complemented Grayscale image." }, { "code": null, "e": 27267, "s": 26880, "text": "It means if an image pixel have value 100 then, in complemented Grayscale image same pixel will have value ( 255 – 100 ) = 155.And if Grayscale image pixel have value 0 then, in complemented grayscale image same pixel will have value ( 255 – 0 ) = 255.Similarly, if Grayscale image pixel have value 255 then, in complemented grayscale image same pixel will have value ( 255 – 255 ) = 0." }, { "code": null, "e": 27310, "s": 27267, "text": "Below is the Implementation of above idea:" }, { "code": "% This function will take a Grayscale image as input% and will complement the colors in it. function [complement] = complementGray(img) % Determine the number of rows and columns % in the Grayscale image array [x, y]=size(img); % create a array of same number rows and % columns as original Grayscale image array complement=zeros(x, y); % loop to subtract 255 to each pixel. for i=1:x for j=1:y complement(i, j) = 255-img(i, j); end endend % Driver Code % read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg'); % call complementGray() function to% complement colors in the Grayscale Imagecomp=complementGray(img); % Display complemented Grayscale imageimshow(comp);", "e": 28069, "s": 27310, "text": null }, { "code": null, "e": 28087, "s": 28071, "text": "Alternatively –" }, { "code": null, "e": 28271, "s": 28087, "text": "Instead of using two loops to subtract 255 to each pixel of grayscale image. We can directly write it as comp = 255-image. Above code will subtract each value of image array from 255." }, { "code": null, "e": 28322, "s": 28271, "text": "Below code will also complement a Grayscale Image:" }, { "code": "% read a Grayscale Image in MATLAB Environmentimg=imread('apple.jpg'); % complement each pixel by subtracting it from 255.comp=255-img; % Display Complemented Grayscale Image imshow(comp);", "e": 28513, "s": 28322, "text": null }, { "code": null, "e": 28520, "s": 28513, "text": "Input:" }, { "code": null, "e": 28528, "s": 28520, "text": "Output:" }, { "code": null, "e": 28545, "s": 28528, "text": "Image-Processing" }, { "code": null, "e": 28552, "s": 28545, "text": "MATLAB" }, { "code": null, "e": 28578, "s": 28552, "text": "Advanced Computer Subject" }, { "code": null, "e": 28676, "s": 28578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28699, "s": 28676, "text": "ML | Linear Regression" }, { "code": null, "e": 28722, "s": 28699, "text": "Reinforcement learning" }, { "code": null, "e": 28736, "s": 28722, "text": "Decision Tree" }, { "code": null, "e": 28776, "s": 28736, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 28799, "s": 28776, "text": "System Design Tutorial" }, { "code": null, "e": 28837, "s": 28799, "text": "Python | Decision tree implementation" }, { "code": null, "e": 28881, "s": 28837, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 28915, "s": 28881, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28946, "s": 28915, "text": "Clustering in Machine Learning" } ]
p5.js Geometry() Method - GeeksforGeeks
21 May, 2021 p5.Geometry() method is used to represent 3d objects. It is returned by the loadModel() function and also used internally by the 3d primitive drawing functions. This function requires p5.dom library. So add the following line in the head section of the index.html file. Javascript <script language="javascript" type="text/javascript" src="path/to/p5.dom.js"></script> Syntax: new p5.Geometry([detailX], [detailY], [callback]) Parameters: detailX and detailY takes the number of vertices on a horizontal surface, callback takes a function to call upon object instantiation. Available methods in p5.Geometry Class: Sr.no. Methods Description 1. computeFaces() It used to compute the faces for geometry objects based on the vertices. 2. computeNormals() It used to compute the smooth normals per vertex as an average of each face. 3. averageNormals() It is used in curved surfaces to compute the average vertex normals. 4. averagePoleNormals() It is used in spherical primitives to compute the average pole normals. 5. normalize() It will modify all vertices to be centered within the range -100 to 100. Example: Javascript function setup() { // Create Canvas of given size var cvs = createCanvas(400, 300);} function draw() { // Set the background color background('pink'); // Creating rectangle at center of canvas rectMode(CENTER); // Initializing a rect geometry geo = new p5.Geometry( rect(200,150,190,120) ); // Adding text to the geometry figure text('GeeksforGeeks', 160, 150);} In new p5.Geometry( rect(200,150,190,120)), 200 is used to specify the x-axis, 150 for the y-axis and 190 is the width of the rectangle and, 120 is the height of the rectangle. Similarly, in text, 160 is the x-axis position and 150 is the y-axis position with respect to the canvas screen. Output: Reference : https://p5js.org/reference/#/p5.Geometry JavaScript-p5.js Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26627, "s": 26599, "text": "\n21 May, 2021" }, { "code": null, "e": 26789, "s": 26627, "text": "p5.Geometry() method is used to represent 3d objects. It is returned by the loadModel() function and also used internally by the 3d primitive drawing functions. " }, { "code": null, "e": 26898, "s": 26789, "text": "This function requires p5.dom library. So add the following line in the head section of the index.html file." }, { "code": null, "e": 26909, "s": 26898, "text": "Javascript" }, { "code": "<script language=\"javascript\" type=\"text/javascript\" src=\"path/to/p5.dom.js\"></script>", "e": 27000, "s": 26909, "text": null }, { "code": null, "e": 27008, "s": 27000, "text": "Syntax:" }, { "code": null, "e": 27058, "s": 27008, "text": "new p5.Geometry([detailX], [detailY], [callback])" }, { "code": null, "e": 27206, "s": 27058, "text": "Parameters: detailX and detailY takes the number of vertices on a horizontal surface, callback takes a function to call upon object instantiation. " }, { "code": null, "e": 27248, "s": 27208, "text": "Available methods in p5.Geometry Class:" }, { "code": null, "e": 27255, "s": 27248, "text": "Sr.no." }, { "code": null, "e": 27263, "s": 27255, "text": "Methods" }, { "code": null, "e": 27275, "s": 27263, "text": "Description" }, { "code": null, "e": 27278, "s": 27275, "text": "1." }, { "code": null, "e": 27293, "s": 27278, "text": "computeFaces()" }, { "code": null, "e": 27366, "s": 27293, "text": "It used to compute the faces for geometry objects based on the vertices." }, { "code": null, "e": 27369, "s": 27366, "text": "2." }, { "code": null, "e": 27386, "s": 27369, "text": "computeNormals()" }, { "code": null, "e": 27463, "s": 27386, "text": "It used to compute the smooth normals per vertex as an average of each face." }, { "code": null, "e": 27466, "s": 27463, "text": "3." }, { "code": null, "e": 27483, "s": 27466, "text": "averageNormals()" }, { "code": null, "e": 27552, "s": 27483, "text": "It is used in curved surfaces to compute the average vertex normals." }, { "code": null, "e": 27555, "s": 27552, "text": "4." }, { "code": null, "e": 27576, "s": 27555, "text": "averagePoleNormals()" }, { "code": null, "e": 27648, "s": 27576, "text": "It is used in spherical primitives to compute the average pole normals." }, { "code": null, "e": 27651, "s": 27648, "text": "5." }, { "code": null, "e": 27663, "s": 27651, "text": "normalize()" }, { "code": null, "e": 27736, "s": 27663, "text": "It will modify all vertices to be centered within the range -100 to 100." }, { "code": null, "e": 27745, "s": 27736, "text": "Example:" }, { "code": null, "e": 27756, "s": 27745, "text": "Javascript" }, { "code": "function setup() { // Create Canvas of given size var cvs = createCanvas(400, 300);} function draw() { // Set the background color background('pink'); // Creating rectangle at center of canvas rectMode(CENTER); // Initializing a rect geometry geo = new p5.Geometry( rect(200,150,190,120) ); // Adding text to the geometry figure text('GeeksforGeeks', 160, 150);}", "e": 28165, "s": 27756, "text": null }, { "code": null, "e": 28342, "s": 28165, "text": "In new p5.Geometry( rect(200,150,190,120)), 200 is used to specify the x-axis, 150 for the y-axis and 190 is the width of the rectangle and, 120 is the height of the rectangle." }, { "code": null, "e": 28455, "s": 28342, "text": "Similarly, in text, 160 is the x-axis position and 150 is the y-axis position with respect to the canvas screen." }, { "code": null, "e": 28463, "s": 28455, "text": "Output:" }, { "code": null, "e": 28516, "s": 28463, "text": "Reference : https://p5js.org/reference/#/p5.Geometry" }, { "code": null, "e": 28533, "s": 28516, "text": "JavaScript-p5.js" }, { "code": null, "e": 28540, "s": 28533, "text": "Picked" }, { "code": null, "e": 28551, "s": 28540, "text": "JavaScript" }, { "code": null, "e": 28568, "s": 28551, "text": "Web Technologies" }, { "code": null, "e": 28666, "s": 28568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28706, "s": 28666, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28767, "s": 28706, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28808, "s": 28767, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28830, "s": 28808, "text": "JavaScript | Promises" }, { "code": null, "e": 28884, "s": 28830, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28924, "s": 28884, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28957, "s": 28924, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29000, "s": 28957, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29050, "s": 29000, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Role of KL-divergence in Variational Autoencoders - GeeksforGeeks
27 Jan, 2022 Variational autoencoder was proposed in 2013 by Knigma and Welling at Google and Qualcomm. A variational autoencoder (VAE) provides a probabilistic manner for describing an observation in latent space. Thus, rather than building an encoder that outputs a single value to describe each latent state attribute, we’ll formulate our encoder to describe a probability distribution for each latent attribute. Autoencoders basically contains two parts: The first one is an encoder which is similar to the convolution neural network except for the last layer. The aim of the encoder is to learn efficient data encoding from the dataset and pass it into a bottleneck architecture. The other part of the autoencoder is a decoder that uses latent space in the bottleneck layer to regenerate the images similar to the dataset. These results backpropagate from the neural network in the form of the loss function. Variational autoencoder is different from autoencoder in a way such that it provides a statistical manner for describing the samples of the dataset in latent space. Therefore, in the variational autoencoder, the encoder outputs a probability distribution in the bottleneck layer instead of a single output value. The Variational Autoencoder latent space is continuous. It provides random sampling and interpolation. Instead of outputting a vector of size n, the encoder outputs two vectors: Vector ???? of means (vector size n) Vector ???? of standard deviations (vector size n) Output is an approximate posterior distribution q(z|x). Sample from this distribution to get z. let’s look at more details into Sampling: Let’s take some values of mean and standard deviation, The intermediate distribution that is generated from that: Now, let’s generate the sampled vector from this: While the mean and standard deviation are the same for one input the result may be different due to sampling. Eventually, our goal is to make the encoder learn to generate differently???? For different classes, clustering them and generating encoding such they don’t vary much. To this we use KL-divergence. KL divergence stands for Kullback Leibler Divergence, it is a measure of divergence between two distributions. Our goal is to Minimize KL divergence and optimize ???? and ???? of one distribution to resemble the required distribution.Of For multiple distribution the KL-divergence can be calculated as the following formula: where X_j \sim N(\mu_j, \sigma_j^{2}) is the standard normal distribution. Suppose we have a distribution z and we want to generate the observation x from it. In other words, we want to calculate We can do it by following way: But, the calculation of p(x) can be quite difficult This usually makes it an intractable distribution. Hence, we need to approximate p(z|x) to q(z|x) to make it a tractable distribution. To better approximate p(z|x) to q(z|x), we will minimize the KL-divergence loss which calculates how similar two distributions are: By simplifying, the above minimization problem is equivalent to the following maximization problem : The first term represents the reconstruction likelihood and the other term ensures that our learned distribution q is similar to the true prior distribution p. Thus our total loss consists of two terms, one is reconstruction error and the other is KL-divergence loss: In this implementation, we will be using the MNIST dataset, this dataset is already available in keras.datasets API, so we don’t need to add or upload manually. First, we need to import the necessary packages to our python environment. we will be using Keras package with TensorFlow as a backend. python3 # codeimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import Input, Modelfrom tensorflow.keras.layers import Layer, Conv2D, Flatten, Dense, Reshape, Conv2DTransposeimport matplotlib.pyplot as plt For variational autoencoders, we need to define the architecture of two parts encoder and decoder but first, we will define the bottleneck layer of architecture, the sampling layer. python3 # this sampling layer is the bottleneck layer of variational autoencoder,# it uses the output from two dense layers z_mean and z_log_var as input,# convert them into normal distribution and pass them to the decoder layerclass Sampling(Layer): def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape =(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon Now, we define the architecture of the encoder part of our autoencoder, this part takes images as input and encodes their representation in the Sampling layer. python3 # Define Encoder Modellatent_dim = 2 encoder_inputs = Input(shape =(28, 28, 1))x = Conv2D(32, 3, activation ="relu", strides = 2, padding ="same")(encoder_inputs)x = Conv2D(64, 3, activation ="relu", strides = 2, padding ="same")(x)x = Flatten()(x)x = Dense(16, activation ="relu")(x)z_mean = Dense(latent_dim, name ="z_mean")(x)z_log_var = Dense(latent_dim, name ="z_log_var")(x)z = Sampling()([z_mean, z_log_var])encoder = Model(encoder_inputs, [z_mean, z_log_var, z], name ="encoder")encoder.summary() Model: "encoder" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_3 (InputLayer) [(None, 28, 28, 1)] 0 __________________________________________________________________________________________________ conv2d_2 (Conv2D) (None, 14, 14, 32) 320 input_3[0][0] __________________________________________________________________________________________________ conv2d_3 (Conv2D) (None, 7, 7, 64) 18496 conv2d_2[0][0] __________________________________________________________________________________________________ flatten_1 (Flatten) (None, 3136) 0 conv2d_3[0][0] __________________________________________________________________________________________________ dense_2 (Dense) (None, 16) 50192 flatten_1[0][0] __________________________________________________________________________________________________ z_mean (Dense) (None, 2) 34 dense_2[0][0] __________________________________________________________________________________________________ z_log_var (Dense) (None, 2) 34 dense_2[0][0] __________________________________________________________________________________________________ sampling_1 (Sampling) (None, 2) 0 z_mean[0][0] z_log_var[0][0] ================================================================================================== Total params: 69, 076 Trainable params: 69, 076 Non-trainable params: 0 __________________________________________________________________________________________________ Now, we define the architecture of decoder part of our autoencoder, this part takes the output of the sampling layer as input and output an image of size (28, 28, 1) . python3 # Define Decoder Architecturelatent_inputs = keras.Input(shape =(latent_dim, ))x = Dense(7 * 7 * 64, activation ="relu")(latent_inputs)x = Reshape((7, 7, 64))(x)x = Conv2DTranspose(64, 3, activation ="relu", strides = 2, padding ="same")(x)x = Conv2DTranspose(32, 3, activation ="relu", strides = 2, padding ="same")(x)decoder_outputs = Conv2DTranspose(1, 3, activation ="sigmoid", padding ="same")(x)decoder = Model(latent_inputs, decoder_outputs, name ="decoder")decoder.summary() Model: "decoder" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_4 (InputLayer) [(None, 2)] 0 _________________________________________________________________ dense_3 (Dense) (None, 3136) 9408 _________________________________________________________________ reshape_1 (Reshape) (None, 7, 7, 64) 0 _________________________________________________________________ conv2d_transpose_3 (Conv2DTr (None, 14, 14, 64) 36928 _________________________________________________________________ conv2d_transpose_4 (Conv2DTr (None, 28, 28, 32) 18464 _________________________________________________________________ conv2d_transpose_5 (Conv2DTr (None, 28, 28, 1) 289 ================================================================= Total params: 65, 089 Trainable params: 65, 089 Non-trainable params: 0 _________________________________________________________________ In this step, we combine the model and define the training procedure with loss functions. python3 # this class takes encoder and decoder models and# define the complete variational autoencoder architectureclass VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder def train_step(self, data): if isinstance(data, tuple): data = data[0] with tf.GradientTape() as tape: z_mean, z_log_var, z = encoder(data) reconstruction = decoder(z) reconstruction_loss = tf.reduce_mean( keras.losses.binary_crossentropy(data, reconstruction) ) reconstruction_loss *= 28 * 28 kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var) kl_loss = tf.reduce_mean(kl_loss) kl_loss *= -0.5 # beta =10 total_loss = reconstruction_loss + 10 * kl_loss grads = tape.gradient(total_loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) return { "loss": total_loss, "reconstruction_loss": reconstruction_loss, "kl_loss": kl_loss, } Now it’s the right time to train our variational autoencoder model, we will train it for 100 epochs. But first we need to import the MNIST dataset. python3 # load fashion mnist dataset from keras.dataset API(x_train, _), (x_test, _) = keras.datasets.fashion_mnist.load_data()fmnist_images = np.concatenate([x_train, x_test], axis = 0)# expand dimension to add a color map dimensionfmnist_images = np.expand_dims(fmnist_images, -1).astype("float32") / 255 # compile and train the modelvae = VAE(encoder, decoder)vae.compile(optimizer ='rmsprop')vae.fit(fmnist_images, epochs = 100, batch_size = 128) In this step, we display training results, we will be displaying these results according to their values in latent space vectors. python3 def plot_latent(encoder, decoder): # display a n * n 2D manifold of images n = 10 img_dim = 28 scale = 2.0 figsize = 15 figure = np.zeros((img_dim * n, img_dim * n)) # linearly spaced coordinates corresponding to the 2D plot # of images classes in the latent space grid_x = np.linspace(-scale, scale, n) grid_y = np.linspace(-scale, scale, n)[::-1] for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): z_sample = np.array([[xi, yi]]) x_decoded = decoder.predict(z_sample) images = x_decoded[0].reshape(img_dim, img_dim) figure[ i * img_dim : (i + 1) * img_dim, j * img_dim : (j + 1) * img_dim, ] = images plt.figure(figsize =(figsize, figsize)) start_range = img_dim // 2 end_range = n * img_dim + start_range + 1 pixel_range = np.arange(start_range, end_range, img_dim) sample_range_x = np.round(grid_x, 1) sample_range_y = np.round(grid_y, 1) plt.xticks(pixel_range, sample_range_x) plt.yticks(pixel_range, sample_range_y) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.imshow(figure, cmap ="Greys_r") plt.show() plot_latent(encoder, decoder) Output from Encoder To get a more clear view of our representational latent vectors values, we will be plotting the scatter plot of training data on the basis of their values of corresponding latent dimensions generated from the encoder python3 def plot_label_clusters(encoder, decoder, data, test_lab): z_mean, _, _ = encoder.predict(data) plt.figure(figsize =(12, 10)) sc = plt.scatter(z_mean[:, 0], z_mean[:, 1], c = test_lab) cbar = plt.colorbar(sc, ticks = range(10)) cbar.ax.set_yticklabels([i for i in range(10)]) plt.xlabel("z[0]") plt.ylabel("z[1]") plt.show() (x_train, y_train), _ = keras.datasets.mnist.load_data()x_train = np.expand_dims(x_train, -1).astype("float32") / 255plot_label_clusters(encoder, decoder, x_train, y_train) Distribution for Beta = 10 To compare the difference, I also train the above autoencoder for \beta =0 i.e we remove the Kl-divergence loss, and it generated the following distribution: Distribution for Beta = 0 Here, we can see that the distribution is not separable and quite skewed for different values, that’s why we use KL-divergence loss in the above variational autoencoder. References: Variational Autoencoder Paper Keras Variational Autoencoder simmytarika5 Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25589, "s": 25561, "text": "\n27 Jan, 2022" }, { "code": null, "e": 25992, "s": 25589, "text": "Variational autoencoder was proposed in 2013 by Knigma and Welling at Google and Qualcomm. A variational autoencoder (VAE) provides a probabilistic manner for describing an observation in latent space. Thus, rather than building an encoder that outputs a single value to describe each latent state attribute, we’ll formulate our encoder to describe a probability distribution for each latent attribute." }, { "code": null, "e": 26036, "s": 25992, "text": "Autoencoders basically contains two parts: " }, { "code": null, "e": 26262, "s": 26036, "text": "The first one is an encoder which is similar to the convolution neural network except for the last layer. The aim of the encoder is to learn efficient data encoding from the dataset and pass it into a bottleneck architecture." }, { "code": null, "e": 26491, "s": 26262, "text": "The other part of the autoencoder is a decoder that uses latent space in the bottleneck layer to regenerate the images similar to the dataset. These results backpropagate from the neural network in the form of the loss function." }, { "code": null, "e": 26804, "s": 26491, "text": "Variational autoencoder is different from autoencoder in a way such that it provides a statistical manner for describing the samples of the dataset in latent space. Therefore, in the variational autoencoder, the encoder outputs a probability distribution in the bottleneck layer instead of a single output value." }, { "code": null, "e": 26982, "s": 26804, "text": "The Variational Autoencoder latent space is continuous. It provides random sampling and interpolation. Instead of outputting a vector of size n, the encoder outputs two vectors:" }, { "code": null, "e": 27020, "s": 26982, "text": "Vector ???? of means (vector size n)" }, { "code": null, "e": 27071, "s": 27020, "text": "Vector ???? of standard deviations (vector size n)" }, { "code": null, "e": 27209, "s": 27071, "text": "Output is an approximate posterior distribution q(z|x). Sample from this distribution to get z. let’s look at more details into Sampling:" }, { "code": null, "e": 27264, "s": 27209, "text": "Let’s take some values of mean and standard deviation," }, { "code": null, "e": 27323, "s": 27264, "text": "The intermediate distribution that is generated from that:" }, { "code": null, "e": 27373, "s": 27323, "text": "Now, let’s generate the sampled vector from this:" }, { "code": null, "e": 27483, "s": 27373, "text": "While the mean and standard deviation are the same for one input the result may be different due to sampling." }, { "code": null, "e": 27681, "s": 27483, "text": "Eventually, our goal is to make the encoder learn to generate differently???? For different classes, clustering them and generating encoding such they don’t vary much. To this we use KL-divergence." }, { "code": null, "e": 27920, "s": 27681, "text": "KL divergence stands for Kullback Leibler Divergence, it is a measure of divergence between two distributions. Our goal is to Minimize KL divergence and optimize ???? and ???? of one distribution to resemble the required distribution.Of " }, { "code": null, "e": 28008, "s": 27920, "text": "For multiple distribution the KL-divergence can be calculated as the following formula:" }, { "code": null, "e": 28084, "s": 28008, "text": "where X_j \\sim N(\\mu_j, \\sigma_j^{2}) is the standard normal distribution." }, { "code": null, "e": 28207, "s": 28084, "text": "Suppose we have a distribution z and we want to generate the observation x from it. In other words, we want to calculate " }, { "code": null, "e": 28240, "s": 28209, "text": "We can do it by following way:" }, { "code": null, "e": 28294, "s": 28242, "text": "But, the calculation of p(x) can be quite difficult" }, { "code": null, "e": 28563, "s": 28296, "text": "This usually makes it an intractable distribution. Hence, we need to approximate p(z|x) to q(z|x) to make it a tractable distribution. To better approximate p(z|x) to q(z|x), we will minimize the KL-divergence loss which calculates how similar two distributions are:" }, { "code": null, "e": 28666, "s": 28565, "text": "By simplifying, the above minimization problem is equivalent to the following maximization problem :" }, { "code": null, "e": 28828, "s": 28668, "text": "The first term represents the reconstruction likelihood and the other term ensures that our learned distribution q is similar to the true prior distribution p." }, { "code": null, "e": 28936, "s": 28828, "text": "Thus our total loss consists of two terms, one is reconstruction error and the other is KL-divergence loss:" }, { "code": null, "e": 29097, "s": 28936, "text": "In this implementation, we will be using the MNIST dataset, this dataset is already available in keras.datasets API, so we don’t need to add or upload manually." }, { "code": null, "e": 29233, "s": 29097, "text": "First, we need to import the necessary packages to our python environment. we will be using Keras package with TensorFlow as a backend." }, { "code": null, "e": 29241, "s": 29233, "text": "python3" }, { "code": "# codeimport numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import Input, Modelfrom tensorflow.keras.layers import Layer, Conv2D, Flatten, Dense, Reshape, Conv2DTransposeimport matplotlib.pyplot as plt", "e": 29480, "s": 29241, "text": null }, { "code": null, "e": 29662, "s": 29480, "text": "For variational autoencoders, we need to define the architecture of two parts encoder and decoder but first, we will define the bottleneck layer of architecture, the sampling layer." }, { "code": null, "e": 29670, "s": 29662, "text": "python3" }, { "code": "# this sampling layer is the bottleneck layer of variational autoencoder,# it uses the output from two dense layers z_mean and z_log_var as input,# convert them into normal distribution and pass them to the decoder layerclass Sampling(Layer): def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape =(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon", "e": 30169, "s": 29670, "text": null }, { "code": null, "e": 30329, "s": 30169, "text": "Now, we define the architecture of the encoder part of our autoencoder, this part takes images as input and encodes their representation in the Sampling layer." }, { "code": null, "e": 30337, "s": 30329, "text": "python3" }, { "code": "# Define Encoder Modellatent_dim = 2 encoder_inputs = Input(shape =(28, 28, 1))x = Conv2D(32, 3, activation =\"relu\", strides = 2, padding =\"same\")(encoder_inputs)x = Conv2D(64, 3, activation =\"relu\", strides = 2, padding =\"same\")(x)x = Flatten()(x)x = Dense(16, activation =\"relu\")(x)z_mean = Dense(latent_dim, name =\"z_mean\")(x)z_log_var = Dense(latent_dim, name =\"z_log_var\")(x)z = Sampling()([z_mean, z_log_var])encoder = Model(encoder_inputs, [z_mean, z_log_var, z], name =\"encoder\")encoder.summary()", "e": 30842, "s": 30337, "text": null }, { "code": null, "e": 33010, "s": 30842, "text": "Model: \"encoder\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_3 (InputLayer) [(None, 28, 28, 1)] 0 \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 14, 14, 32) 320 input_3[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 7, 7, 64) 18496 conv2d_2[0][0] \n__________________________________________________________________________________________________\nflatten_1 (Flatten) (None, 3136) 0 conv2d_3[0][0] \n__________________________________________________________________________________________________\ndense_2 (Dense) (None, 16) 50192 flatten_1[0][0] \n__________________________________________________________________________________________________\nz_mean (Dense) (None, 2) 34 dense_2[0][0] \n__________________________________________________________________________________________________\nz_log_var (Dense) (None, 2) 34 dense_2[0][0] \n__________________________________________________________________________________________________\nsampling_1 (Sampling) (None, 2) 0 z_mean[0][0] \n z_log_var[0][0] \n==================================================================================================\nTotal params: 69, 076\nTrainable params: 69, 076\nNon-trainable params: 0\n__________________________________________________________________________________________________" }, { "code": null, "e": 33179, "s": 33010, "text": "Now, we define the architecture of decoder part of our autoencoder, this part takes the output of the sampling layer as input and output an image of size (28, 28, 1) . " }, { "code": null, "e": 33187, "s": 33179, "text": "python3" }, { "code": "# Define Decoder Architecturelatent_inputs = keras.Input(shape =(latent_dim, ))x = Dense(7 * 7 * 64, activation =\"relu\")(latent_inputs)x = Reshape((7, 7, 64))(x)x = Conv2DTranspose(64, 3, activation =\"relu\", strides = 2, padding =\"same\")(x)x = Conv2DTranspose(32, 3, activation =\"relu\", strides = 2, padding =\"same\")(x)decoder_outputs = Conv2DTranspose(1, 3, activation =\"sigmoid\", padding =\"same\")(x)decoder = Model(latent_inputs, decoder_outputs, name =\"decoder\")decoder.summary()", "e": 33670, "s": 33187, "text": null }, { "code": null, "e": 34815, "s": 33670, "text": "Model: \"decoder\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_4 (InputLayer) [(None, 2)] 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 3136) 9408 \n_________________________________________________________________\nreshape_1 (Reshape) (None, 7, 7, 64) 0 \n_________________________________________________________________\nconv2d_transpose_3 (Conv2DTr (None, 14, 14, 64) 36928 \n_________________________________________________________________\nconv2d_transpose_4 (Conv2DTr (None, 28, 28, 32) 18464 \n_________________________________________________________________\nconv2d_transpose_5 (Conv2DTr (None, 28, 28, 1) 289 \n=================================================================\nTotal params: 65, 089\nTrainable params: 65, 089\nNon-trainable params: 0\n_________________________________________________________________" }, { "code": null, "e": 34906, "s": 34815, "text": "In this step, we combine the model and define the training procedure with loss functions. " }, { "code": null, "e": 34914, "s": 34906, "text": "python3" }, { "code": "# this class takes encoder and decoder models and# define the complete variational autoencoder architectureclass VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder def train_step(self, data): if isinstance(data, tuple): data = data[0] with tf.GradientTape() as tape: z_mean, z_log_var, z = encoder(data) reconstruction = decoder(z) reconstruction_loss = tf.reduce_mean( keras.losses.binary_crossentropy(data, reconstruction) ) reconstruction_loss *= 28 * 28 kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var) kl_loss = tf.reduce_mean(kl_loss) kl_loss *= -0.5 # beta =10 total_loss = reconstruction_loss + 10 * kl_loss grads = tape.gradient(total_loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) return { \"loss\": total_loss, \"reconstruction_loss\": reconstruction_loss, \"kl_loss\": kl_loss, }", "e": 36101, "s": 34914, "text": null }, { "code": null, "e": 36250, "s": 36101, "text": "Now it’s the right time to train our variational autoencoder model, we will train it for 100 epochs. But first we need to import the MNIST dataset." }, { "code": null, "e": 36258, "s": 36250, "text": "python3" }, { "code": "# load fashion mnist dataset from keras.dataset API(x_train, _), (x_test, _) = keras.datasets.fashion_mnist.load_data()fmnist_images = np.concatenate([x_train, x_test], axis = 0)# expand dimension to add a color map dimensionfmnist_images = np.expand_dims(fmnist_images, -1).astype(\"float32\") / 255 # compile and train the modelvae = VAE(encoder, decoder)vae.compile(optimizer ='rmsprop')vae.fit(fmnist_images, epochs = 100, batch_size = 128)", "e": 36704, "s": 36258, "text": null }, { "code": null, "e": 36834, "s": 36704, "text": "In this step, we display training results, we will be displaying these results according to their values in latent space vectors." }, { "code": null, "e": 36842, "s": 36834, "text": "python3" }, { "code": "def plot_latent(encoder, decoder): # display a n * n 2D manifold of images n = 10 img_dim = 28 scale = 2.0 figsize = 15 figure = np.zeros((img_dim * n, img_dim * n)) # linearly spaced coordinates corresponding to the 2D plot # of images classes in the latent space grid_x = np.linspace(-scale, scale, n) grid_y = np.linspace(-scale, scale, n)[::-1] for i, yi in enumerate(grid_y): for j, xi in enumerate(grid_x): z_sample = np.array([[xi, yi]]) x_decoded = decoder.predict(z_sample) images = x_decoded[0].reshape(img_dim, img_dim) figure[ i * img_dim : (i + 1) * img_dim, j * img_dim : (j + 1) * img_dim, ] = images plt.figure(figsize =(figsize, figsize)) start_range = img_dim // 2 end_range = n * img_dim + start_range + 1 pixel_range = np.arange(start_range, end_range, img_dim) sample_range_x = np.round(grid_x, 1) sample_range_y = np.round(grid_y, 1) plt.xticks(pixel_range, sample_range_x) plt.yticks(pixel_range, sample_range_y) plt.xlabel(\"z[0]\") plt.ylabel(\"z[1]\") plt.imshow(figure, cmap =\"Greys_r\") plt.show() plot_latent(encoder, decoder)", "e": 38057, "s": 36842, "text": null }, { "code": null, "e": 38077, "s": 38057, "text": "Output from Encoder" }, { "code": null, "e": 38296, "s": 38077, "text": "To get a more clear view of our representational latent vectors values, we will be plotting the scatter plot of training data on the basis of their values of corresponding latent dimensions generated from the encoder " }, { "code": null, "e": 38304, "s": 38296, "text": "python3" }, { "code": "def plot_label_clusters(encoder, decoder, data, test_lab): z_mean, _, _ = encoder.predict(data) plt.figure(figsize =(12, 10)) sc = plt.scatter(z_mean[:, 0], z_mean[:, 1], c = test_lab) cbar = plt.colorbar(sc, ticks = range(10)) cbar.ax.set_yticklabels([i for i in range(10)]) plt.xlabel(\"z[0]\") plt.ylabel(\"z[1]\") plt.show() (x_train, y_train), _ = keras.datasets.mnist.load_data()x_train = np.expand_dims(x_train, -1).astype(\"float32\") / 255plot_label_clusters(encoder, decoder, x_train, y_train)", "e": 38826, "s": 38304, "text": null }, { "code": null, "e": 38856, "s": 38829, "text": "Distribution for Beta = 10" }, { "code": null, "e": 39016, "s": 38858, "text": "To compare the difference, I also train the above autoencoder for \\beta =0 i.e we remove the Kl-divergence loss, and it generated the following distribution:" }, { "code": null, "e": 39042, "s": 39016, "text": "Distribution for Beta = 0" }, { "code": null, "e": 39212, "s": 39042, "text": "Here, we can see that the distribution is not separable and quite skewed for different values, that’s why we use KL-divergence loss in the above variational autoencoder." }, { "code": null, "e": 39224, "s": 39212, "text": "References:" }, { "code": null, "e": 39254, "s": 39224, "text": "Variational Autoencoder Paper" }, { "code": null, "e": 39284, "s": 39254, "text": "Keras Variational Autoencoder" }, { "code": null, "e": 39297, "s": 39284, "text": "simmytarika5" }, { "code": null, "e": 39312, "s": 39297, "text": "Neural Network" }, { "code": null, "e": 39329, "s": 39312, "text": "Machine Learning" }, { "code": null, "e": 39336, "s": 39329, "text": "Python" }, { "code": null, "e": 39353, "s": 39336, "text": "Machine Learning" }, { "code": null, "e": 39451, "s": 39353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39492, "s": 39451, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 39525, "s": 39492, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 39553, "s": 39525, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 39589, "s": 39553, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 39644, "s": 39589, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 39672, "s": 39644, "text": "Read JSON file using Python" }, { "code": null, "e": 39722, "s": 39672, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 39744, "s": 39722, "text": "Python map() function" } ]
Find smallest possible Number from a given large Number with same count of digits - GeeksforGeeks
20 Jan, 2022 Given a number K of length N, the task is to find the smallest possible number that can be formed from K of N digits by swapping the digits any number of times. Examples: Input: N = 15, K = 325343273113434 Output: 112233333344457 Explanation: The smallest number possible after swapping the digits of the given number is 112233333344457 Input: N = 7, K = 3416781 Output: 1134678 Approach: The idea is to use Hashing. To implement the hash, an array arr[] of size 10 is created. The given number is iterated and the count of occurrence of every digit is stored in the hash at the corresponding index. Then iterate the hash array and print the ith digit according to its frequency. The output will be the smallest required number of N digits. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach #include <iostream>using namespace std; // Function for finding the smallest// possible number after swapping// the digits any number of timesstring smallestPoss(string s, int n){ // Variable to store the final answer string ans = ""; // Array to store the count of // occurrence of each digit int arr[10] = { 0 }; // Loop to calculate the number // of occurrences of every digit for (int i = 0; i < n; i++) { arr[s[i] - 48]++; } // Loop to get smallest number for (int i = 0; i < 10; i++) { for (int j = 0; j < arr[i]; j++) ans = ans + to_string(i); } // Returning the answer return ans;} // Driver codeint main(){ int N = 15; string K = "325343273113434"; cout << smallestPoss(K, N); return 0;} // Java implementation of the above approachclass GFG{ // Function for finding the smallest// possible number after swapping// the digits any number of timesstatic String smallestPoss(String s, int n){ // Variable to store the final answer String ans = ""; // Array to store the count of // occurrence of each digit int arr[] = new int[10]; // Loop to calculate the number // of occurrences of every digit for (int i = 0; i < n; i++) { arr[s.charAt(i) - 48]++; } // Loop to get smallest number for (int i = 0; i < 10; i++) { for (int j = 0; j < arr[i]; j++) ans = ans + String.valueOf(i); } // Returning the answer return ans;} // Driver codepublic static void main(String[] args){ int N = 15; String K = "325343273113434"; System.out.print(smallestPoss(K, N));}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the above approach # Function for finding the smallest# possible number after swapping# the digits any number of timesdef smallestPoss(s, n): # Variable to store the final answer ans = ""; # Array to store the count of # occurrence of each digit arr = [0]*10; # Loop to calculate the number # of occurrences of every digit for i in range(n): arr[ord(s[i]) - 48] += 1; # Loop to get smallest number for i in range(10): for j in range(arr[i]): ans = ans + str(i); # Returning the answer return ans; # Driver codeif __name__ == '__main__': N = 15; K = "325343273113434"; print(smallestPoss(K, N)); # This code is contributed by 29AjayKumar // C# implementation of the above approachusing System; class GFG{ // Function for finding the smallest// possible number after swapping// the digits any number of timesstatic String smallestPoss(String s, int n){ // Variable to store the readonly answer String ans = ""; // Array to store the count of // occurrence of each digit int []arr = new int[10]; // Loop to calculate the number // of occurrences of every digit for (int i = 0; i < n; i++) { arr[s[i] - 48]++; } // Loop to get smallest number for (int i = 0; i < 10; i++) { for (int j = 0; j < arr[i]; j++) ans = ans + String.Join("",i); } // Returning the answer return ans;} // Driver codepublic static void Main(String[] args){ int N = 15; String K = "325343273113434"; Console.Write(smallestPoss(K, N));}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the above approach // Function for finding the smallest// possible number after swapping// the digits any number of timesfunction smallestPoss(s, n){ // Variable to store the final answer var ans = ""; // Array to store the count of // occurrence of each digit var arr = Array(10).fill(0); // Loop to calculate the number // of occurrences of every digit for (var i = 0; i < n; i++) { arr[s[i].charCodeAt(0) - 48]++; } // Loop to get smallest number for (var i = 0; i < 10; i++) { for (var j = 0; j < arr[i]; j++) ans = ans + i.toString(); } // Returning the answer return ans;} // Driver codevar N = 15;var K = "325343273113434";document.write( smallestPoss(K, N)); </script> 112233333344457 Time Complexity: O(N) Auxiliary Space: O(N + 10) princiraj1992 29AjayKumar itsok sweetyty subhammahato348 large-numbers number-digits Arrays Hash Mathematical Arrays Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26041, "s": 26013, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26203, "s": 26041, "text": "Given a number K of length N, the task is to find the smallest possible number that can be formed from K of N digits by swapping the digits any number of times. " }, { "code": null, "e": 26214, "s": 26203, "text": "Examples: " }, { "code": null, "e": 26380, "s": 26214, "text": "Input: N = 15, K = 325343273113434 Output: 112233333344457 Explanation: The smallest number possible after swapping the digits of the given number is 112233333344457" }, { "code": null, "e": 26423, "s": 26380, "text": "Input: N = 7, K = 3416781 Output: 1134678 " }, { "code": null, "e": 26785, "s": 26423, "text": "Approach: The idea is to use Hashing. To implement the hash, an array arr[] of size 10 is created. The given number is iterated and the count of occurrence of every digit is stored in the hash at the corresponding index. Then iterate the hash array and print the ith digit according to its frequency. The output will be the smallest required number of N digits." }, { "code": null, "e": 26838, "s": 26785, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26842, "s": 26838, "text": "C++" }, { "code": null, "e": 26847, "s": 26842, "text": "Java" }, { "code": null, "e": 26855, "s": 26847, "text": "Python3" }, { "code": null, "e": 26858, "s": 26855, "text": "C#" }, { "code": null, "e": 26869, "s": 26858, "text": "Javascript" }, { "code": "// C++ implementation of the above approach #include <iostream>using namespace std; // Function for finding the smallest// possible number after swapping// the digits any number of timesstring smallestPoss(string s, int n){ // Variable to store the final answer string ans = \"\"; // Array to store the count of // occurrence of each digit int arr[10] = { 0 }; // Loop to calculate the number // of occurrences of every digit for (int i = 0; i < n; i++) { arr[s[i] - 48]++; } // Loop to get smallest number for (int i = 0; i < 10; i++) { for (int j = 0; j < arr[i]; j++) ans = ans + to_string(i); } // Returning the answer return ans;} // Driver codeint main(){ int N = 15; string K = \"325343273113434\"; cout << smallestPoss(K, N); return 0;}", "e": 27695, "s": 26869, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function for finding the smallest// possible number after swapping// the digits any number of timesstatic String smallestPoss(String s, int n){ // Variable to store the final answer String ans = \"\"; // Array to store the count of // occurrence of each digit int arr[] = new int[10]; // Loop to calculate the number // of occurrences of every digit for (int i = 0; i < n; i++) { arr[s.charAt(i) - 48]++; } // Loop to get smallest number for (int i = 0; i < 10; i++) { for (int j = 0; j < arr[i]; j++) ans = ans + String.valueOf(i); } // Returning the answer return ans;} // Driver codepublic static void main(String[] args){ int N = 15; String K = \"325343273113434\"; System.out.print(smallestPoss(K, N));}} // This code is contributed by PrinciRaj1992", "e": 28591, "s": 27695, "text": null }, { "code": "# Python3 implementation of the above approach # Function for finding the smallest# possible number after swapping# the digits any number of timesdef smallestPoss(s, n): # Variable to store the final answer ans = \"\"; # Array to store the count of # occurrence of each digit arr = [0]*10; # Loop to calculate the number # of occurrences of every digit for i in range(n): arr[ord(s[i]) - 48] += 1; # Loop to get smallest number for i in range(10): for j in range(arr[i]): ans = ans + str(i); # Returning the answer return ans; # Driver codeif __name__ == '__main__': N = 15; K = \"325343273113434\"; print(smallestPoss(K, N)); # This code is contributed by 29AjayKumar", "e": 29344, "s": 28591, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function for finding the smallest// possible number after swapping// the digits any number of timesstatic String smallestPoss(String s, int n){ // Variable to store the readonly answer String ans = \"\"; // Array to store the count of // occurrence of each digit int []arr = new int[10]; // Loop to calculate the number // of occurrences of every digit for (int i = 0; i < n; i++) { arr[s[i] - 48]++; } // Loop to get smallest number for (int i = 0; i < 10; i++) { for (int j = 0; j < arr[i]; j++) ans = ans + String.Join(\"\",i); } // Returning the answer return ans;} // Driver codepublic static void Main(String[] args){ int N = 15; String K = \"325343273113434\"; Console.Write(smallestPoss(K, N));}} // This code is contributed by PrinciRaj1992", "e": 30245, "s": 29344, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function for finding the smallest// possible number after swapping// the digits any number of timesfunction smallestPoss(s, n){ // Variable to store the final answer var ans = \"\"; // Array to store the count of // occurrence of each digit var arr = Array(10).fill(0); // Loop to calculate the number // of occurrences of every digit for (var i = 0; i < n; i++) { arr[s[i].charCodeAt(0) - 48]++; } // Loop to get smallest number for (var i = 0; i < 10; i++) { for (var j = 0; j < arr[i]; j++) ans = ans + i.toString(); } // Returning the answer return ans;} // Driver codevar N = 15;var K = \"325343273113434\";document.write( smallestPoss(K, N)); </script>", "e": 31034, "s": 30245, "text": null }, { "code": null, "e": 31050, "s": 31034, "text": "112233333344457" }, { "code": null, "e": 31074, "s": 31052, "text": "Time Complexity: O(N)" }, { "code": null, "e": 31101, "s": 31074, "text": "Auxiliary Space: O(N + 10)" }, { "code": null, "e": 31115, "s": 31101, "text": "princiraj1992" }, { "code": null, "e": 31127, "s": 31115, "text": "29AjayKumar" }, { "code": null, "e": 31133, "s": 31127, "text": "itsok" }, { "code": null, "e": 31142, "s": 31133, "text": "sweetyty" }, { "code": null, "e": 31158, "s": 31142, "text": "subhammahato348" }, { "code": null, "e": 31172, "s": 31158, "text": "large-numbers" }, { "code": null, "e": 31186, "s": 31172, "text": "number-digits" }, { "code": null, "e": 31193, "s": 31186, "text": "Arrays" }, { "code": null, "e": 31198, "s": 31193, "text": "Hash" }, { "code": null, "e": 31211, "s": 31198, "text": "Mathematical" }, { "code": null, "e": 31218, "s": 31211, "text": "Arrays" }, { "code": null, "e": 31223, "s": 31218, "text": "Hash" }, { "code": null, "e": 31236, "s": 31223, "text": "Mathematical" }, { "code": null, "e": 31334, "s": 31236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31361, "s": 31334, "text": "Count pairs with given sum" }, { "code": null, "e": 31392, "s": 31361, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31417, "s": 31392, "text": "Window Sliding Technique" }, { "code": null, "e": 31455, "s": 31417, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31476, "s": 31455, "text": "Next Greater Element" }, { "code": null, "e": 31512, "s": 31476, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 31539, "s": 31512, "text": "Count pairs with given sum" }, { "code": null, "e": 31570, "s": 31539, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 31604, "s": 31570, "text": "Hashing | Set 3 (Open Addressing)" } ]
C# | Remove a range of elements from the ArrayList - GeeksforGeeks
01 Feb, 2019 ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveRange(Int32, Int32) method is used to remove a range of elements from the ArrayList. Properties of the ArrayList Class: Elements can be added or removed from the Array List collection at any point in time. The ArrayList is not guaranteed to be sorted. The capacity of an ArrayList is the number of elements the ArrayList can hold. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. It also allows duplicate elements. Using multidimensional arrays as elements in an ArrayList collection is not supported. Syntax: public virtual void RemoveRange (int index, int count); Parameters: index : It is the zero-based starting index of the range of elements to remove. count : It is the number of elements which is to be removed. Exceptions: ArgumentOutOfRangeException : If index is less than zero or count is less than zero. ArgumentException : If index and count do not denote a valid range of elements in the ArrayList. NotSupportedException : If the ArrayList is read-only or the ArrayList has a fixed size. Note: This method is an O(n) operation, where n is Count. Below programs illustrate the use of ArrayList.RemoveRange(Int32, Int32) method: Example 1: // C# code to remove a range of// elements from the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); myList.Add("G"); myList.Add("H"); myList.Add("I"); myList.Add("J"); // Displaying the elements in ArrayList Console.WriteLine("The initial ArrayList is: "); foreach(string str in myList) { Console.WriteLine(str); } // removing 2 elements starting from index 2 myList.RemoveRange(2, 2); // Displaying the modified ArrayList Console.WriteLine("The ArrayList after Removing elements: "); // Displaying the elements in ArrayList foreach(string str in myList) { Console.WriteLine(str); } }} The initial ArrayList is: A B C D E F G H I J The ArrayList after Removing elements: A B E F G H I J Example 2: // C# code to remove a range of// elements from the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(2); myList.Add(4); myList.Add(6); myList.Add(8); myList.Add(10); myList.Add(12); myList.Add(14); myList.Add(16); myList.Add(18); myList.Add(20); // Displaying the elements in ArrayList Console.WriteLine("The initial ArrayList: "); foreach(int i in myList) { Console.WriteLine(i); } // removing 4 elements starting from index 0 myList.RemoveRange(0, 4); // Displaying the modified ArrayList Console.WriteLine("The ArrayList after Removing elements: "); // Displaying the elements in ArrayList foreach(int i in myList) { Console.WriteLine(i); } }} The initial ArrayList is: 2 4 6 8 10 12 14 16 18 20 The ArrayList after Removing elements: 10 12 14 16 18 20 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.removerange?view=netframework-4.7.2 CSharp-Collections-ArrayList CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | Replace() Method Introduction to .NET Framework
[ { "code": null, "e": 26193, "s": 26165, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26519, "s": 26193, "text": "ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveRange(Int32, Int32) method is used to remove a range of elements from the ArrayList." }, { "code": null, "e": 26554, "s": 26519, "text": "Properties of the ArrayList Class:" }, { "code": null, "e": 26640, "s": 26554, "text": "Elements can be added or removed from the Array List collection at any point in time." }, { "code": null, "e": 26686, "s": 26640, "text": "The ArrayList is not guaranteed to be sorted." }, { "code": null, "e": 26765, "s": 26686, "text": "The capacity of an ArrayList is the number of elements the ArrayList can hold." }, { "code": null, "e": 26876, "s": 26765, "text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based." }, { "code": null, "e": 26911, "s": 26876, "text": "It also allows duplicate elements." }, { "code": null, "e": 26998, "s": 26911, "text": "Using multidimensional arrays as elements in an ArrayList collection is not supported." }, { "code": null, "e": 27006, "s": 26998, "text": "Syntax:" }, { "code": null, "e": 27063, "s": 27006, "text": "public virtual void RemoveRange (int index, int count);\n" }, { "code": null, "e": 27075, "s": 27063, "text": "Parameters:" }, { "code": null, "e": 27155, "s": 27075, "text": "index : It is the zero-based starting index of the range of elements to remove." }, { "code": null, "e": 27216, "s": 27155, "text": "count : It is the number of elements which is to be removed." }, { "code": null, "e": 27228, "s": 27216, "text": "Exceptions:" }, { "code": null, "e": 27313, "s": 27228, "text": "ArgumentOutOfRangeException : If index is less than zero or count is less than zero." }, { "code": null, "e": 27410, "s": 27313, "text": "ArgumentException : If index and count do not denote a valid range of elements in the ArrayList." }, { "code": null, "e": 27499, "s": 27410, "text": "NotSupportedException : If the ArrayList is read-only or the ArrayList has a fixed size." }, { "code": null, "e": 27557, "s": 27499, "text": "Note: This method is an O(n) operation, where n is Count." }, { "code": null, "e": 27638, "s": 27557, "text": "Below programs illustrate the use of ArrayList.RemoveRange(Int32, Int32) method:" }, { "code": null, "e": 27649, "s": 27638, "text": "Example 1:" }, { "code": "// C# code to remove a range of// elements from the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(\"A\"); myList.Add(\"B\"); myList.Add(\"C\"); myList.Add(\"D\"); myList.Add(\"E\"); myList.Add(\"F\"); myList.Add(\"G\"); myList.Add(\"H\"); myList.Add(\"I\"); myList.Add(\"J\"); // Displaying the elements in ArrayList Console.WriteLine(\"The initial ArrayList is: \"); foreach(string str in myList) { Console.WriteLine(str); } // removing 2 elements starting from index 2 myList.RemoveRange(2, 2); // Displaying the modified ArrayList Console.WriteLine(\"The ArrayList after Removing elements: \"); // Displaying the elements in ArrayList foreach(string str in myList) { Console.WriteLine(str); } }}", "e": 28753, "s": 27649, "text": null }, { "code": null, "e": 28857, "s": 28753, "text": "The initial ArrayList is: \nA\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nThe ArrayList after Removing elements: \nA\nB\nE\nF\nG\nH\nI\nJ\n" }, { "code": null, "e": 28868, "s": 28857, "text": "Example 2:" }, { "code": "// C# code to remove a range of// elements from the ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(10); // Adding elements to ArrayList myList.Add(2); myList.Add(4); myList.Add(6); myList.Add(8); myList.Add(10); myList.Add(12); myList.Add(14); myList.Add(16); myList.Add(18); myList.Add(20); // Displaying the elements in ArrayList Console.WriteLine(\"The initial ArrayList: \"); foreach(int i in myList) { Console.WriteLine(i); } // removing 4 elements starting from index 0 myList.RemoveRange(0, 4); // Displaying the modified ArrayList Console.WriteLine(\"The ArrayList after Removing elements: \"); // Displaying the elements in ArrayList foreach(int i in myList) { Console.WriteLine(i); } }}", "e": 29941, "s": 28868, "text": null }, { "code": null, "e": 30053, "s": 29941, "text": "The initial ArrayList is: \n2\n4\n6\n8\n10\n12\n14\n16\n18\n20\nThe ArrayList after Removing elements: \n10\n12\n14\n16\n18\n20\n" }, { "code": null, "e": 30064, "s": 30053, "text": "Reference:" }, { "code": null, "e": 30173, "s": 30064, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.removerange?view=netframework-4.7.2" }, { "code": null, "e": 30202, "s": 30173, "text": "CSharp-Collections-ArrayList" }, { "code": null, "e": 30231, "s": 30202, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 30245, "s": 30231, "text": "CSharp-method" }, { "code": null, "e": 30248, "s": 30245, "text": "C#" }, { "code": null, "e": 30346, "s": 30248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30374, "s": 30346, "text": "C# Dictionary with examples" }, { "code": null, "e": 30389, "s": 30374, "text": "C# | Delegates" }, { "code": null, "e": 30412, "s": 30389, "text": "C# | Method Overriding" }, { "code": null, "e": 30434, "s": 30412, "text": "C# | Abstract Classes" }, { "code": null, "e": 30480, "s": 30434, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30503, "s": 30480, "text": "Extension Method in C#" }, { "code": null, "e": 30525, "s": 30503, "text": "C# | Class and Object" }, { "code": null, "e": 30543, "s": 30525, "text": "C# | Constructors" }, { "code": null, "e": 30565, "s": 30543, "text": "C# | Replace() Method" } ]
How to draw a pie chart using react bootstrap ? - GeeksforGeeks
02 Jul, 2021 A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. The area of slices of the pie represents the percentage of the parts of the data. Creating React Application And Installing Module: Step 1: Create a React application using the following commandnpx create-react-app foldername npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername cd foldername Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2 npm install --save mdbreact react-chartjs-2 Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css'; import 'bootstrap-css-only/css/bootstrap.min.css'; import 'mdbreact/dist/css/mdb.css'; import '@fortawesome/fontawesome-free/css/all.min.css'; import 'bootstrap-css-only/css/bootstrap.min.css'; import 'mdbreact/dist/css/mdb.css'; Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import { MDBContainer } from "mdbreact";import { Pie } from "react-chartjs-2"; const App = () => { // Sample data const data = { labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], datasets: [ { label: "Hours Studied in Geeksforgeeks", data: [2, 5, 6, 7, 3], backgroundColor: ["blue", "green", "yellow", "pink", "orange"], } ] } return ( <MDBContainer> <Pie data={data} /> </MDBContainer> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output Picked React-Bootstrap React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to redirect to another page in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS useNavigate() Hook ReactJS defaultProps Re-rendering Components in ReactJS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25585, "s": 25557, "text": "\n02 Jul, 2021" }, { "code": null, "e": 25818, "s": 25585, "text": "A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. The area of slices of the pie represents the percentage of the parts of the data. " }, { "code": null, "e": 25868, "s": 25818, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25962, "s": 25868, "text": "Step 1: Create a React application using the following commandnpx create-react-app foldername" }, { "code": null, "e": 25994, "s": 25962, "text": "npx create-react-app foldername" }, { "code": null, "e": 26107, "s": 25994, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 26121, "s": 26107, "text": "cd foldername" }, { "code": null, "e": 26270, "s": 26121, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2" }, { "code": null, "e": 26314, "s": 26270, "text": "npm install --save mdbreact react-chartjs-2" }, { "code": null, "e": 26519, "s": 26314, "text": "Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css'; \nimport 'bootstrap-css-only/css/bootstrap.min.css'; \nimport 'mdbreact/dist/css/mdb.css';" }, { "code": null, "e": 26666, "s": 26519, "text": "import '@fortawesome/fontawesome-free/css/all.min.css'; \nimport 'bootstrap-css-only/css/bootstrap.min.css'; \nimport 'mdbreact/dist/css/mdb.css';" }, { "code": null, "e": 26718, "s": 26666, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26736, "s": 26718, "text": "Project Structure" }, { "code": null, "e": 26866, "s": 26736, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26873, "s": 26866, "text": "App.js" }, { "code": "import React from \"react\";import { MDBContainer } from \"mdbreact\";import { Pie } from \"react-chartjs-2\"; const App = () => { // Sample data const data = { labels: [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\"], datasets: [ { label: \"Hours Studied in Geeksforgeeks\", data: [2, 5, 6, 7, 3], backgroundColor: [\"blue\", \"green\", \"yellow\", \"pink\", \"orange\"], } ] } return ( <MDBContainer> <Pie data={data} /> </MDBContainer> );} export default App;", "e": 27410, "s": 26873, "text": null }, { "code": null, "e": 27523, "s": 27410, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27533, "s": 27523, "text": "npm start" }, { "code": null, "e": 27632, "s": 27533, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27639, "s": 27632, "text": "Output" }, { "code": null, "e": 27646, "s": 27639, "text": "Picked" }, { "code": null, "e": 27662, "s": 27646, "text": "React-Bootstrap" }, { "code": null, "e": 27678, "s": 27662, "text": "React-Questions" }, { "code": null, "e": 27686, "s": 27678, "text": "ReactJS" }, { "code": null, "e": 27703, "s": 27686, "text": "Web Technologies" }, { "code": null, "e": 27801, "s": 27703, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27846, "s": 27801, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27914, "s": 27846, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 27941, "s": 27914, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27962, "s": 27941, "text": "ReactJS defaultProps" }, { "code": null, "e": 27997, "s": 27962, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 28037, "s": 27997, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28070, "s": 28037, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28115, "s": 28070, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28165, "s": 28115, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
tmpnam() function in C - GeeksforGeeks
06 Sep, 2017 The tmpnam() function is a special function which is declared inside “stdio.h” header file. It generates a different temporary file name each time it is called up to at least TMP_MAX names. Here TMP_MAX represents maximum number of different file names that can be produce by tmpnam() function. If it is called more than TMP_MAX times, the behavior is implementation dependent.Here, L_tmpnam define the size needed for an array of char to hold the result of tmpnam. Syntax : char *tmpnam(char *str) s : The character array to copy the file name. It generates and returns a valid temporary filename which does not exist. If str is null then it simply returns the tmp file name. // C program to generate random temporary file names.#include <stdio.h>int main(void){ // L_tmpnam declared in the stdio.h file. // L_tmpnam define length of the generated file name. char generate[L_tmpnam + 1]; // Add +1 for the null character. tmpnam(generate); puts(generate); return 0;} Output: The file names are dependent on running machine, which can be anything. Example: /tmp/fileRTOA0m \s260. \s3ok. \s5gg. etc This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [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. C-Library C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Core Dump (Segmentation fault) in C/C++ rand() and srand() in C/C++ std::string class in C++ Different methods to reverse a string in C/C++ Enumeration (or enum) in C
[ { "code": null, "e": 25549, "s": 25521, "text": "\n06 Sep, 2017" }, { "code": null, "e": 26015, "s": 25549, "text": "The tmpnam() function is a special function which is declared inside “stdio.h” header file. It generates a different temporary file name each time it is called up to at least TMP_MAX names. Here TMP_MAX represents maximum number of different file names that can be produce by tmpnam() function. If it is called more than TMP_MAX times, the behavior is implementation dependent.Here, L_tmpnam define the size needed for an array of char to hold the result of tmpnam." }, { "code": null, "e": 26024, "s": 26015, "text": "Syntax :" }, { "code": null, "e": 26228, "s": 26024, "text": "char *tmpnam(char *str)\ns : The character array to copy the file name.\nIt generates and returns a valid temporary \nfilename which does not exist. \nIf str is null then it simply returns the tmp file name." }, { "code": "// C program to generate random temporary file names.#include <stdio.h>int main(void){ // L_tmpnam declared in the stdio.h file. // L_tmpnam define length of the generated file name. char generate[L_tmpnam + 1]; // Add +1 for the null character. tmpnam(generate); puts(generate); return 0;}", "e": 26537, "s": 26228, "text": null }, { "code": null, "e": 26545, "s": 26537, "text": "Output:" }, { "code": null, "e": 26695, "s": 26545, "text": "The file names are dependent on running machine, which can be anything.\nExample: /tmp/fileRTOA0m\n \\s260.\n \\s3ok.\n \\s5gg. etc\n" }, { "code": null, "e": 27001, "s": 26695, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27126, "s": 27001, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27136, "s": 27126, "text": "C-Library" }, { "code": null, "e": 27147, "s": 27136, "text": "C Language" }, { "code": null, "e": 27245, "s": 27147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27262, "s": 27245, "text": "Substring in C++" }, { "code": null, "e": 27297, "s": 27262, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27336, "s": 27297, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 27382, "s": 27336, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27404, "s": 27382, "text": "Function Pointer in C" }, { "code": null, "e": 27444, "s": 27404, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 27472, "s": 27444, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27497, "s": 27472, "text": "std::string class in C++" }, { "code": null, "e": 27544, "s": 27497, "text": "Different methods to reverse a string in C/C++" } ]
Count digits present in each element of a given Matrix - GeeksforGeeks
07 Mar, 2022 Given a matrix arr[][] of dimensions M * N, the task is to count the number of digits of every element present in the given matrix. Examples: Input: arr[][] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }Output: 2 3 12 1 31 3 2 Input: arr[][] = { {11, 12, 33 }, { 64, 57, 61 }, { 74, 88, 39 } }Output: 2 2 22 2 22 2 2 Approach: The idea to solve this problem is to traverse the given matrix and for every index of the matrix, count the number of digits of the number present at that index using the following expression: Number of digits present in any value X is given by floor(log10(X))+1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; const int M = 3;const int N = 3; // Function to count the number of digits// in each element of the given matrixvoid countDigit(int arr[M][N]){ // Traverse each row of arr[][] for (int i = 0; i < M; i++) { // Traverse each column of arr[][] for (int j = 0; j < N; j++) { // Store the current matrix element int X = arr[i][j]; // Count the number of digits int d = floor(log10(X) * 1.0) + 1; // Print the result cout << d << " "; } cout << endl; }} // Driver Codeint main(){ // Given matrix int arr[][3] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }; countDigit(arr); return 0;} // Java program for the above approachimport java.util.*;class GFG{ static int M = 3;static int N = 3; // Function to count the number of digits// in each element of the given matrixstatic void countDigit(int arr[][]){ // Traverse each row of arr[][] for (int i = 0; i < M; i++) { // Traverse each column of arr[][] for (int j = 0; j < N; j++) { // Store the current matrix element int X = arr[i][j]; // Count the number of digits int d = (int) (Math.floor(Math.log10(X) * 1.0) + 1); // Print the result System.out.print(d+ " "); } System.out.println(); }} // Driver Codepublic static void main(String[] args){ // Given matrix int arr[][] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }; countDigit(arr);}} // This code is contributed by Princi Singh # Python3 program for the above approachfrom math import floor, log10 M = 3N = 3 # Function to count the number of digits# in each element of the given matrixdef countDigit(arr): # Traverse each row of arr[][] for i in range(M): # Traverse each column of arr[][] for j in range(N): # Store the current matrix element X = arr[i][j] # Count the number of digits d = floor(log10(X) * 1.0) + 1 # Print the result print(d, end = " ") print() # Driver Codeif __name__ == '__main__': # Given matrix arr = [ [ 27, 173, 5 ], [ 21, 6, 624 ], [ 5, 321, 49 ] ] countDigit(arr) # This code is contributed by mohit kumar 29 // C# program to implement// the above approach using System;class GFG{ static int M = 3;static int N = 3; // Function to count the number of digits// in each element of the given matrixstatic void countDigit(int[,] arr){ // Traverse each row of arr[][] for (int i = 0; i < M; i++) { // Traverse each column of arr[][] for (int j = 0; j < N; j++) { // Store the current matrix element int X = arr[i, j]; // Count the number of digits int d = (int) (Math.Floor(Math.Log10(X) * 1.0) + 1); // Print the result Console.Write(d + " "); } Console.WriteLine(); }} // Driver Codepublic static void Main(){ // Given matrix int[,] arr = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }; countDigit(arr);}} // This code is contributed by susmitakundugoaldanga <script> // JavaScript program to implement// the above approach let M = 3;let N = 3; // Function to count the number of digits// in each element of the given matrixfunction countDigit(arr){ // Traverse each row of arr[][] for (let i = 0; i < M; i++) { // Traverse each column of arr[][] for (let j = 0; j < N; j++) { // Store the current matrix element let X = arr[i][j]; // Count the number of digits let d = (Math.floor(Math.log10(X) * 1.0) + 1); // Print the result document.write(d+ " "); } document.write("<br/>"); }} // Driver code // Given matrix let arr = [[ 27, 173, 5 ], [ 21, 6, 624 ], [ 5, 321, 49 ]]; countDigit(arr); </script> 2 3 1 2 1 3 1 3 2 Time Complexity: O(M * N)Auxiliary Space: O(1) mohit kumar 29 princi singh susmitakundugoaldanga target_2 simranarora5sos number-digits Mathematical Matrix School Programming Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Rat in a Maze | Backtracking-2 Maximum size square sub-matrix with all 1s
[ { "code": null, "e": 25937, "s": 25909, "text": "\n07 Mar, 2022" }, { "code": null, "e": 26069, "s": 25937, "text": "Given a matrix arr[][] of dimensions M * N, the task is to count the number of digits of every element present in the given matrix." }, { "code": null, "e": 26079, "s": 26069, "text": "Examples:" }, { "code": null, "e": 26170, "s": 26079, "text": "Input: arr[][] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }Output: 2 3 12 1 31 3 2" }, { "code": null, "e": 26260, "s": 26170, "text": "Input: arr[][] = { {11, 12, 33 }, { 64, 57, 61 }, { 74, 88, 39 } }Output: 2 2 22 2 22 2 2" }, { "code": null, "e": 26463, "s": 26260, "text": "Approach: The idea to solve this problem is to traverse the given matrix and for every index of the matrix, count the number of digits of the number present at that index using the following expression:" }, { "code": null, "e": 26534, "s": 26463, "text": "Number of digits present in any value X is given by floor(log10(X))+1." }, { "code": null, "e": 26585, "s": 26534, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26589, "s": 26585, "text": "C++" }, { "code": null, "e": 26594, "s": 26589, "text": "Java" }, { "code": null, "e": 26602, "s": 26594, "text": "Python3" }, { "code": null, "e": 26605, "s": 26602, "text": "C#" }, { "code": null, "e": 26616, "s": 26605, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; const int M = 3;const int N = 3; // Function to count the number of digits// in each element of the given matrixvoid countDigit(int arr[M][N]){ // Traverse each row of arr[][] for (int i = 0; i < M; i++) { // Traverse each column of arr[][] for (int j = 0; j < N; j++) { // Store the current matrix element int X = arr[i][j]; // Count the number of digits int d = floor(log10(X) * 1.0) + 1; // Print the result cout << d << \" \"; } cout << endl; }} // Driver Codeint main(){ // Given matrix int arr[][3] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }; countDigit(arr); return 0;}", "e": 27446, "s": 26616, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ static int M = 3;static int N = 3; // Function to count the number of digits// in each element of the given matrixstatic void countDigit(int arr[][]){ // Traverse each row of arr[][] for (int i = 0; i < M; i++) { // Traverse each column of arr[][] for (int j = 0; j < N; j++) { // Store the current matrix element int X = arr[i][j]; // Count the number of digits int d = (int) (Math.floor(Math.log10(X) * 1.0) + 1); // Print the result System.out.print(d+ \" \"); } System.out.println(); }} // Driver Codepublic static void main(String[] args){ // Given matrix int arr[][] = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }; countDigit(arr);}} // This code is contributed by Princi Singh", "e": 28372, "s": 27446, "text": null }, { "code": "# Python3 program for the above approachfrom math import floor, log10 M = 3N = 3 # Function to count the number of digits# in each element of the given matrixdef countDigit(arr): # Traverse each row of arr[][] for i in range(M): # Traverse each column of arr[][] for j in range(N): # Store the current matrix element X = arr[i][j] # Count the number of digits d = floor(log10(X) * 1.0) + 1 # Print the result print(d, end = \" \") print() # Driver Codeif __name__ == '__main__': # Given matrix arr = [ [ 27, 173, 5 ], [ 21, 6, 624 ], [ 5, 321, 49 ] ] countDigit(arr) # This code is contributed by mohit kumar 29", "e": 29122, "s": 28372, "text": null }, { "code": "// C# program to implement// the above approach using System;class GFG{ static int M = 3;static int N = 3; // Function to count the number of digits// in each element of the given matrixstatic void countDigit(int[,] arr){ // Traverse each row of arr[][] for (int i = 0; i < M; i++) { // Traverse each column of arr[][] for (int j = 0; j < N; j++) { // Store the current matrix element int X = arr[i, j]; // Count the number of digits int d = (int) (Math.Floor(Math.Log10(X) * 1.0) + 1); // Print the result Console.Write(d + \" \"); } Console.WriteLine(); }} // Driver Codepublic static void Main(){ // Given matrix int[,] arr = { { 27, 173, 5 }, { 21, 6, 624 }, { 5, 321, 49 } }; countDigit(arr);}} // This code is contributed by susmitakundugoaldanga", "e": 30055, "s": 29122, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach let M = 3;let N = 3; // Function to count the number of digits// in each element of the given matrixfunction countDigit(arr){ // Traverse each row of arr[][] for (let i = 0; i < M; i++) { // Traverse each column of arr[][] for (let j = 0; j < N; j++) { // Store the current matrix element let X = arr[i][j]; // Count the number of digits let d = (Math.floor(Math.log10(X) * 1.0) + 1); // Print the result document.write(d+ \" \"); } document.write(\"<br/>\"); }} // Driver code // Given matrix let arr = [[ 27, 173, 5 ], [ 21, 6, 624 ], [ 5, 321, 49 ]]; countDigit(arr); </script>", "e": 30886, "s": 30055, "text": null }, { "code": null, "e": 30906, "s": 30886, "text": "2 3 1 \n2 1 3 \n1 3 2" }, { "code": null, "e": 30955, "s": 30908, "text": "Time Complexity: O(M * N)Auxiliary Space: O(1)" }, { "code": null, "e": 30970, "s": 30955, "text": "mohit kumar 29" }, { "code": null, "e": 30983, "s": 30970, "text": "princi singh" }, { "code": null, "e": 31005, "s": 30983, "text": "susmitakundugoaldanga" }, { "code": null, "e": 31014, "s": 31005, "text": "target_2" }, { "code": null, "e": 31030, "s": 31014, "text": "simranarora5sos" }, { "code": null, "e": 31044, "s": 31030, "text": "number-digits" }, { "code": null, "e": 31057, "s": 31044, "text": "Mathematical" }, { "code": null, "e": 31064, "s": 31057, "text": "Matrix" }, { "code": null, "e": 31083, "s": 31064, "text": "School Programming" }, { "code": null, "e": 31096, "s": 31083, "text": "Mathematical" }, { "code": null, "e": 31103, "s": 31096, "text": "Matrix" }, { "code": null, "e": 31201, "s": 31103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31245, "s": 31201, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 31287, "s": 31245, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 31318, "s": 31287, "text": "Modular multiplicative inverse" }, { "code": null, "e": 31389, "s": 31318, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 31414, "s": 31389, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 31449, "s": 31414, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 31493, "s": 31449, "text": "Program to find largest element in an array" }, { "code": null, "e": 31529, "s": 31493, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 31560, "s": 31529, "text": "Rat in a Maze | Backtracking-2" } ]
Lodash _.mean() Method - GeeksforGeeks
09 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.mean() method is used to find the mean of the values in the array. Syntax: _.mean( array ) Parameters: This method accepts a single parameter as mentioned above and described below: array: It is the array that the method iterates over to get the mean of all the values. Return Value: This method returns the mean of the values in the array. Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.mean() // method let mean_val = _.mean([15, 7, 38, 46, 82]); // Printing the output console.log(mean_val); Output: 37.6 Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.mean() // method let mean_val = _.mean([2, 3, 4, 6, 7, 8]); // Printing the output console.log(mean_val); Output: 5 Example 3: Javascript // Requiring the lodash library const _ = require("lodash"); // Use of _.mean() // method let mean_val = _.mean([10, -4, -6, 8, 12]); // Printing the output console.log(mean_val); Output: 4 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 38681, "s": 38653, "text": "\n09 Sep, 2020" }, { "code": null, "e": 38821, "s": 38681, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 38894, "s": 38821, "text": "The _.mean() method is used to find the mean of the values in the array." }, { "code": null, "e": 38902, "s": 38894, "text": "Syntax:" }, { "code": null, "e": 38918, "s": 38902, "text": "_.mean( array )" }, { "code": null, "e": 39009, "s": 38918, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 39097, "s": 39009, "text": "array: It is the array that the method iterates over to get the mean of all the values." }, { "code": null, "e": 39168, "s": 39097, "text": "Return Value: This method returns the mean of the values in the array." }, { "code": null, "e": 39179, "s": 39168, "text": "Example 1:" }, { "code": null, "e": 39190, "s": 39179, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.mean() // method let mean_val = _.mean([15, 7, 38, 46, 82]); // Printing the output console.log(mean_val);", "e": 39386, "s": 39190, "text": null }, { "code": null, "e": 39394, "s": 39386, "text": "Output:" }, { "code": null, "e": 39399, "s": 39394, "text": "37.6" }, { "code": null, "e": 39412, "s": 39399, "text": "Example 2: " }, { "code": null, "e": 39423, "s": 39412, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.mean() // method let mean_val = _.mean([2, 3, 4, 6, 7, 8]); // Printing the output console.log(mean_val);", "e": 39618, "s": 39423, "text": null }, { "code": null, "e": 39626, "s": 39618, "text": "Output:" }, { "code": null, "e": 39628, "s": 39626, "text": "5" }, { "code": null, "e": 39641, "s": 39628, "text": "Example 3: " }, { "code": null, "e": 39652, "s": 39641, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.mean() // method let mean_val = _.mean([10, -4, -6, 8, 12]); // Printing the output console.log(mean_val);", "e": 39848, "s": 39652, "text": null }, { "code": null, "e": 39856, "s": 39848, "text": "Output:" }, { "code": null, "e": 39858, "s": 39856, "text": "4" }, { "code": null, "e": 39876, "s": 39858, "text": "JavaScript-Lodash" }, { "code": null, "e": 39887, "s": 39876, "text": "JavaScript" }, { "code": null, "e": 39904, "s": 39887, "text": "Web Technologies" }, { "code": null, "e": 40002, "s": 39904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40042, "s": 40002, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40087, "s": 40042, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40148, "s": 40087, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40220, "s": 40148, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40289, "s": 40220, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40329, "s": 40289, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40362, "s": 40329, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40407, "s": 40362, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40450, "s": 40407, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript | Encode/Decode a string to Base64. - GeeksforGeeks
29 Apr, 2019 In order to encode/decode a string in JavaScript, We are using built-in functions provided by JavaScript. btoa():This method encodes a string in base-64 and uses the “A-Z”, “a-z”, “0-9”, “+”, “/” and “=” characters to encode the provided string. Syntax:window.btoa(String) window.btoa(String) Parameter:String: This parameter is required. It specifies the string to be encoded. atob():This method decodes a base-64 encoded string, Which has been encoded by the btoa() method. Syntax:window.atob(string) window.atob(string) Parameter:string: This parameter is required. It specifies the string which has already been encoded by the btoa() method. Here are few of the examples.Example-1: This examples encodes the string “This is GeeksForGeeks” by btoa() function. <!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> Encode </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var str = "This is GeeksForGeeks"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = window.btoa(str); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-2:This examples decodes the string “VGhpcyBpcyBHZWVrc0ZvckdlZWtz” encoded by btoa() function with the help of atob() function. <!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> Decode </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var str = "VGhpcyBpcyBHZWVrc0ZvckdlZWtz"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = window.atob(str); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: The Cross-Browser Method is used as a javascript library to encode/decode a string in any browser.Example-3:This examples encodes the string “This is GeeksForGeeks” by creating a Base64 object. <!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> Encode </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "abcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function(e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function(e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function(e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function(e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode( (r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode( (r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } } var str = "This is GeeksForGeeks"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = Base64.encode(str); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-4: This examples encodes the string “VGhpcyBpcyBHZWVrc0ZvckdlZWtz” by creating a Base64 object. <!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="Geeks()"> Decode </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"+ "ghijklmnopqrstuvwxyz0123456789+/=", encode: function(e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function(e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function(e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function(e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode( (r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode( (r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } } var str = "VGhpcyBpcyBHZWVrc0ZvckdlZWtz"; var up = document.getElementById("GFG_UP"); var down = document.getElementById("GFG_DOWN"); up.innerHTML = "Str = '" + str + "'"; function Geeks() { down.innerHTML = Base64.decode(str); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25527, "s": 25499, "text": "\n29 Apr, 2019" }, { "code": null, "e": 25633, "s": 25527, "text": "In order to encode/decode a string in JavaScript, We are using built-in functions provided by JavaScript." }, { "code": null, "e": 25773, "s": 25633, "text": "btoa():This method encodes a string in base-64 and uses the “A-Z”, “a-z”, “0-9”, “+”, “/” and “=” characters to encode the provided string." }, { "code": null, "e": 25801, "s": 25773, "text": "Syntax:window.btoa(String)\n" }, { "code": null, "e": 25822, "s": 25801, "text": "window.btoa(String)\n" }, { "code": null, "e": 25907, "s": 25822, "text": "Parameter:String: This parameter is required. It specifies the string to be encoded." }, { "code": null, "e": 26005, "s": 25907, "text": "atob():This method decodes a base-64 encoded string, Which has been encoded by the btoa() method." }, { "code": null, "e": 26033, "s": 26005, "text": "Syntax:window.atob(string)\n" }, { "code": null, "e": 26054, "s": 26033, "text": "window.atob(string)\n" }, { "code": null, "e": 26177, "s": 26054, "text": "Parameter:string: This parameter is required. It specifies the string which has already been encoded by the btoa() method." }, { "code": null, "e": 26294, "s": 26177, "text": "Here are few of the examples.Example-1: This examples encodes the string “This is GeeksForGeeks” by btoa() function." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> Encode </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var str = \"This is GeeksForGeeks\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = window.btoa(str); } </script></body> </html>", "e": 26987, "s": 26294, "text": null }, { "code": null, "e": 26995, "s": 26987, "text": "Output:" }, { "code": null, "e": 27026, "s": 26995, "text": "Before clicking on the button:" }, { "code": null, "e": 27056, "s": 27026, "text": "After clicking on the button:" }, { "code": null, "e": 27191, "s": 27056, "text": "Example-2:This examples decodes the string “VGhpcyBpcyBHZWVrc0ZvckdlZWtz” encoded by btoa() function with the help of atob() function." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> Decode </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var str = \"VGhpcyBpcyBHZWVrc0ZvckdlZWtz\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = window.atob(str); } </script></body> </html>", "e": 27879, "s": 27191, "text": null }, { "code": null, "e": 27887, "s": 27879, "text": "Output:" }, { "code": null, "e": 27918, "s": 27887, "text": "Before clicking on the button:" }, { "code": null, "e": 27948, "s": 27918, "text": "After clicking on the button:" }, { "code": null, "e": 28142, "s": 27948, "text": "The Cross-Browser Method is used as a javascript library to encode/decode a string in any browser.Example-3:This examples encodes the string “This is GeeksForGeeks” by creating a Base64 object." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> Encode </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var Base64 = { _keyStr: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"+ \"abcdefghijklmnopqrstuvwxyz0123456789+/=\", encode: function(e) { var t = \"\"; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function(e) { var t = \"\"; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\\+\\/\\=]/g, \"\"); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function(e) { e = e.replace(/\\r\\n/g, \"\\n\"); var t = \"\"; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function(e) { var t = \"\"; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode( (r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode( (r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } } var str = \"This is GeeksForGeeks\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = Base64.encode(str); } </script></body> </html>", "e": 32690, "s": 28142, "text": null }, { "code": null, "e": 32698, "s": 32690, "text": "Output:" }, { "code": null, "e": 32729, "s": 32698, "text": "Before clicking on the button:" }, { "code": null, "e": 32759, "s": 32729, "text": "After clicking on the button:" }, { "code": null, "e": 32863, "s": 32759, "text": "Example-4: This examples encodes the string “VGhpcyBpcyBHZWVrc0ZvckdlZWtz” by creating a Base64 object." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | encode/decode a string to Base64. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"Geeks()\"> Decode </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var Base64 = { _keyStr: \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef\"+ \"ghijklmnopqrstuvwxyz0123456789+/=\", encode: function(e) { var t = \"\"; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function(e) { var t = \"\"; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\\+\\/\\=]/g, \"\"); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function(e) { e = e.replace(/\\r\\n/g, \"\\n\"); var t = \"\"; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function(e) { var t = \"\"; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode( (r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode( (r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } } var str = \"VGhpcyBpcyBHZWVrc0ZvckdlZWtz\"; var up = document.getElementById(\"GFG_UP\"); var down = document.getElementById(\"GFG_DOWN\"); up.innerHTML = \"Str = '\" + str + \"'\"; function Geeks() { down.innerHTML = Base64.decode(str); } </script></body> </html>", "e": 37451, "s": 32863, "text": null }, { "code": null, "e": 37459, "s": 37451, "text": "Output:" }, { "code": null, "e": 37490, "s": 37459, "text": "Before clicking on the button:" }, { "code": null, "e": 37520, "s": 37490, "text": "After clicking on the button:" }, { "code": null, "e": 37536, "s": 37520, "text": "JavaScript-Misc" }, { "code": null, "e": 37547, "s": 37536, "text": "JavaScript" }, { "code": null, "e": 37564, "s": 37547, "text": "Web Technologies" }, { "code": null, "e": 37591, "s": 37564, "text": "Web technologies Questions" }, { "code": null, "e": 37689, "s": 37591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37729, "s": 37689, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37774, "s": 37729, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37835, "s": 37774, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37907, "s": 37835, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37959, "s": 37907, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 37999, "s": 37959, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 38032, "s": 37999, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38077, "s": 38032, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38120, "s": 38077, "text": "How to fetch data from an API in ReactJS ?" } ]
Datasets in Keras - GeeksforGeeks
17 Jul, 2020 Keras is a python library which is widely used for training deep learning models. One of the common problems in deep learning is finding the proper dataset for developing models. In this article, we will see the list of popular datasets which are already incorporated in the keras.datasets module. MNIST (Classification of 10 digits):This dataset is used to classify handwritten digits. It contains 60,000 images in the training set and 10,000 images in the test set. The size of each image is 28×28. from keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data() Returns: x_train, x_test: An unsigned integer(0-255) array of grayscale image data with shape (num_samples, 28, 28). y_train, y_test: An unsigned integer(0-255) array of digit labels (integers in range 0-9) with shape (num_samples,). This dataset can be used as a drop-in replacement for MNIST. It consists of 60,000 28×28 grayscale images of 10 fashion categories, along with a test set of 10,000 images. The class labels are: from keras.datasets import fashion_mnist(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() Returns: x_train, x_test: An unsigned integer(0-255) array of grayscale image data with shape (num_samples, 28, 28). y_train, y_test: An unsigned integer(0-255) array of digit labels (integers in range 0-9) with shape (num_samples,). This dataset contains 10 different categories of images which are widely used in image classification tasks. It consists of 50,000 32×32 color training images, labeled over 10 categories, and 10,000 test images. The dataset is divided into five training batches , each with 10000 images. The test batch contains exactly 1000 randomly-selected images from each class. The training batches contain the remaining images in random order, but some training batches may contain more images from one class than another. Between them, the training batches contain exactly 5000 images from each class. The classes are completely mutually exclusive. There is no overlap between automobiles and trucks. The class labels are: from keras.datasets import cifar10(x_train, y_train), (x_test, y_test) = cifar10.load_data() Returns: x_train, x_test: An unsigned integer(0-255) array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3) based on the image_data_format backend setting of either channels_first or channels_last respectively. The value “3” in the shape refers to the 3 RGB channels. y_train, y_test: An unsigned integer(0-255) array of category labels (integers in range 0-9) with shape (num_samples, 1). This dataset contains 10 different categories of images which are widely used in image classification tasks. It consists of 50,000 32×32 colour training images, labelled over 10 categories, and 10,000 test images. This dataset is just like the CIFAR-10, except it has 100 classes containing 600 images each. There are 500 training images and 100 testing images per class. The 100 classes in the CIFAR-100 are grouped into 20 superclasses. Each image comes with a “fine” label (the class to which it belongs) and a “coarse” label (the superclass to which it belongs). from keras.datasets import cifar100(x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode='fine') Returns: x_train, x_test: An unsigned integer(0-255) array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3) based on the image_data_format backend setting of either channels_first or channels_last respectively. The value “3” in the shape refers to the 3 RGB channels. y_train, y_test: An unsigned integer(0-255) array of category labels (integers in range 0-99) with shape (num_samples, 1). Arguments: label_mode: “fine” or “coarse”. This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University. This dataset contains 13 attributes of houses at different locations around the Boston suburbs in the late 1970s. Targets are the median values of the houses at a location (in k$). The training set contains data of 404 different households while the test set contains data of 102 different households from keras.datasets import boston_housing(x_train, y_train), (x_test, y_test) = boston_housing.load_data() Returns: x_train, x_test: A numpy array of values of different attributes with shape (num_samples, 13) . y_train, y_test: A numpy array of values of different attributes with shape (num_samples, ). Arguments: seed: Random seed for shuffling the data before computing the test split. test_split: fraction of the data to reserve as test set. This dataset is used for binary classification of reviews i.e, positive or negative. It consists of 25,000 movies reviews from IMDB, labeled by sentiment (positive/negative). These reviews have already been preprocessed, and each review is encoded as a sequence of word indexes (integers). These words are indexed by overall frequency of their presence in the dataset. For example, the integer “5” encodes the 5th most frequent word in the data. This allows for quick filtering operations such as considering only the top 5000 words as the model vocabulary etc.. from keras.datasets import imdb(x_train, y_train), (x_test, y_test) = imdb.load_data() Returns: x_train, x_test: list of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is num_words-1. If the maxlen argument was specified, the largest possible sequence length is maxlen. y_train, y_test: list of integer labels (1 for positive or 0 for negative). Arguments: num_words(int or None): Top most frequent words to consider. Any less frequent word will appear as “oov_char” value in the sequence data. skip_top(int): Top most frequent words to ignore (they will appear as oov_char value in the sequence data). maxlen(int): Maximum sequence length. Any longer sequence will be truncated. seed(int): Seed for reproducible data shuffling. start_char(int): The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character. oov_char(int): words that were cut out because of the num_words or skip_top limit will be replaced with this character. index_from(int): Index actual words with this index and higher. This dataset is used for multiclass text classification. It consists of 11,228 newswires from Reuters, labelled over 46 topics. Just like the IMDB dataset, each wire is encoded as a sequence of word indexes (same conventions). from keras.datasets import reuters(x_train, y_train), (x_test, y_test) = reuters.load_data() Returns: x_train, x_test: list of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is num_words-1. If the maxlen argument was specified, the largest possible sequence length is maxlen. y_train, y_test: list of integer labels (1 for positive or 0 for negative). Arguments: num_words(int or None): Top most frequent words to consider. Any less frequent word will appear as “oov_char” value in the sequence data. skip_top(int): Top most frequent words to ignore (they will appear as oov_char value in the sequence data). maxlen(int): Maximum sequence length. Any longer sequence will be truncated. seed(int): Seed for reproducible data shuffling. start_char(int): The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character. oov_char(int): words that were cut out because of the num_words or skip_top limit will be replaced with this character. index_from(int): Index actual words with this index and higher. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network Read JSON file using Python Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python
[ { "code": null, "e": 26269, "s": 26241, "text": "\n17 Jul, 2020" }, { "code": null, "e": 26567, "s": 26269, "text": "Keras is a python library which is widely used for training deep learning models. One of the common problems in deep learning is finding the proper dataset for developing models. In this article, we will see the list of popular datasets which are already incorporated in the keras.datasets module." }, { "code": null, "e": 26770, "s": 26567, "text": "MNIST (Classification of 10 digits):This dataset is used to classify handwritten digits. It contains 60,000 images in the training set and 10,000 images in the test set. The size of each image is 28×28." }, { "code": "from keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()", "e": 26859, "s": 26770, "text": null }, { "code": null, "e": 26868, "s": 26859, "text": "Returns:" }, { "code": null, "e": 26976, "s": 26868, "text": "x_train, x_test: An unsigned integer(0-255) array of grayscale image data with shape (num_samples, 28, 28)." }, { "code": null, "e": 27093, "s": 26976, "text": "y_train, y_test: An unsigned integer(0-255) array of digit labels (integers in range 0-9) with shape (num_samples,)." }, { "code": null, "e": 27287, "s": 27093, "text": "This dataset can be used as a drop-in replacement for MNIST. It consists of 60,000 28×28 grayscale images of 10 fashion categories, along with a test set of 10,000 images. The class labels are:" }, { "code": "from keras.datasets import fashion_mnist(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()", "e": 27392, "s": 27287, "text": null }, { "code": null, "e": 27401, "s": 27392, "text": "Returns:" }, { "code": null, "e": 27509, "s": 27401, "text": "x_train, x_test: An unsigned integer(0-255) array of grayscale image data with shape (num_samples, 28, 28)." }, { "code": null, "e": 27626, "s": 27509, "text": "y_train, y_test: An unsigned integer(0-255) array of digit labels (integers in range 0-9) with shape (num_samples,)." }, { "code": null, "e": 28340, "s": 27626, "text": "This dataset contains 10 different categories of images which are widely used in image classification tasks. It consists of 50,000 32×32 color training images, labeled over 10 categories, and 10,000 test images. The dataset is divided into five training batches , each with 10000 images. The test batch contains exactly 1000 randomly-selected images from each class. The training batches contain the remaining images in random order, but some training batches may contain more images from one class than another. Between them, the training batches contain exactly 5000 images from each class. The classes are completely mutually exclusive. There is no overlap between automobiles and trucks. The class labels are:" }, { "code": "from keras.datasets import cifar10(x_train, y_train), (x_test, y_test) = cifar10.load_data()", "e": 28433, "s": 28340, "text": null }, { "code": null, "e": 28442, "s": 28433, "text": "Returns:" }, { "code": null, "e": 28734, "s": 28442, "text": "x_train, x_test: An unsigned integer(0-255) array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3) based on the image_data_format backend setting of either channels_first or channels_last respectively. The value “3” in the shape refers to the 3 RGB channels." }, { "code": null, "e": 28856, "s": 28734, "text": "y_train, y_test: An unsigned integer(0-255) array of category labels (integers in range 0-9) with shape (num_samples, 1)." }, { "code": null, "e": 29423, "s": 28856, "text": "This dataset contains 10 different categories of images which are widely used in image classification tasks. It consists of 50,000 32×32 colour training images, labelled over 10 categories, and 10,000 test images. This dataset is just like the CIFAR-10, except it has 100 classes containing 600 images each. There are 500 training images and 100 testing images per class. The 100 classes in the CIFAR-100 are grouped into 20 superclasses. Each image comes with a “fine” label (the class to which it belongs) and a “coarse” label (the superclass to which it belongs)." }, { "code": "from keras.datasets import cifar100(x_train, y_train), (x_test, y_test) = cifar100.load_data(label_mode='fine')", "e": 29535, "s": 29423, "text": null }, { "code": null, "e": 29544, "s": 29535, "text": "Returns:" }, { "code": null, "e": 29836, "s": 29544, "text": "x_train, x_test: An unsigned integer(0-255) array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3) based on the image_data_format backend setting of either channels_first or channels_last respectively. The value “3” in the shape refers to the 3 RGB channels." }, { "code": null, "e": 29959, "s": 29836, "text": "y_train, y_test: An unsigned integer(0-255) array of category labels (integers in range 0-99) with shape (num_samples, 1)." }, { "code": null, "e": 29970, "s": 29959, "text": "Arguments:" }, { "code": null, "e": 30002, "s": 29970, "text": "label_mode: “fine” or “coarse”." }, { "code": null, "e": 30402, "s": 30002, "text": "This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University. This dataset contains 13 attributes of houses at different locations around the Boston suburbs in the late 1970s. Targets are the median values of the houses at a location (in k$). The training set contains data of 404 different households while the test set contains data of 102 different households" }, { "code": "from keras.datasets import boston_housing(x_train, y_train), (x_test, y_test) = boston_housing.load_data()", "e": 30509, "s": 30402, "text": null }, { "code": null, "e": 30518, "s": 30509, "text": "Returns:" }, { "code": null, "e": 30614, "s": 30518, "text": "x_train, x_test: A numpy array of values of different attributes with shape (num_samples, 13) ." }, { "code": null, "e": 30707, "s": 30614, "text": "y_train, y_test: A numpy array of values of different attributes with shape (num_samples, )." }, { "code": null, "e": 30718, "s": 30707, "text": "Arguments:" }, { "code": null, "e": 30792, "s": 30718, "text": "seed: Random seed for shuffling the data before computing the test split." }, { "code": null, "e": 30849, "s": 30792, "text": "test_split: fraction of the data to reserve as test set." }, { "code": null, "e": 31412, "s": 30849, "text": "This dataset is used for binary classification of reviews i.e, positive or negative. It consists of 25,000 movies reviews from IMDB, labeled by sentiment (positive/negative). These reviews have already been preprocessed, and each review is encoded as a sequence of word indexes (integers). These words are indexed by overall frequency of their presence in the dataset. For example, the integer “5” encodes the 5th most frequent word in the data. This allows for quick filtering operations such as considering only the top 5000 words as the model vocabulary etc.." }, { "code": "from keras.datasets import imdb(x_train, y_train), (x_test, y_test) = imdb.load_data()", "e": 31499, "s": 31412, "text": null }, { "code": null, "e": 31508, "s": 31499, "text": "Returns:" }, { "code": null, "e": 31758, "s": 31508, "text": "x_train, x_test: list of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is num_words-1. If the maxlen argument was specified, the largest possible sequence length is maxlen." }, { "code": null, "e": 31834, "s": 31758, "text": "y_train, y_test: list of integer labels (1 for positive or 0 for negative)." }, { "code": null, "e": 31845, "s": 31834, "text": "Arguments:" }, { "code": null, "e": 31983, "s": 31845, "text": "num_words(int or None): Top most frequent words to consider. Any less frequent word will appear as “oov_char” value in the sequence data." }, { "code": null, "e": 32091, "s": 31983, "text": "skip_top(int): Top most frequent words to ignore (they will appear as oov_char value in the sequence data)." }, { "code": null, "e": 32168, "s": 32091, "text": "maxlen(int): Maximum sequence length. Any longer sequence will be truncated." }, { "code": null, "e": 32217, "s": 32168, "text": "seed(int): Seed for reproducible data shuffling." }, { "code": null, "e": 32347, "s": 32217, "text": "start_char(int): The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character." }, { "code": null, "e": 32467, "s": 32347, "text": "oov_char(int): words that were cut out because of the num_words or skip_top limit will be replaced with this character." }, { "code": null, "e": 32531, "s": 32467, "text": "index_from(int): Index actual words with this index and higher." }, { "code": null, "e": 32758, "s": 32531, "text": "This dataset is used for multiclass text classification. It consists of 11,228 newswires from Reuters, labelled over 46 topics. Just like the IMDB dataset, each wire is encoded as a sequence of word indexes (same conventions)." }, { "code": "from keras.datasets import reuters(x_train, y_train), (x_test, y_test) = reuters.load_data()", "e": 32851, "s": 32758, "text": null }, { "code": null, "e": 32860, "s": 32851, "text": "Returns:" }, { "code": null, "e": 33110, "s": 32860, "text": "x_train, x_test: list of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is num_words-1. If the maxlen argument was specified, the largest possible sequence length is maxlen." }, { "code": null, "e": 33186, "s": 33110, "text": "y_train, y_test: list of integer labels (1 for positive or 0 for negative)." }, { "code": null, "e": 33197, "s": 33186, "text": "Arguments:" }, { "code": null, "e": 33335, "s": 33197, "text": "num_words(int or None): Top most frequent words to consider. Any less frequent word will appear as “oov_char” value in the sequence data." }, { "code": null, "e": 33443, "s": 33335, "text": "skip_top(int): Top most frequent words to ignore (they will appear as oov_char value in the sequence data)." }, { "code": null, "e": 33520, "s": 33443, "text": "maxlen(int): Maximum sequence length. Any longer sequence will be truncated." }, { "code": null, "e": 33569, "s": 33520, "text": "seed(int): Seed for reproducible data shuffling." }, { "code": null, "e": 33699, "s": 33569, "text": "start_char(int): The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character." }, { "code": null, "e": 33819, "s": 33699, "text": "oov_char(int): words that were cut out because of the num_words or skip_top limit will be replaced with this character." }, { "code": null, "e": 33883, "s": 33819, "text": "index_from(int): Index actual words with this index and higher." }, { "code": null, "e": 33900, "s": 33883, "text": "Machine Learning" }, { "code": null, "e": 33907, "s": 33900, "text": "Python" }, { "code": null, "e": 33924, "s": 33907, "text": "Machine Learning" }, { "code": null, "e": 34022, "s": 33924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34045, "s": 34022, "text": "ML | Linear Regression" }, { "code": null, "e": 34068, "s": 34045, "text": "Reinforcement learning" }, { "code": null, "e": 34108, "s": 34068, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 34148, "s": 34108, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 34189, "s": 34148, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 34217, "s": 34189, "text": "Read JSON file using Python" }, { "code": null, "e": 34239, "s": 34217, "text": "Python map() function" }, { "code": null, "e": 34283, "s": 34239, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 34301, "s": 34283, "text": "Python Dictionary" } ]
JavaFX | Popup Class - GeeksforGeeks
30 Aug, 2018 Popup class is a part of JavaFX. Popup class creates a popup with no content, a null fill and is transparent. Popup class is used to display a notification, buttons, or a drop-down menu and so forth. The popup has no decorations. It essentially acts as a specialized scene/window which has no decorations. Constructor of the class: Popup(): Creates an object of Popup class. Commonly Used Methods: Below programs illustrate the use of Popup class: Java program to create a popup and add it to the stage: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it and then display the popup if it is hidden and hide it if it is already visible. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java program to create a popup and // add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class Popup_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating popup"); // create a button Button button = new Button("button"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("This is a Popup"); // create a popup Popup popup = new Popup(); // set background label.setStyle(" -fx-background-color: white;"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); else popup.hide(); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_1.mp400:0000:0000:14Use Up/Down Arrow keys to increase or decrease volume.Java Program to create a popup and add it to the stage and make the popup hide automatically when it loses focus using the setAutoHide() function: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it, to display the popup if it is hidden. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The popup will automatically hide when it loses focus, we will apply this feature to the popup using the setAutoHide() function.The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java Program to create a popup and add// it to the stage and make the popup hide// automatically when it loses focus using// the setAutoHide() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class popup_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating Popup"); // create a button Button button = new Button("popup"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("This is a Popup"); // create a popup Popup popup = new Popup(); // set background label.setStyle(" -fx-background-color: white;"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // set auto hide popup.setAutoHide(true); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_2.mp400:0000:0000:22Use Up/Down Arrow keys to increase or decrease volume. Java program to create a popup and add it to the stage: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it and then display the popup if it is hidden and hide it if it is already visible. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java program to create a popup and // add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class Popup_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating popup"); // create a button Button button = new Button("button"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("This is a Popup"); // create a popup Popup popup = new Popup(); // set background label.setStyle(" -fx-background-color: white;"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); else popup.hide(); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_1.mp400:0000:0000:14Use Up/Down Arrow keys to increase or decrease volume. // Java program to create a popup and // add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class Popup_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating popup"); // create a button Button button = new Button("button"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("This is a Popup"); // create a popup Popup popup = new Popup(); // set background label.setStyle(" -fx-background-color: white;"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); else popup.hide(); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Java Program to create a popup and add it to the stage and make the popup hide automatically when it loses focus using the setAutoHide() function: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it, to display the popup if it is hidden. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The popup will automatically hide when it loses focus, we will apply this feature to the popup using the setAutoHide() function.The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java Program to create a popup and add// it to the stage and make the popup hide// automatically when it loses focus using// the setAutoHide() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class popup_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating Popup"); // create a button Button button = new Button("popup"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("This is a Popup"); // create a popup Popup popup = new Popup(); // set background label.setStyle(" -fx-background-color: white;"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // set auto hide popup.setAutoHide(true); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_2.mp400:0000:0000:22Use Up/Down Arrow keys to increase or decrease volume. // Java Program to create a popup and add// it to the stage and make the popup hide// automatically when it loses focus using// the setAutoHide() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class popup_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("Creating Popup"); // create a button Button button = new Button("popup"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label("This is a Popup"); // create a popup Popup popup = new Popup(); // set background label.setStyle(" -fx-background-color: white;"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // set auto hide popup.setAutoHide(true); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE. Please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/stage/Popup.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Stack Class in Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java LinkedList in Java
[ { "code": null, "e": 25335, "s": 25307, "text": "\n30 Aug, 2018" }, { "code": null, "e": 25641, "s": 25335, "text": "Popup class is a part of JavaFX. Popup class creates a popup with no content, a null fill and is transparent. Popup class is used to display a notification, buttons, or a drop-down menu and so forth. The popup has no decorations. It essentially acts as a specialized scene/window which has no decorations." }, { "code": null, "e": 25667, "s": 25641, "text": "Constructor of the class:" }, { "code": null, "e": 25710, "s": 25667, "text": "Popup(): Creates an object of Popup class." }, { "code": null, "e": 25733, "s": 25710, "text": "Commonly Used Methods:" }, { "code": null, "e": 25783, "s": 25733, "text": "Below programs illustrate the use of Popup class:" }, { "code": null, "e": 31306, "s": 25783, "text": "Java program to create a popup and add it to the stage: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it and then display the popup if it is hidden and hide it if it is already visible. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java program to create a popup and // add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class Popup_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating popup\"); // create a button Button button = new Button(\"button\"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"This is a Popup\"); // create a popup Popup popup = new Popup(); // set background label.setStyle(\" -fx-background-color: white;\"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); else popup.hide(); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_1.mp400:0000:0000:14Use Up/Down Arrow keys to increase or decrease volume.Java Program to create a popup and add it to the stage and make the popup hide automatically when it loses focus using the setAutoHide() function: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it, to display the popup if it is hidden. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The popup will automatically hide when it loses focus, we will apply this feature to the popup using the setAutoHide() function.The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java Program to create a popup and add// it to the stage and make the popup hide// automatically when it loses focus using// the setAutoHide() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class popup_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating Popup\"); // create a button Button button = new Button(\"popup\"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"This is a Popup\"); // create a popup Popup popup = new Popup(); // set background label.setStyle(\" -fx-background-color: white;\"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // set auto hide popup.setAutoHide(true); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_2.mp400:0000:0000:22Use Up/Down Arrow keys to increase or decrease volume." }, { "code": null, "e": 33941, "s": 31306, "text": "Java program to create a popup and add it to the stage: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it and then display the popup if it is hidden and hide it if it is already visible. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java program to create a popup and // add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class Popup_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating popup\"); // create a button Button button = new Button(\"button\"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"This is a Popup\"); // create a popup Popup popup = new Popup(); // set background label.setStyle(\" -fx-background-color: white;\"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); else popup.hide(); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_1.mp400:0000:0000:14Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "// Java program to create a popup and // add it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class Popup_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating popup\"); // create a button Button button = new Button(\"button\"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"This is a Popup\"); // create a popup Popup popup = new Popup(); // set background label.setStyle(\" -fx-background-color: white;\"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); else popup.hide(); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 35763, "s": 33941, "text": null }, { "code": null, "e": 35771, "s": 35763, "text": "Output:" }, { "code": null, "e": 38660, "s": 35771, "text": "Java Program to create a popup and add it to the stage and make the popup hide automatically when it loses focus using the setAutoHide() function: In this program we create a Popup named popup. The popup contains a Label named label. We also create a Button named button and add event handler to it, to display the popup if it is hidden. The button is added to the TilePane and the TilePane is added to the scene, and the scene is added to the stage. The show function is called to display the results. The popup will automatically hide when it loses focus, we will apply this feature to the popup using the setAutoHide() function.The background color of the label is set using the setStyle() function, and the label size is set using setMinHeight(), setMinWidth() function. The hide() and show() function is used to hide or show the popup.// Java Program to create a popup and add// it to the stage and make the popup hide// automatically when it loses focus using// the setAutoHide() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class popup_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating Popup\"); // create a button Button button = new Button(\"popup\"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"This is a Popup\"); // create a popup Popup popup = new Popup(); // set background label.setStyle(\" -fx-background-color: white;\"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // set auto hide popup.setAutoHide(true); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/Popup_2.mp400:0000:0000:22Use Up/Down Arrow keys to increase or decrease volume." }, { "code": "// Java Program to create a popup and add// it to the stage and make the popup hide// automatically when it loses focus using// the setAutoHide() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.control.Label;import javafx.stage.Stage;import javafx.stage.Popup; public class popup_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"Creating Popup\"); // create a button Button button = new Button(\"popup\"); // create a tile pane TilePane tilepane = new TilePane(); // create a label Label label = new Label(\"This is a Popup\"); // create a popup Popup popup = new Popup(); // set background label.setStyle(\" -fx-background-color: white;\"); // add the label popup.getContent().add(label); // set size of label label.setMinWidth(80); label.setMinHeight(50); // set auto hide popup.setAutoHide(true); // action event EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if (!popup.isShowing()) popup.show(stage); } }; // when button is pressed button.setOnAction(event); // add button tilepane.getChildren().add(button); // create a scene Scene scene = new Scene(tilepane, 200, 200); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 40559, "s": 38660, "text": null }, { "code": null, "e": 40567, "s": 40559, "text": "Output:" }, { "code": null, "e": 40656, "s": 40567, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler." }, { "code": null, "e": 40735, "s": 40656, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/stage/Popup.html" }, { "code": null, "e": 40742, "s": 40735, "text": "JavaFX" }, { "code": null, "e": 40747, "s": 40742, "text": "Java" }, { "code": null, "e": 40752, "s": 40747, "text": "Java" }, { "code": null, "e": 40850, "s": 40752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40869, "s": 40850, "text": "Interfaces in Java" }, { "code": null, "e": 40884, "s": 40869, "text": "Stream In Java" }, { "code": null, "e": 40902, "s": 40884, "text": "ArrayList in Java" }, { "code": null, "e": 40922, "s": 40902, "text": "Stack Class in Java" }, { "code": null, "e": 40946, "s": 40922, "text": "Singleton Class in Java" }, { "code": null, "e": 40958, "s": 40946, "text": "Set in Java" }, { "code": null, "e": 40981, "s": 40958, "text": "Multithreading in Java" }, { "code": null, "e": 41001, "s": 40981, "text": "Collections in Java" }, { "code": null, "e": 41025, "s": 41001, "text": "Queue Interface In Java" } ]
GATE | GATE-CS-2004 | Question 32 - GeeksforGeeks
28 Jun, 2021 Consider the following program fragment for reversing the digits in a given integer to obtain a new integer. Let n = D1D2...Dm int n, rev;rev = 0;while (n > 0){ rev = rev*10 + n%10; n = n/10;} The loop invariant condition at the end of the ith iteration is:(A) n = D1D2....Dm-i and rev = DmDm-1...Dm-i+1(B) n = Dm-i+1...Dm-1Dm and rev = Dm-1....D2D1(C) n != rev(D) n = D1D2....Dm and rev = DmDm-1...D2D1Answer: (A)Explanation: The loop one by adds digits to rev starting from the last digit of n. It also removes digits from n starting from left.Quiz of this Question GATE-CS-2004 GATE-GATE-CS-2004 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-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 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": 25721, "s": 25693, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25848, "s": 25721, "text": "Consider the following program fragment for reversing the digits in a given integer to obtain a new integer. Let n = D1D2...Dm" }, { "code": "int n, rev;rev = 0;while (n > 0){ rev = rev*10 + n%10; n = n/10;}", "e": 25918, "s": 25848, "text": null }, { "code": null, "e": 26293, "s": 25918, "text": "The loop invariant condition at the end of the ith iteration is:(A) n = D1D2....Dm-i and rev = DmDm-1...Dm-i+1(B) n = Dm-i+1...Dm-1Dm and rev = Dm-1....D2D1(C) n != rev(D) n = D1D2....Dm and rev = DmDm-1...D2D1Answer: (A)Explanation: The loop one by adds digits to rev starting from the last digit of n. It also removes digits from n starting from left.Quiz of this Question" }, { "code": null, "e": 26306, "s": 26293, "text": "GATE-CS-2004" }, { "code": null, "e": 26324, "s": 26306, "text": "GATE-GATE-CS-2004" }, { "code": null, "e": 26329, "s": 26324, "text": "GATE" }, { "code": null, "e": 26427, "s": 26329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26461, "s": 26427, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26495, "s": 26461, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26529, "s": 26495, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26562, "s": 26529, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26598, "s": 26562, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26632, "s": 26598, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26668, "s": 26632, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26702, "s": 26668, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26736, "s": 26702, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Java | Packages | Question 1 - GeeksforGeeks
28 Jun, 2021 Which of the following is/are true about packages in Java? 1) Every class is part of some package. 2) All classes in a file are part of the same package. 3) If no package is specified, the classes in the file go into a special unnamed package 4) If no package is specified, a new package is created with folder name of class and the class is put in this package. (A) Only 1, 2 and 3(B) Only 1, 2 and 4(C) Only 4(D) Only 1 and 3Answer: (A)Explanation: In Java, a package can be considered as equivalent to C++ language’s namespace.Quiz of this Question Java-Java Packages Java-Packages Java Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Constructors | Question 3 Java | Constructors | Question 5 Java | Exception Handling | Question 2 Java | final keyword | Question 1 Java | Class and Object | Question 1 Java | Abstract Class and Interface | Question 2 Java | Functions | Question 1 Java | Exception Handling | Question 3 Java | Exception Handling | Question 4 Java | Exception Handling | Question 7
[ { "code": null, "e": 25431, "s": 25403, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25490, "s": 25431, "text": "Which of the following is/are true about packages in Java?" }, { "code": null, "e": 25806, "s": 25490, "text": "1) Every class is part of some package. \n2) All classes in a file are part of the same package. \n3) If no package is specified, the classes in the file \n go into a special unnamed package \n4) If no package is specified, a new package is created with \n folder name of class and the class is put in this package. " }, { "code": null, "e": 25995, "s": 25806, "text": "(A) Only 1, 2 and 3(B) Only 1, 2 and 4(C) Only 4(D) Only 1 and 3Answer: (A)Explanation: In Java, a package can be considered as equivalent to C++ language’s namespace.Quiz of this Question" }, { "code": null, "e": 26014, "s": 25995, "text": "Java-Java Packages" }, { "code": null, "e": 26028, "s": 26014, "text": "Java-Packages" }, { "code": null, "e": 26038, "s": 26028, "text": "Java Quiz" }, { "code": null, "e": 26136, "s": 26038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26169, "s": 26136, "text": "Java | Constructors | Question 3" }, { "code": null, "e": 26202, "s": 26169, "text": "Java | Constructors | Question 5" }, { "code": null, "e": 26241, "s": 26202, "text": "Java | Exception Handling | Question 2" }, { "code": null, "e": 26275, "s": 26241, "text": "Java | final keyword | Question 1" }, { "code": null, "e": 26312, "s": 26275, "text": "Java | Class and Object | Question 1" }, { "code": null, "e": 26361, "s": 26312, "text": "Java | Abstract Class and Interface | Question 2" }, { "code": null, "e": 26391, "s": 26361, "text": "Java | Functions | Question 1" }, { "code": null, "e": 26430, "s": 26391, "text": "Java | Exception Handling | Question 3" }, { "code": null, "e": 26469, "s": 26430, "text": "Java | Exception Handling | Question 4" } ]
Kubernetes - Images
Kubernetes (Docker) images are the key building blocks of Containerized Infrastructure. As of now, we are only supporting Kubernetes to support Docker images. Each container in a pod has its Docker image running inside it. When we are configuring a pod, the image property in the configuration file has the same syntax as the Docker command does. The configuration file has a field to define the image name, which we are planning to pull from the registry. Following is the common configuration structure which will pull image from Docker registry and deploy in to Kubernetes container. apiVersion: v1 kind: pod metadata: name: Tesing_for_Image_pull -----------> 1 spec: containers: - name: neo4j-server ------------------------> 2 image: <Name of the Docker image>----------> 3 imagePullPolicy: Always ------------->4 command: ["echo", "SUCCESS"] -------------------> In the above code, we have defined − name: Tesing_for_Image_pull − This name is given to identify and check what is the name of the container that would get created after pulling the images from Docker registry. name: Tesing_for_Image_pull − This name is given to identify and check what is the name of the container that would get created after pulling the images from Docker registry. name: neo4j-server − This is the name given to the container that we are trying to create. Like we have given neo4j-server. name: neo4j-server − This is the name given to the container that we are trying to create. Like we have given neo4j-server. image: <Name of the Docker image> − This is the name of the image which we are trying to pull from the Docker or internal registry of images. We need to define a complete registry path along with the image name that we are trying to pull. image: <Name of the Docker image> − This is the name of the image which we are trying to pull from the Docker or internal registry of images. We need to define a complete registry path along with the image name that we are trying to pull. imagePullPolicy − Always - This image pull policy defines that whenever we run this file to create the container, it will pull the same name again. imagePullPolicy − Always - This image pull policy defines that whenever we run this file to create the container, it will pull the same name again. command: [“echo”, “SUCCESS”] − With this, when we create the container and if everything goes fine, it will display a message when we will access the container. command: [“echo”, “SUCCESS”] − With this, when we create the container and if everything goes fine, it will display a message when we will access the container. In order to pull the image and create a container, we will run the following command. $ kubectl create –f Tesing_for_Image_pull Once we fetch the log, we will get the output as successful. $ kubectl log Tesing_for_Image_pull The above command will produce an output of success or we will get an output as failure. Note − It is recommended that you try all the commands yourself. 41 Lectures 5 hours AR Shankar 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Nigel Poulton 25 Lectures 1.5 hours Pranjal Srivastava 18 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2418, "s": 2195, "text": "Kubernetes (Docker) images are the key building blocks of Containerized Infrastructure. As of now, we are only supporting Kubernetes to support Docker images. Each container in a pod has its Docker image running inside it." }, { "code": null, "e": 2652, "s": 2418, "text": "When we are configuring a pod, the image property in the configuration file has the same syntax as the Docker command does. The configuration file has a field to define the image name, which we are planning to pull from the registry." }, { "code": null, "e": 2782, "s": 2652, "text": "Following is the common configuration structure which will pull image from Docker registry and deploy in to Kubernetes container." }, { "code": null, "e": 3113, "s": 2782, "text": "apiVersion: v1\nkind: pod\nmetadata:\n name: Tesing_for_Image_pull -----------> 1\n spec:\n containers:\n - name: neo4j-server ------------------------> 2\n image: <Name of the Docker image>----------> 3\n imagePullPolicy: Always ------------->4\n command: [\"echo\", \"SUCCESS\"] ------------------->\n" }, { "code": null, "e": 3150, "s": 3113, "text": "In the above code, we have defined −" }, { "code": null, "e": 3325, "s": 3150, "text": "name: Tesing_for_Image_pull − This name is given to identify and check what is the name of the container that would get created after pulling the images from Docker registry." }, { "code": null, "e": 3500, "s": 3325, "text": "name: Tesing_for_Image_pull − This name is given to identify and check what is the name of the container that would get created after pulling the images from Docker registry." }, { "code": null, "e": 3624, "s": 3500, "text": "name: neo4j-server − This is the name given to the container that we are trying to create. Like we have given neo4j-server." }, { "code": null, "e": 3748, "s": 3624, "text": "name: neo4j-server − This is the name given to the container that we are trying to create. Like we have given neo4j-server." }, { "code": null, "e": 3987, "s": 3748, "text": "image: <Name of the Docker image> − This is the name of the image which we are trying to pull from the Docker or internal registry of images. We need to define a complete registry path along with the image name that we are trying to pull." }, { "code": null, "e": 4226, "s": 3987, "text": "image: <Name of the Docker image> − This is the name of the image which we are trying to pull from the Docker or internal registry of images. We need to define a complete registry path along with the image name that we are trying to pull." }, { "code": null, "e": 4374, "s": 4226, "text": "imagePullPolicy − Always - This image pull policy defines that whenever we run this file to create the container, it will pull the same name again." }, { "code": null, "e": 4522, "s": 4374, "text": "imagePullPolicy − Always - This image pull policy defines that whenever we run this file to create the container, it will pull the same name again." }, { "code": null, "e": 4683, "s": 4522, "text": "command: [“echo”, “SUCCESS”] − With this, when we create the container and if everything goes fine, it will display a message when we will access the container." }, { "code": null, "e": 4844, "s": 4683, "text": "command: [“echo”, “SUCCESS”] − With this, when we create the container and if everything goes fine, it will display a message when we will access the container." }, { "code": null, "e": 4930, "s": 4844, "text": "In order to pull the image and create a container, we will run the following command." }, { "code": null, "e": 4973, "s": 4930, "text": "$ kubectl create –f Tesing_for_Image_pull\n" }, { "code": null, "e": 5034, "s": 4973, "text": "Once we fetch the log, we will get the output as successful." }, { "code": null, "e": 5071, "s": 5034, "text": "$ kubectl log Tesing_for_Image_pull\n" }, { "code": null, "e": 5160, "s": 5071, "text": "The above command will produce an output of success or we will get an output as failure." }, { "code": null, "e": 5225, "s": 5160, "text": "Note − It is recommended that you try all the commands yourself." }, { "code": null, "e": 5258, "s": 5225, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 5270, "s": 5258, "text": " AR Shankar" }, { "code": null, "e": 5303, "s": 5270, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 5343, "s": 5303, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 5378, "s": 5343, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5393, "s": 5378, "text": " Nigel Poulton" }, { "code": null, "e": 5428, "s": 5393, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5448, "s": 5428, "text": " Pranjal Srivastava" }, { "code": null, "e": 5481, "s": 5448, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 5501, "s": 5481, "text": " Pranjal Srivastava" }, { "code": null, "e": 5536, "s": 5501, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5556, "s": 5536, "text": " Pranjal Srivastava" }, { "code": null, "e": 5563, "s": 5556, "text": " Print" }, { "code": null, "e": 5574, "s": 5563, "text": " Add Notes" } ]
AWT Color Class
The Color class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace. Following is the declaration for java.awt.Color class: public class Color extends Object implements Paint, Serializable Following are the fields for java.awt.geom.Arc2D class: static Color black -- The color black. static Color black -- The color black. static Color BLACK -- The color black. static Color BLACK -- The color black. static Color blue -- The color blue. static Color blue -- The color blue. static Color BLUE -- The color blue. static Color BLUE -- The color blue. static Color cyan -- The color cyan. static Color cyan -- The color cyan. static Color CYAN -- The color cyan. static Color CYAN -- The color cyan. static Color DARK_GRAY -- The color dark gray. static Color DARK_GRAY -- The color dark gray. static Color darkGray -- The color dark gray. static Color darkGray -- The color dark gray. static Color gray -- The color gray. static Color gray -- The color gray. static Color GRAY -- The color gray. static Color GRAY -- The color gray. static Color green -- The color green. static Color green -- The color green. static Color GREEN -- The color green. static Color GREEN -- The color green. static Color LIGHT_GRAY -- The color light gray. static Color LIGHT_GRAY -- The color light gray. static Color lightGray -- The color light gray. static Color lightGray -- The color light gray. static Color magenta -- The color magenta. static Color magenta -- The color magenta. static Color MAGENTA -- The color magenta. static Color MAGENTA -- The color magenta. static Color orange -- The color orange. static Color orange -- The color orange. static Color ORANGE -- The color orange. static Color ORANGE -- The color orange. static Color pink -- The color pink. static Color pink -- The color pink. static Color PINK -- The color pink. static Color PINK -- The color pink. static Color red -- The color red. static Color red -- The color red. static Color RED -- The color red. static Color RED -- The color red. static Color white -- The color white. static Color white -- The color white. static Color WHITE -- The color white. static Color WHITE -- The color white. static Color yellow -- The color yellow. static Color yellow -- The color yellow. static Color YELLOW -- The color yellow. static Color YELLOW -- The color yellow. Color(ColorSpace cspace, float[] components, float alpha) Creates a color in the specified ColorSpace with the color components specified in the float array and the specified alpha. Color(float r, float g, float b) Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 - 1.0). Color(float r, float g, float b, float a) Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0.0 - 1.0). Color(int rgb) Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7. Color(int rgba, boolean hasalpha) Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7. Color(int r, int g, int b) Creates an opaque sRGB color with the specified red, green, and blue values in the range (0 - 255). Color(int r, int g, int b, int a) Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0 - 255). Color brighter() Creates a new Color that is a brighter version of this Color. PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform, RenderingHints hints) Creates and returns a PaintContext used to generate a solid color pattern. Color darker() Creates a new Color that is a darker version of this Color. static Color decode(String nm) Converts a String to an integer and returns the specified opaque Color. boolean equals(Object obj) Determines whether another object is equal to this Color. int getAlpha() Returns the alpha component in the range 0-255. int getBlue() Returns the blue component in the range 0-255 in the default sRGB space. static Color getColor(String nm) Finds a color in the system properties. static Color getColor(String nm, Color v) Finds a color in the system properties. static Color getColor(String nm, int v) Finds a color in the system properties. float[] getColorComponents(ColorSpace cspace, float[] compArray) Returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter. float[] getColorComponents(float[] compArray) Returns a float array containing only the color components of the Color, in the ColorSpace of the Color. ColorSpace getColorSpace() Returns the ColorSpace of this Color. float[] getComponents(ColorSpace cspace, float[] compArray) Returns a float array containing the color and alpha components of the Color, in the ColorSpace specified by the cspace parameter. float[] getComponents(float[] compArray) Returns a float array containing the color and alpha components of the Color, in the ColorSpace of the Color. int getGreen() Returns the green component in the range 0-255 in the default sRGB space. static Color getHSBColor(float h, float s, float b) Creates a Color object based on the specified values for the HSB color model. int getRed() Returns the red component in the range 0-255 in the default sRGB space. int getRGB() Returns the RGB value representing the color in the default sRGB ColorModel. float[] getRGBColorComponents(float[] compArray) Returns a float array containing only the color components of the Color, in the default sRGB color space. float[] getRGBComponents(float[] compArray) Returns a float array containing the color and alpha components of the Color, as represented in the default sRGB color space. int getTransparency() Returns the transparency mode for this Color. int hashCode() Computes the hash code for this Color. static int HSBtoRGB(float hue, float saturation, float brightness) Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model. static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) Converts the components of a color, as specified by the default RGB model, to an equivalent set of values for hue, saturation, and brightness that are the three components of the HSB model. String toString() Returns a string representation of this Color. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class AWTGraphicsDemo extends Frame { public AWTGraphicsDemo(){ super("Java AWT Examples"); prepareGUI(); } public static void main(String[] args){ AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); awtGraphicsDemo.setVisible(true); } private void prepareGUI(){ setSize(400,400); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); } @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; Font plainFont = new Font("Serif", Font.PLAIN, 24); g2.setFont(plainFont); g2.setColor(Color.red); g2.drawString("Welcome to TutorialsPoint", 50, 70); g2.setColor(Color.GRAY); g2.drawString("Welcome to TutorialsPoint", 50, 120); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1873, "s": 1747, "text": "The Color class states colors in the default sRGB color space or colors in arbitrary color spaces identified by a ColorSpace." }, { "code": null, "e": 1928, "s": 1873, "text": "Following is the declaration for java.awt.Color class:" }, { "code": null, "e": 2002, "s": 1928, "text": "public class Color\n extends Object\n implements Paint, Serializable" }, { "code": null, "e": 2058, "s": 2002, "text": "Following are the fields for java.awt.geom.Arc2D class:" }, { "code": null, "e": 2098, "s": 2058, "text": "static Color black -- The color black." }, { "code": null, "e": 2138, "s": 2098, "text": "static Color black -- The color black." }, { "code": null, "e": 2178, "s": 2138, "text": "static Color BLACK -- The color black." }, { "code": null, "e": 2218, "s": 2178, "text": "static Color BLACK -- The color black." }, { "code": null, "e": 2256, "s": 2218, "text": "static Color blue -- The color blue." }, { "code": null, "e": 2294, "s": 2256, "text": "static Color blue -- The color blue." }, { "code": null, "e": 2332, "s": 2294, "text": "static Color BLUE -- The color blue." }, { "code": null, "e": 2370, "s": 2332, "text": "static Color BLUE -- The color blue." }, { "code": null, "e": 2408, "s": 2370, "text": "static Color cyan -- The color cyan." }, { "code": null, "e": 2446, "s": 2408, "text": "static Color cyan -- The color cyan." }, { "code": null, "e": 2484, "s": 2446, "text": "static Color CYAN -- The color cyan." }, { "code": null, "e": 2522, "s": 2484, "text": "static Color CYAN -- The color cyan." }, { "code": null, "e": 2569, "s": 2522, "text": "static Color DARK_GRAY -- The color dark gray." }, { "code": null, "e": 2616, "s": 2569, "text": "static Color DARK_GRAY -- The color dark gray." }, { "code": null, "e": 2663, "s": 2616, "text": "static Color darkGray -- The color dark gray." }, { "code": null, "e": 2710, "s": 2663, "text": "static Color darkGray -- The color dark gray." }, { "code": null, "e": 2748, "s": 2710, "text": "static Color gray -- The color gray." }, { "code": null, "e": 2786, "s": 2748, "text": "static Color gray -- The color gray." }, { "code": null, "e": 2824, "s": 2786, "text": "static Color GRAY -- The color gray." }, { "code": null, "e": 2862, "s": 2824, "text": "static Color GRAY -- The color gray." }, { "code": null, "e": 2902, "s": 2862, "text": "static Color green -- The color green." }, { "code": null, "e": 2942, "s": 2902, "text": "static Color green -- The color green." }, { "code": null, "e": 2982, "s": 2942, "text": "static Color GREEN -- The color green." }, { "code": null, "e": 3022, "s": 2982, "text": "static Color GREEN -- The color green." }, { "code": null, "e": 3072, "s": 3022, "text": "static Color LIGHT_GRAY -- The color light gray." }, { "code": null, "e": 3122, "s": 3072, "text": "static Color LIGHT_GRAY -- The color light gray." }, { "code": null, "e": 3171, "s": 3122, "text": "static Color lightGray -- The color light gray." }, { "code": null, "e": 3220, "s": 3171, "text": "static Color lightGray -- The color light gray." }, { "code": null, "e": 3264, "s": 3220, "text": "static Color magenta -- The color magenta." }, { "code": null, "e": 3308, "s": 3264, "text": "static Color magenta -- The color magenta." }, { "code": null, "e": 3352, "s": 3308, "text": "static Color MAGENTA -- The color magenta." }, { "code": null, "e": 3396, "s": 3352, "text": "static Color MAGENTA -- The color magenta." }, { "code": null, "e": 3438, "s": 3396, "text": "static Color orange -- The color orange." }, { "code": null, "e": 3480, "s": 3438, "text": "static Color orange -- The color orange." }, { "code": null, "e": 3522, "s": 3480, "text": "static Color ORANGE -- The color orange." }, { "code": null, "e": 3564, "s": 3522, "text": "static Color ORANGE -- The color orange." }, { "code": null, "e": 3602, "s": 3564, "text": "static Color pink -- The color pink." }, { "code": null, "e": 3640, "s": 3602, "text": "static Color pink -- The color pink." }, { "code": null, "e": 3678, "s": 3640, "text": "static Color PINK -- The color pink." }, { "code": null, "e": 3716, "s": 3678, "text": "static Color PINK -- The color pink." }, { "code": null, "e": 3752, "s": 3716, "text": "static Color red -- The color red." }, { "code": null, "e": 3788, "s": 3752, "text": "static Color red -- The color red." }, { "code": null, "e": 3824, "s": 3788, "text": "static Color RED -- The color red." }, { "code": null, "e": 3860, "s": 3824, "text": "static Color RED -- The color red." }, { "code": null, "e": 3900, "s": 3860, "text": "static Color white -- The color white." }, { "code": null, "e": 3940, "s": 3900, "text": "static Color white -- The color white." }, { "code": null, "e": 3980, "s": 3940, "text": "static Color WHITE -- The color white." }, { "code": null, "e": 4020, "s": 3980, "text": "static Color WHITE -- The color white." }, { "code": null, "e": 4062, "s": 4020, "text": "static Color yellow -- The color yellow." }, { "code": null, "e": 4104, "s": 4062, "text": "static Color yellow -- The color yellow." }, { "code": null, "e": 4146, "s": 4104, "text": "static Color YELLOW -- The color yellow." }, { "code": null, "e": 4188, "s": 4146, "text": "static Color YELLOW -- The color yellow." }, { "code": null, "e": 4248, "s": 4188, "text": "Color(ColorSpace cspace, float[] components, float alpha) " }, { "code": null, "e": 4372, "s": 4248, "text": "Creates a color in the specified ColorSpace with the color components specified in the float array and the specified alpha." }, { "code": null, "e": 4407, "s": 4372, "text": "Color(float r, float g, float b) " }, { "code": null, "e": 4509, "s": 4407, "text": "Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 - 1.0)." }, { "code": null, "e": 4553, "s": 4509, "text": "Color(float r, float g, float b, float a) " }, { "code": null, "e": 4655, "s": 4553, "text": "Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0.0 - 1.0)." }, { "code": null, "e": 4670, "s": 4655, "text": "Color(int rgb)" }, { "code": null, "e": 4854, "s": 4670, "text": "Creates an opaque sRGB color with the specified combined RGB value consisting of the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7." }, { "code": null, "e": 4890, "s": 4854, "text": "Color(int rgba, boolean hasalpha) " }, { "code": null, "e": 5103, "s": 4890, "text": "Creates an sRGB color with the specified combined RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green component in bits 8-15, and the blue component in bits 0-7." }, { "code": null, "e": 5132, "s": 5103, "text": "Color(int r, int g, int b) " }, { "code": null, "e": 5232, "s": 5132, "text": "Creates an opaque sRGB color with the specified red, green, and blue values in the range (0 - 255)." }, { "code": null, "e": 5268, "s": 5232, "text": "Color(int r, int g, int b, int a) " }, { "code": null, "e": 5368, "s": 5268, "text": "Creates an sRGB color with the specified red, green, blue, and alpha values in the range (0 - 255)." }, { "code": null, "e": 5385, "s": 5368, "text": "Color brighter()" }, { "code": null, "e": 5447, "s": 5385, "text": "Creates a new Color that is a brighter version of this Color." }, { "code": null, "e": 5565, "s": 5447, "text": "PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform, RenderingHints hints) " }, { "code": null, "e": 5640, "s": 5565, "text": "Creates and returns a PaintContext used to generate a solid color pattern." }, { "code": null, "e": 5657, "s": 5640, "text": "Color darker() " }, { "code": null, "e": 5717, "s": 5657, "text": "Creates a new Color that is a darker version of this Color." }, { "code": null, "e": 5750, "s": 5717, "text": "static Color decode(String nm) " }, { "code": null, "e": 5822, "s": 5750, "text": "Converts a String to an integer and returns the specified opaque Color." }, { "code": null, "e": 5851, "s": 5822, "text": "boolean equals(Object obj) " }, { "code": null, "e": 5909, "s": 5851, "text": "Determines whether another object is equal to this Color." }, { "code": null, "e": 5926, "s": 5909, "text": "int getAlpha() " }, { "code": null, "e": 5974, "s": 5926, "text": "Returns the alpha component in the range 0-255." }, { "code": null, "e": 5990, "s": 5974, "text": "int getBlue() " }, { "code": null, "e": 6063, "s": 5990, "text": "Returns the blue component in the range 0-255 in the default sRGB space." }, { "code": null, "e": 6096, "s": 6063, "text": "static Color getColor(String nm)" }, { "code": null, "e": 6136, "s": 6096, "text": "Finds a color in the system properties." }, { "code": null, "e": 6178, "s": 6136, "text": "static Color getColor(String nm, Color v)" }, { "code": null, "e": 6218, "s": 6178, "text": "Finds a color in the system properties." }, { "code": null, "e": 6258, "s": 6218, "text": "static Color getColor(String nm, int v)" }, { "code": null, "e": 6298, "s": 6258, "text": "Finds a color in the system properties." }, { "code": null, "e": 6363, "s": 6298, "text": "float[] getColorComponents(ColorSpace cspace, float[] compArray)" }, { "code": null, "e": 6488, "s": 6363, "text": "Returns a float array containing only the color components of the Color in the ColorSpace specified by the cspace parameter." }, { "code": null, "e": 6536, "s": 6488, "text": "float[] getColorComponents(float[] compArray) " }, { "code": null, "e": 6641, "s": 6536, "text": "Returns a float array containing only the color components of the Color, in the ColorSpace of the Color." }, { "code": null, "e": 6670, "s": 6641, "text": "ColorSpace\tgetColorSpace() " }, { "code": null, "e": 6708, "s": 6670, "text": "Returns the ColorSpace of this Color." }, { "code": null, "e": 6770, "s": 6708, "text": "float[] getComponents(ColorSpace cspace, float[] compArray) " }, { "code": null, "e": 6901, "s": 6770, "text": "Returns a float array containing the color and alpha components of the Color, in the ColorSpace specified by the cspace parameter." }, { "code": null, "e": 6944, "s": 6901, "text": "float[] getComponents(float[] compArray) " }, { "code": null, "e": 7054, "s": 6944, "text": "Returns a float array containing the color and alpha components of the Color, in the ColorSpace of the Color." }, { "code": null, "e": 7071, "s": 7054, "text": "int\tgetGreen() " }, { "code": null, "e": 7145, "s": 7071, "text": "Returns the green component in the range 0-255 in the default sRGB space." }, { "code": null, "e": 7199, "s": 7145, "text": "static Color getHSBColor(float h, float s, float b) " }, { "code": null, "e": 7277, "s": 7199, "text": "Creates a Color object based on the specified values for the HSB color model." }, { "code": null, "e": 7292, "s": 7277, "text": "int getRed() " }, { "code": null, "e": 7364, "s": 7292, "text": "Returns the red component in the range 0-255 in the default sRGB space." }, { "code": null, "e": 7379, "s": 7364, "text": "int getRGB() " }, { "code": null, "e": 7456, "s": 7379, "text": "Returns the RGB value representing the color in the default sRGB ColorModel." }, { "code": null, "e": 7507, "s": 7456, "text": "float[] getRGBColorComponents(float[] compArray) " }, { "code": null, "e": 7613, "s": 7507, "text": "Returns a float array containing only the color components of the Color, in the default sRGB color space." }, { "code": null, "e": 7659, "s": 7613, "text": "float[] getRGBComponents(float[] compArray) " }, { "code": null, "e": 7785, "s": 7659, "text": "Returns a float array containing the color and alpha components of the Color, as represented in the default sRGB color space." }, { "code": null, "e": 7809, "s": 7785, "text": "int getTransparency() " }, { "code": null, "e": 7855, "s": 7809, "text": "Returns the transparency mode for this Color." }, { "code": null, "e": 7872, "s": 7855, "text": "int hashCode() " }, { "code": null, "e": 7911, "s": 7872, "text": "Computes the hash code for this Color." }, { "code": null, "e": 7979, "s": 7911, "text": "static int HSBtoRGB(float hue, float saturation, float brightness) " }, { "code": null, "e": 8104, "s": 7979, "text": "Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model." }, { "code": null, "e": 8168, "s": 8104, "text": "static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) " }, { "code": null, "e": 8358, "s": 8168, "text": "Converts the components of a color, as specified by the default RGB model, to an equivalent set of values for hue, saturation, and brightness that are the three components of the HSB model." }, { "code": null, "e": 8378, "s": 8358, "text": "String toString() " }, { "code": null, "e": 8425, "s": 8378, "text": "Returns a string representation of this Color." }, { "code": null, "e": 8481, "s": 8425, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 8498, "s": 8481, "text": "java.lang.Object" }, { "code": null, "e": 8515, "s": 8498, "text": "java.lang.Object" }, { "code": null, "e": 8629, "s": 8515, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 9633, "s": 8629, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\n\npublic class AWTGraphicsDemo extends Frame {\n \n public AWTGraphicsDemo(){\n super(\"Java AWT Examples\");\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); \n awtGraphicsDemo.setVisible(true);\n }\n\n private void prepareGUI(){\n setSize(400,400);\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n } \n\n @Override\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D)g; \n Font plainFont = new Font(\"Serif\", Font.PLAIN, 24); \n g2.setFont(plainFont);\n g2.setColor(Color.red);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 70); \n g2.setColor(Color.GRAY);\n g2.drawString(\"Welcome to TutorialsPoint\", 50, 120); \n }\n}" }, { "code": null, "e": 9724, "s": 9633, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 9781, "s": 9724, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTGraphicsDemo.java" }, { "code": null, "e": 9878, "s": 9781, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 9929, "s": 9878, "text": "D:\\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo" }, { "code": null, "e": 9957, "s": 9929, "text": "Verify the following output" }, { "code": null, "e": 9990, "s": 9957, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 9998, "s": 9990, "text": " EduOLC" }, { "code": null, "e": 10005, "s": 9998, "text": " Print" }, { "code": null, "e": 10016, "s": 10005, "text": " Add Notes" } ]
LCM and HCF of fractions - GeeksforGeeks
07 Apr, 2021 Given n fractions as two arrays Num and Den. The task is to find out the L.C.M of the fractions. Examples: Input: num[] = {1, 7, 4}, den[] = {2, 3, 6} Output: LCM is = 28/1 The given fractions are 1/2, 7/3 and 4/6. The LCM is 28/1 Input: num[] = {24, 48, 72, 96}, den[] = {2, 6, 8, 3} Output: LCM is = 288/1 LCM of A/B and C/D = (LCM of A and C) / (HCF of B and D) Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to find LCM of array of fractions#include <bits/stdc++.h>using namespace std; // Function that will calculate// the Lcm of Numeratorint LCM(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = (((num[i] * ans)) / (__gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorint HCF(int den[], int N){ int ans = den[0]; for(int i = 1; i < N; i++) ans = __gcd(den[i], ans); return ans;} int LCMOfFractions(int num[], int den[], int N){ int Numerator = LCM(num, N); int Denominator = HCF(den, N); int gcd = __gcd(Numerator, Denominator); Numerator = Numerator / gcd; Denominator = Denominator / gcd; cout << "LCM is = " << Numerator << "/" << Denominator;} // Driver codeint main(){ int num[] = { 1, 7, 4 }, den[] = { 2, 3, 6 }; int N = sizeof(num) / sizeof(num[0]); LCMOfFractions(num, den, N); return 0;} // Java program to find LCM of array of fractions class GFG{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // Function that will calculate// the Lcm of Numeratorstatic int LCM(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorstatic int HCF(int den[], int N){ int ans = den[0]; for(int i = 1; i < N; i++) ans = gcd(den[i], ans); return ans;} static int LCMOfFractions(int num[], int den[], int N){ int Numerator = LCM(num, N); int Denominator = HCF(den, N); int gcd1 = gcd(Numerator, Denominator); Numerator = Numerator / gcd1; Denominator = Denominator / gcd1; System.out.println("LCM is = " +Numerator+ "/" + Denominator); return 0;} // Driver codepublic static void main(String args[]){ int num[] = { 1, 7, 4 }, den[] = { 2, 3, 6 }; int N = num.length; LCMOfFractions(num, den, N);}} # Python3 def program to find LCM of# array of fractions # Recursive function to# return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0): return b; if (b == 0): return a; # base case if (a == b): return a; # a is greater if (a > b): return gcd(a - b, b); return gcd(a, b - a); # Function that will calculate# the Lcm of Numeratordef LCM(num, N): ans = num[0]; for i in range(1,N): ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans; # Function that will calculate# the Hcf of Denominatordef HCF(den, N): ans = den[0]; for i in range(1,N): ans = gcd(den[i], ans); return ans; def LCMOfFractions(num, den, N): Numerator = LCM(num, N); Denominator = HCF(den, N); gcd1 = gcd(Numerator, Denominator); Numerator = int(Numerator / gcd1); Denominator = int(Denominator / gcd1); print("LCM is =",Numerator,"/",Denominator); # Driver codenum = [1, 7, 4 ];den = [2, 3, 6 ];N = len(num);LCMOfFractions(num, den, N); # This code is contributed# by mits // C# program to find LCM of// array of fractionsusing System; class GFG{ // Recursive function to return// gcd of a and bstatic int gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function that will calculate// the Lcm of Numeratorstatic int LCM(int []num, int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorstatic int HCF(int []den, int N){ int ans = den[0]; for(int i = 1; i < N; i++) ans = gcd(den[i], ans); return ans;} static int LCMOfFractions(int []num, int []den, int N){ int Numerator = LCM(num, N); int Denominator = HCF(den, N); int gcd1 = gcd(Numerator, Denominator); Numerator = Numerator / gcd1; Denominator = Denominator / gcd1; Console.WriteLine("LCM is = " + Numerator + "/" + Denominator); return 0;} // Driver codestatic public void Main(String []args){ int[] num = { 1, 7, 4 }, den = { 2, 3, 6 }; int N = num.Length; LCMOfFractions(num, den, N);}} // This code is contributed by Arnab Kundu <?php// PHP program to find LCM of// array of fractions // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return gcd($a - $b, $b); return gcd($a, $b - $a);} // Function that will calculate// the Lcm of Numeratorfunction LCM($num, $N){ $ans = $num[0]; for ($i = 1; $i < $N; $i++) $ans = ((($num[$i] * $ans)) / (gcd($num[$i], $ans))); return $ans;} // Function that will calculate// the Hcf of Denominatorfunction HCF($den, $N){ $ans = $den[0]; for($i = 1; $i < $N; $i++) $ans = gcd($den[$i], $ans); return $ans;} function LCMOfFractions($num, $den, $N){ $Numerator = LCM($num, $N); $Denominator = HCF($den, $N); $gcd1 = gcd($Numerator, $Denominator); $Numerator = $Numerator / $gcd1; $Denominator = $Denominator / $gcd1; echo "LCM is = " . $Numerator . "/" . $Denominator; return 0;} // Driver code$num = array(1, 7, 4 );$den = array(2, 3, 6 );$N = sizeof($num);LCMOfFractions($num, $den, $N); // This code is contributed// by Akanksha Rai <script> // Javascript program to find LCM of// array of fractionsvar num = [ 1, 7, 4 ];var den = [ 2, 3, 6 ]; // Recursive function to return// gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function that will calculate// the Lcm of Numeratorfunction LCM(num, N){ var ans = num[0]; for(var i = 1; i < N; i++) ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorfunction HCF(den, N){ var ans = den[0]; for(var i = 1; i < N; i++) ans = gcd(den[i], ans); return ans;} function LCMOfFractions(num, den, N){ var Numerator = LCM(num, N); var Denominator = HCF(den, N); var gcd1 = gcd(Numerator, Denominator); Numerator = Numerator / gcd1; Denominator = Denominator / gcd1; document.write("LCM is = " + Numerator + "/" + Denominator); return 0;} // Driver codevar N = num.length; LCMOfFractions(num, den, N); // This code is contributed by Ankita saini </script> LCM is = 28/1 Given n fractions as two arrays Num and Den. The task is to find out the L.C.M of the fractions. Input: num[] = {1, 7, 4}, den[] = {2, 3, 6} Output: HCF is 1/6 The given fractions are 1/2, 7/3 and 4/6. The HCF is 1/6 Input: num[] = {24, 48, 72, 96}, den[] = {2, 6, 8, 3} Output: HCF is 1/1 HCF of A/B and C/D = (HCF of A and C) / (LCM of B and D) Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to find GCD of array of fractions#include <bits/stdc++.h>using namespace std; // Function that will calculate// the Lcm of Denominatorint LCM(int den[], int N){ int ans = den[0]; for (int i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans;} // Function that will calculate// the Hcf of Numeratorint HCF(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans;} int HCFOfFractions(int num[], int den[], int N){ int Numerator = HCF(num, N); int Denominator = LCM(den, N); int result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; cout << "HCF is = " << Numerator << "/" << Denominator;} // Driver codeint main(){ int num[] = { 24, 48, 72, 96 }, den[] = { 2, 6, 8, 3 }; int N = sizeof(num) / sizeof(num[0]); HCFOfFractions(num, den, N); return 0;} // Java program to find GCD of array of fractions class GFG{ static int __gcd(int a, int b){ if (a == 0) return b; return __gcd(b % a, a);}// Function that will calculate// the Lcm of Denominatorstatic int LCM(int den[], int N){ int ans = den[0]; for (int i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans;} // Function that will calculate// the Hcf of Numeratorstatic int HCF(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans;} static void HCFOfFractions(int num[], int den[], int N){ int Numerator = HCF(num, N); int Denominator = LCM(den, N); int result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; System.out.println("HCF is = "+Numerator+"/"+Denominator);} // Driver codepublic static void main(String[] args){ int num[] = { 24, 48, 72, 96 }, den[] = { 2, 6, 8, 3 }; int N = num.length; HCFOfFractions(num, den, N); }}// This code is contributed by mits # Python3 def program to find LCM# of array of fractions # Recursive function to# return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0): return b; if (b == 0): return a; # base case if (a == b): return a; # a is greater if (a > b): return gcd(a - b, b); return gcd(a, b - a); # Function that will calculate# the Lcm of Numeratordef LCM(den, N): ans = den[0]; for i in range(1,N): ans = (((den[i] * ans)) / (gcd(den[i], ans))); return ans; # Function that will calculate# the Hcf of Denominatordef HCF(num, N): ans = num[0]; for i in range(1, N): ans = gcd(num[i], ans); return ans; def HCFOfFractions(num, den, N): Numerator = HCF(num, N); Denominator = LCM(den, N); gcd1 = gcd(Numerator, Denominator); Numerator = int(Numerator / gcd1); Denominator = int(Denominator / gcd1); print("HCF is =", Numerator, "/", Denominator); # Driver codenum = [24, 48, 72, 96 ];den = [2, 6, 8, 3 ];N = len(num);HCFOfFractions(num, den, N); # This code is contributed# by Akanksha Rai // C# program to find GCD of array of fractionsusing System;class GFG{ static int __gcd(int a, int b){ if (a == 0) return b; return __gcd(b % a, a);}// Function that will calculate// the Lcm of Denominatorstatic int LCM(int[] den, int N){ int ans = den[0]; for (int i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans;} // Function that will calculate// the Hcf of Numeratorstatic int HCF(int[] num, int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans;} static void HCFOfFractions(int[] num, int[] den, int N){ int Numerator = HCF(num, N); int Denominator = LCM(den, N); int result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; Console.WriteLine("HCF is = "+Numerator+"/"+Denominator);} // Driver codepublic static void Main(){ int[] num = { 24, 48, 72, 96 }, den = { 2, 6, 8, 3 }; int N = num.Length; HCFOfFractions(num, den, N); }}// This code is contributed by mits <?php// PHP program to find GCD of// array of fractionsfunction __gcd($a, $b){ if ($a == 0) return $b; return __gcd($b % $a, $a);} // Function that will calculate// the Lcm of Denominatorfunction LCM($den, $N){ $ans = $den[0]; for ($i = 1; $i < $N; $i++) $ans = ((($den[$i] * $ans)) / (__gcd($den[$i], $ans))); return $ans;} // Function that will calculate// the Hcf of Numeratorfunction HCF($num, $N){ $ans = $num[0]; for ($i = 1; $i < $N; $i++) $ans = __gcd($num[$i], $ans); return $ans;} function HCFOfFractions($num, $den, $N){ $Numerator = HCF($num, $N); $Denominator = LCM($den, $N); $result = __gcd($Numerator, $Denominator); $Numerator = $Numerator / $result; $Denominator = $Denominator / $result; echo "HCF is = " . $Numerator . "/" . $Denominator;} // Driver code$num = array( 24, 48, 72, 96 );$den = array( 2, 6, 8, 3 );$N = count($num);HCFOfFractions($num, $den, $N); // This code is contributed by mits?> <script> // Javascript program to find GCD of array of fractions const __gcd = (a, b) => { if(a == 0){ return b; } return __gcd(b % a, a);} // Function that will calculate // the Lcm of Denominator const LCM = (den, N) => { let ans = den[0]; for (var i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans; } // Function that will calculate // the Hcf of Numerator const HCF = (num, N) => { let ans = num[0]; for (var i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans; } const HCFOfFractions = (num, den, N) => { let Numerator = HCF(num, N); let Denominator = LCM(den, N); let result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; document.write(`HCF is = ${Numerator} / ${Denominator}`); } // Driver code let num = [24, 48, 72, 96 ];let den = [2, 6, 8, 3 ]; let N = num.length; HCFOfFractions(num, den, N); // This code is contributed by _saurabh_jaiswal </script> HCF is = 1/1 Kirti_Mangal andrew1234 Akanksha_Rai Mithun Kumar _saurabh_jaiswal ankita_saini Fraction GCD-LCM Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Find all pairs in an Array in sorted order with minimum absolute difference Fizz Buzz Implementation Program to print prime numbers from 1 to N. Modular multiplicative inverse Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24716, "s": 24688, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24813, "s": 24716, "text": "Given n fractions as two arrays Num and Den. The task is to find out the L.C.M of the fractions." }, { "code": null, "e": 24824, "s": 24813, "text": "Examples: " }, { "code": null, "e": 24948, "s": 24824, "text": "Input: num[] = {1, 7, 4}, den[] = {2, 3, 6} Output: LCM is = 28/1 The given fractions are 1/2, 7/3 and 4/6. The LCM is 28/1" }, { "code": null, "e": 25027, "s": 24948, "text": "Input: num[] = {24, 48, 72, 96}, den[] = {2, 6, 8, 3} Output: LCM is = 288/1 " }, { "code": null, "e": 25086, "s": 25027, "text": "LCM of A/B and C/D = (LCM of A and C) / (HCF of B and D) " }, { "code": null, "e": 25133, "s": 25086, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 25137, "s": 25133, "text": "C++" }, { "code": null, "e": 25142, "s": 25137, "text": "Java" }, { "code": null, "e": 25150, "s": 25142, "text": "Python3" }, { "code": null, "e": 25153, "s": 25150, "text": "C#" }, { "code": null, "e": 25157, "s": 25153, "text": "PHP" }, { "code": null, "e": 25168, "s": 25157, "text": "Javascript" }, { "code": "// C++ program to find LCM of array of fractions#include <bits/stdc++.h>using namespace std; // Function that will calculate// the Lcm of Numeratorint LCM(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = (((num[i] * ans)) / (__gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorint HCF(int den[], int N){ int ans = den[0]; for(int i = 1; i < N; i++) ans = __gcd(den[i], ans); return ans;} int LCMOfFractions(int num[], int den[], int N){ int Numerator = LCM(num, N); int Denominator = HCF(den, N); int gcd = __gcd(Numerator, Denominator); Numerator = Numerator / gcd; Denominator = Denominator / gcd; cout << \"LCM is = \" << Numerator << \"/\" << Denominator;} // Driver codeint main(){ int num[] = { 1, 7, 4 }, den[] = { 2, 3, 6 }; int N = sizeof(num) / sizeof(num[0]); LCMOfFractions(num, den, N); return 0;}", "e": 26107, "s": 25168, "text": null }, { "code": "// Java program to find LCM of array of fractions class GFG{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // Function that will calculate// the Lcm of Numeratorstatic int LCM(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorstatic int HCF(int den[], int N){ int ans = den[0]; for(int i = 1; i < N; i++) ans = gcd(den[i], ans); return ans;} static int LCMOfFractions(int num[], int den[], int N){ int Numerator = LCM(num, N); int Denominator = HCF(den, N); int gcd1 = gcd(Numerator, Denominator); Numerator = Numerator / gcd1; Denominator = Denominator / gcd1; System.out.println(\"LCM is = \" +Numerator+ \"/\" + Denominator); return 0;} // Driver codepublic static void main(String args[]){ int num[] = { 1, 7, 4 }, den[] = { 2, 3, 6 }; int N = num.length; LCMOfFractions(num, den, N);}}", "e": 27424, "s": 26107, "text": null }, { "code": "# Python3 def program to find LCM of# array of fractions # Recursive function to# return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0): return b; if (b == 0): return a; # base case if (a == b): return a; # a is greater if (a > b): return gcd(a - b, b); return gcd(a, b - a); # Function that will calculate# the Lcm of Numeratordef LCM(num, N): ans = num[0]; for i in range(1,N): ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans; # Function that will calculate# the Hcf of Denominatordef HCF(den, N): ans = den[0]; for i in range(1,N): ans = gcd(den[i], ans); return ans; def LCMOfFractions(num, den, N): Numerator = LCM(num, N); Denominator = HCF(den, N); gcd1 = gcd(Numerator, Denominator); Numerator = int(Numerator / gcd1); Denominator = int(Denominator / gcd1); print(\"LCM is =\",Numerator,\"/\",Denominator); # Driver codenum = [1, 7, 4 ];den = [2, 3, 6 ];N = len(num);LCMOfFractions(num, den, N); # This code is contributed# by mits", "e": 28513, "s": 27424, "text": null }, { "code": "// C# program to find LCM of// array of fractionsusing System; class GFG{ // Recursive function to return// gcd of a and bstatic int gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function that will calculate// the Lcm of Numeratorstatic int LCM(int []num, int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorstatic int HCF(int []den, int N){ int ans = den[0]; for(int i = 1; i < N; i++) ans = gcd(den[i], ans); return ans;} static int LCMOfFractions(int []num, int []den, int N){ int Numerator = LCM(num, N); int Denominator = HCF(den, N); int gcd1 = gcd(Numerator, Denominator); Numerator = Numerator / gcd1; Denominator = Denominator / gcd1; Console.WriteLine(\"LCM is = \" + Numerator + \"/\" + Denominator); return 0;} // Driver codestatic public void Main(String []args){ int[] num = { 1, 7, 4 }, den = { 2, 3, 6 }; int N = num.Length; LCMOfFractions(num, den, N);}} // This code is contributed by Arnab Kundu", "e": 29891, "s": 28513, "text": null }, { "code": "<?php// PHP program to find LCM of// array of fractions // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if ($a == $b) return $a; // a is greater if ($a > $b) return gcd($a - $b, $b); return gcd($a, $b - $a);} // Function that will calculate// the Lcm of Numeratorfunction LCM($num, $N){ $ans = $num[0]; for ($i = 1; $i < $N; $i++) $ans = ((($num[$i] * $ans)) / (gcd($num[$i], $ans))); return $ans;} // Function that will calculate// the Hcf of Denominatorfunction HCF($den, $N){ $ans = $den[0]; for($i = 1; $i < $N; $i++) $ans = gcd($den[$i], $ans); return $ans;} function LCMOfFractions($num, $den, $N){ $Numerator = LCM($num, $N); $Denominator = HCF($den, $N); $gcd1 = gcd($Numerator, $Denominator); $Numerator = $Numerator / $gcd1; $Denominator = $Denominator / $gcd1; echo \"LCM is = \" . $Numerator . \"/\" . $Denominator; return 0;} // Driver code$num = array(1, 7, 4 );$den = array(2, 3, 6 );$N = sizeof($num);LCMOfFractions($num, $den, $N); // This code is contributed// by Akanksha Rai", "e": 31139, "s": 29891, "text": null }, { "code": "<script> // Javascript program to find LCM of// array of fractionsvar num = [ 1, 7, 4 ];var den = [ 2, 3, 6 ]; // Recursive function to return// gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // Base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a);} // Function that will calculate// the Lcm of Numeratorfunction LCM(num, N){ var ans = num[0]; for(var i = 1; i < N; i++) ans = (((num[i] * ans)) / (gcd(num[i], ans))); return ans;} // Function that will calculate// the Hcf of Denominatorfunction HCF(den, N){ var ans = den[0]; for(var i = 1; i < N; i++) ans = gcd(den[i], ans); return ans;} function LCMOfFractions(num, den, N){ var Numerator = LCM(num, N); var Denominator = HCF(den, N); var gcd1 = gcd(Numerator, Denominator); Numerator = Numerator / gcd1; Denominator = Denominator / gcd1; document.write(\"LCM is = \" + Numerator + \"/\" + Denominator); return 0;} // Driver codevar N = num.length; LCMOfFractions(num, den, N); // This code is contributed by Ankita saini </script>", "e": 32420, "s": 31139, "text": null }, { "code": null, "e": 32434, "s": 32420, "text": "LCM is = 28/1" }, { "code": null, "e": 32534, "s": 32436, "text": "Given n fractions as two arrays Num and Den. The task is to find out the L.C.M of the fractions. " }, { "code": null, "e": 32654, "s": 32534, "text": "Input: num[] = {1, 7, 4}, den[] = {2, 3, 6} Output: HCF is 1/6 The given fractions are 1/2, 7/3 and 4/6. The HCF is 1/6" }, { "code": null, "e": 32729, "s": 32654, "text": "Input: num[] = {24, 48, 72, 96}, den[] = {2, 6, 8, 3} Output: HCF is 1/1 " }, { "code": null, "e": 32788, "s": 32729, "text": "HCF of A/B and C/D = (HCF of A and C) / (LCM of B and D) " }, { "code": null, "e": 32836, "s": 32788, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 32840, "s": 32836, "text": "C++" }, { "code": null, "e": 32845, "s": 32840, "text": "Java" }, { "code": null, "e": 32853, "s": 32845, "text": "Python3" }, { "code": null, "e": 32856, "s": 32853, "text": "C#" }, { "code": null, "e": 32860, "s": 32856, "text": "PHP" }, { "code": null, "e": 32871, "s": 32860, "text": "Javascript" }, { "code": "// CPP program to find GCD of array of fractions#include <bits/stdc++.h>using namespace std; // Function that will calculate// the Lcm of Denominatorint LCM(int den[], int N){ int ans = den[0]; for (int i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans;} // Function that will calculate// the Hcf of Numeratorint HCF(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans;} int HCFOfFractions(int num[], int den[], int N){ int Numerator = HCF(num, N); int Denominator = LCM(den, N); int result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; cout << \"HCF is = \" << Numerator << \"/\" << Denominator;} // Driver codeint main(){ int num[] = { 24, 48, 72, 96 }, den[] = { 2, 6, 8, 3 }; int N = sizeof(num) / sizeof(num[0]); HCFOfFractions(num, den, N); return 0;}", "e": 33824, "s": 32871, "text": null }, { "code": "// Java program to find GCD of array of fractions class GFG{ static int __gcd(int a, int b){ if (a == 0) return b; return __gcd(b % a, a);}// Function that will calculate// the Lcm of Denominatorstatic int LCM(int den[], int N){ int ans = den[0]; for (int i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans;} // Function that will calculate// the Hcf of Numeratorstatic int HCF(int num[], int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans;} static void HCFOfFractions(int num[], int den[], int N){ int Numerator = HCF(num, N); int Denominator = LCM(den, N); int result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; System.out.println(\"HCF is = \"+Numerator+\"/\"+Denominator);} // Driver codepublic static void main(String[] args){ int num[] = { 24, 48, 72, 96 }, den[] = { 2, 6, 8, 3 }; int N = num.length; HCFOfFractions(num, den, N); }}// This code is contributed by mits", "e": 34899, "s": 33824, "text": null }, { "code": "# Python3 def program to find LCM# of array of fractions # Recursive function to# return gcd of a and bdef gcd(a, b): # Everything divides 0 if (a == 0): return b; if (b == 0): return a; # base case if (a == b): return a; # a is greater if (a > b): return gcd(a - b, b); return gcd(a, b - a); # Function that will calculate# the Lcm of Numeratordef LCM(den, N): ans = den[0]; for i in range(1,N): ans = (((den[i] * ans)) / (gcd(den[i], ans))); return ans; # Function that will calculate# the Hcf of Denominatordef HCF(num, N): ans = num[0]; for i in range(1, N): ans = gcd(num[i], ans); return ans; def HCFOfFractions(num, den, N): Numerator = HCF(num, N); Denominator = LCM(den, N); gcd1 = gcd(Numerator, Denominator); Numerator = int(Numerator / gcd1); Denominator = int(Denominator / gcd1); print(\"HCF is =\", Numerator, \"/\", Denominator); # Driver codenum = [24, 48, 72, 96 ];den = [2, 6, 8, 3 ];N = len(num);HCFOfFractions(num, den, N); # This code is contributed# by Akanksha Rai", "e": 36038, "s": 34899, "text": null }, { "code": "// C# program to find GCD of array of fractionsusing System;class GFG{ static int __gcd(int a, int b){ if (a == 0) return b; return __gcd(b % a, a);}// Function that will calculate// the Lcm of Denominatorstatic int LCM(int[] den, int N){ int ans = den[0]; for (int i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans;} // Function that will calculate// the Hcf of Numeratorstatic int HCF(int[] num, int N){ int ans = num[0]; for (int i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans;} static void HCFOfFractions(int[] num, int[] den, int N){ int Numerator = HCF(num, N); int Denominator = LCM(den, N); int result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; Console.WriteLine(\"HCF is = \"+Numerator+\"/\"+Denominator);} // Driver codepublic static void Main(){ int[] num = { 24, 48, 72, 96 }, den = { 2, 6, 8, 3 }; int N = num.Length; HCFOfFractions(num, den, N); }}// This code is contributed by mits", "e": 37107, "s": 36038, "text": null }, { "code": "<?php// PHP program to find GCD of// array of fractionsfunction __gcd($a, $b){ if ($a == 0) return $b; return __gcd($b % $a, $a);} // Function that will calculate// the Lcm of Denominatorfunction LCM($den, $N){ $ans = $den[0]; for ($i = 1; $i < $N; $i++) $ans = ((($den[$i] * $ans)) / (__gcd($den[$i], $ans))); return $ans;} // Function that will calculate// the Hcf of Numeratorfunction HCF($num, $N){ $ans = $num[0]; for ($i = 1; $i < $N; $i++) $ans = __gcd($num[$i], $ans); return $ans;} function HCFOfFractions($num, $den, $N){ $Numerator = HCF($num, $N); $Denominator = LCM($den, $N); $result = __gcd($Numerator, $Denominator); $Numerator = $Numerator / $result; $Denominator = $Denominator / $result; echo \"HCF is = \" . $Numerator . \"/\" . $Denominator;} // Driver code$num = array( 24, 48, 72, 96 );$den = array( 2, 6, 8, 3 );$N = count($num);HCFOfFractions($num, $den, $N); // This code is contributed by mits?>", "e": 38122, "s": 37107, "text": null }, { "code": "<script> // Javascript program to find GCD of array of fractions const __gcd = (a, b) => { if(a == 0){ return b; } return __gcd(b % a, a);} // Function that will calculate // the Lcm of Denominator const LCM = (den, N) => { let ans = den[0]; for (var i = 1; i < N; i++) ans = (((den[i] * ans)) / (__gcd(den[i], ans))); return ans; } // Function that will calculate // the Hcf of Numerator const HCF = (num, N) => { let ans = num[0]; for (var i = 1; i < N; i++) ans = __gcd(num[i], ans); return ans; } const HCFOfFractions = (num, den, N) => { let Numerator = HCF(num, N); let Denominator = LCM(den, N); let result = __gcd(Numerator, Denominator); Numerator = Numerator / result; Denominator = Denominator / result; document.write(`HCF is = ${Numerator} / ${Denominator}`); } // Driver code let num = [24, 48, 72, 96 ];let den = [2, 6, 8, 3 ]; let N = num.length; HCFOfFractions(num, den, N); // This code is contributed by _saurabh_jaiswal </script>", "e": 39170, "s": 38122, "text": null }, { "code": null, "e": 39183, "s": 39170, "text": "HCF is = 1/1" }, { "code": null, "e": 39198, "s": 39185, "text": "Kirti_Mangal" }, { "code": null, "e": 39209, "s": 39198, "text": "andrew1234" }, { "code": null, "e": 39222, "s": 39209, "text": "Akanksha_Rai" }, { "code": null, "e": 39235, "s": 39222, "text": "Mithun Kumar" }, { "code": null, "e": 39252, "s": 39235, "text": "_saurabh_jaiswal" }, { "code": null, "e": 39265, "s": 39252, "text": "ankita_saini" }, { "code": null, "e": 39274, "s": 39265, "text": "Fraction" }, { "code": null, "e": 39282, "s": 39274, "text": "GCD-LCM" }, { "code": null, "e": 39295, "s": 39282, "text": "Mathematical" }, { "code": null, "e": 39314, "s": 39295, "text": "School Programming" }, { "code": null, "e": 39327, "s": 39314, "text": "Mathematical" }, { "code": null, "e": 39425, "s": 39327, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39434, "s": 39425, "text": "Comments" }, { "code": null, "e": 39447, "s": 39434, "text": "Old Comments" }, { "code": null, "e": 39479, "s": 39447, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 39555, "s": 39479, "text": "Find all pairs in an Array in sorted order with minimum absolute difference" }, { "code": null, "e": 39580, "s": 39555, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 39624, "s": 39580, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 39655, "s": 39624, "text": "Modular multiplicative inverse" }, { "code": null, "e": 39673, "s": 39655, "text": "Python Dictionary" }, { "code": null, "e": 39689, "s": 39673, "text": "Arrays in C/C++" }, { "code": null, "e": 39708, "s": 39689, "text": "Inheritance in C++" }, { "code": null, "e": 39733, "s": 39708, "text": "Reverse a string in Java" } ]
How to use Meta Tag to redirect an HTML page?
Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection. To use a META Tag to redirect your site is quite easy. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The following is an example of redirecting current page to another page after 2 seconds. If you want to redirect page immediately then do not specify the content attribute. Live Demo <!DOCTYPE html> <html> <head> <title>HTML Meta Tag</title> <meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" /> </head> <body> <p>This is demo text.</p> </body> </html>
[ { "code": null, "e": 1224, "s": 1062, "text": "Page redirection is a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection." }, { "code": null, "e": 1385, "s": 1224, "text": "To use a META Tag to redirect your site is quite easy. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute." }, { "code": null, "e": 1558, "s": 1385, "text": "The following is an example of redirecting current page to another page after 2 seconds. If you want to redirect page immediately then do not specify the content attribute." }, { "code": null, "e": 1568, "s": 1558, "text": "Live Demo" }, { "code": null, "e": 1798, "s": 1568, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Meta Tag</title>\n <meta http-equiv = \"refresh\" content = \"2; url = https://www.tutorialspoint.com\" />\n </head>\n <body>\n <p>This is demo text.</p>\n </body>\n</html>" } ]
Using Python to insert data into SAP with PyRFC | by Rafael Cordeiro | Towards Data Science
Today we are seeing the daily increase of Machine Learning (ML) development and the largest development tool is Python and each day more and more people are trying to return the results of the ML models into their Enterprise Resource Planning systems (ERPs). SAP is one of the most used ERPs systems and to insert the results of an ML model into it we have two options, manually in a custom SAP transaction or using a Remote Function Call (RFC) which is the standard SAP interface for communication between SAP systems and other systems, so RFC calls a function to be executed in a remote system. Let’s say that you can automate the upload of the result file in the transaction with a Robotic Process Automation system (RPA), so then which one we should choose? Well, if I had to choose one of them I would pick the second option because it tends to vary less and have fewer updates than the first one, so you probably would have fewer problems with unnoticed updates. One important thing to point is that RFC has a lot of goals and ways to be developed and the one we want to use is to insert data into tables We can do that with Python using the PyRFC package, but the first use of it is not so simple, so to help with that I’ve created some functions and documentations. Let’s begin! SAP NW RFC SDK is the abbreviation for SAP NetWeaver Remote Function Call System Development Kit, this lets you manage the RFCs. I’ve found a really good manual from Informatica of how to download it, but it’s for an older version and some icons are quite different now, so I’ve written the steps and reprinted the images to have it up to date. If you want to see the manual of Informatica, it is linked at the end of the article as a Source. One difficult thing about downloading this content is that you need an SAP account to do it, so try to get one before starting this journey. Coming back, the download steps: Go to the SAP Service Marketplace: http://service.sap.com/support Enter your SAP Service Marketplace user name and password. The SAP Support Portal page appears. Click the Download Software icon. Observation, once you are logged in the user icon changes its color to blue Click the Support Packages & Patches tab. Click By Category from the list. Click Additional Components from the list. Click SAP NW RFC SDK from the list. Click on the most recent version of SAP NW RFC SDK. Select the operating system for which you want to download Click the hyperlinked .zip file to download libraries. Extract the files and folders that are inside the .zip to your SAP folder The highlighted folders and files were what was inside of the .zip. Once you’ve done that everything is set from the SAP side. It’s a little bit easier than the last step, just write and run, separately, these two lines on your Python terminal. pip install pyrfcpip install pynwrfc I think you might only need to run the second one, but I’ve installed both of them and I prefer to say to you to install them too instead of you not being able to use the PyRFC package. Cool, now you’ve reached the interesting part! Obs: If you have to turn on your Virtual Private Network (VPN) to access SAP you will also need to have it turned on when using these functions. For this development, we’ll have two files: constants.py and sap_rfc_connection.py. Inside constants.py we store the three things, the dictionary with SAP logon credentials, RFC function and table names, and the number of rows you are going to insert per RFC call. Now, in sap_rfc_connection.py we have two main functions: rfc_func_desc def rfc_func_desc(dict_sap_con, func_name): '''consult the RFC description and needed input fields Parameters ---------- dict_sap_con : dict key to create connection with SAP, must contain: user, passwd, ashost, sysnr, client func_name : str name of the function that you want to verify Returns ------- funct_desc : pyrfc.pyrfc.FunctionDescription RFC functional description object ''' print(f'{time.ctime()}, Start getting function description from RFC') print(f'{time.ctime()}, Start SAP connection') # create connection with SAP based on data inside the dict with Connection(**dict_sap_con) as conn: print(f'{time.ctime()}, SAP connection stablished') # get data from the desired RFC function funct_desc = conn.get_function_description(func_name) # display the information about the RFC to user display(funct_desc.parameters[0],funct_desc.parameters[0]['type_description'].fields) # return it as a variable return funct_desc # how the whole command is inside the 'with' when it ends the connection with SAP is closed print(f'{time.ctime()}, SAP connection closed') print(f'{time.ctime()}, End getting function description from RFC') Now an example of how it works, the main goal of this function is to let you get the whole RFC description and stores it into a variable so you can consult it later (and you also can check PyDrive documentation to see all sort of things you can do with it), and display to you what is needed to use the RFC like fields names and data types. This is useful because with them we know the structure/columns names of your data frame and the data type you must use in each field to not get an error. In my case, I’ve created this data frame bellow to test. After the data frame creation, we can continue to the second function. df_to_sap_rfc def df_to_sap_rfc(df, dict_sap_con, func_name, rfc_table): '''ingest data that is in a data frame in SAP using a defined RFC, checking if the dataframe has the same size, column names and data types Parameters ---------- df : pandas.DataFrame dataframe that is going to be used to insert data to SAP dict_sap_con : dict dictionary with SAP logon credentials (user, passwd, ashost, sysnr, client) func_name : string name of the RFC function rfc_table : string name of the rfc table you are going to populate Returns ------- None ''' # get needed parameters from RFC lst_param = get_rfc_parameters(dict_sap_con, func_name) # check dataframe input check_input_format(df, lst_param) # insert data lst_res = insert_df_in_sap_rfc( df, dict_sap_con, func_name, rfc_table) This function wraps another three methods inside of it, but to not waste too much time on them the first two are to check if the data frame follows the RFC requested format (column names and data types), and if doesn’t have it stops the execution to not insert wrong data into SAP. The real “magic” happens inside the third one, the insert_df_in_sap_rfc function: def insert_df_in_sap_rfc(df, dict_sap_con, func_name, rfc_table): '''Ingest data that is in a data frame in SAP using a defined RFC Parameters ---------- df : pandas.DataFrame dataframe that is going to be used to insert data to SAP dict_sap_con : dict dictionary with SAP logon credentials (user, passwd, ashost, sysnr, client) func_name : string name of the function that you want to remotelly call rfc_table : string name of the table which your RFC populates Returns ------- lst_res : list list of dictionaries with field names and data types used in RFC ''' print(f'{time.ctime()}, Start data ingestion to SAP process') # create an empty list that is going to recive the result lst_res = [] # get the quantity of rows of the dataframe rows_qty = len(df) # define the number of execution, getting the entire part of the division and # adding 1 to it, to execute the last rows that don't achieve the quantity of # an extra execution iter_qty = (rows_qty // c.rows_per_exec) + 1 print(f'{time.ctime()}, Start SAP connection') # create connection with SAP based on data inside the dict with Connection(**dict_sap_con) as conn: print(f'{time.ctime()}, SAP connection stablished') # for each iteration for i in range(iter_qty): # define the first and last row for this execution f_r = i*c.rows_per_exec l_r = min((i+1)*c.rows_per_exec, rows_qty) # define an auxiliar dataframe with only the rows of this iteration df_aux = df.iloc[f_r:l_r] print(f'{time.ctime()}, Rows defined') # convert this dataframe to a json format, oriented by records # this is the needed format to do a multirow input with a RFC # by last all the json data must be inside of a list lst_dicts_rows = eval(df_aux.to_json(orient='records')) # once we have the desired rows well formatted we must tell for # which table we are going to insert it dict_insert = {rfc_table: lst_dicts_rows} print(f'{time.ctime()}, RFC input format applied') print(f'{time.ctime()}, Start sending rows {f_r} to {l_r-1}') # with everything set just call the RFC by its name # and pass the connection dict try: result = conn.call(func_name, **dict_insert) exec_ind = True except: result = None exec_ind = False print(f'{time.ctime()}, Rows {f_r} to {l_r-1} sent') # save the row's numbers, execution indicator and the result of the call in the list # as a dict lst_res.append({'row':f'{f_r}_{l_r-1}', 'exec_ind':exec_ind, 'rfc_result':result}) # how the whole command is inside the 'with' when it ends the connection with SAP is closed print(f'{time.ctime()}, SAP connection closed') print(f'{time.ctime()}, End data ingestion to SAP process') return lst_res Long story short, this piece of code gets the number of rows per execution that you define in constants.py and calculate the number of iterations to fully insert your data frame into SAP. After that, it is going to split your data frame into slices, convert them to a .json oriented by records format and put all inside a list, and to finish, it is stored inside of a dictionary whose key is the RFC table name. This come and go might be a little confusing, but it creates a dictionary that lets us insert multiple rows at once to an SAP table. In the end, if everything was set well you will have something like this: If you got interested in these files you can see them in my Git Hub with the link below: github.com If you are thinking to use PyRFC in a process that you must repeat it periodically, perhaps this article bellow may help you to schedule it. medium.com Well, with this I think you can now use Python and RFC to insert data into SAP with a little more ease! I hope this article has helped you! Special thanks to Leonardo Ramos and Anderson Tessitori who put up with me while I cleared a million RFC questions with them
[ { "code": null, "e": 306, "s": 47, "text": "Today we are seeing the daily increase of Machine Learning (ML) development and the largest development tool is Python and each day more and more people are trying to return the results of the ML models into their Enterprise Resource Planning systems (ERPs)." }, { "code": null, "e": 644, "s": 306, "text": "SAP is one of the most used ERPs systems and to insert the results of an ML model into it we have two options, manually in a custom SAP transaction or using a Remote Function Call (RFC) which is the standard SAP interface for communication between SAP systems and other systems, so RFC calls a function to be executed in a remote system." }, { "code": null, "e": 809, "s": 644, "text": "Let’s say that you can automate the upload of the result file in the transaction with a Robotic Process Automation system (RPA), so then which one we should choose?" }, { "code": null, "e": 1016, "s": 809, "text": "Well, if I had to choose one of them I would pick the second option because it tends to vary less and have fewer updates than the first one, so you probably would have fewer problems with unnoticed updates." }, { "code": null, "e": 1158, "s": 1016, "text": "One important thing to point is that RFC has a lot of goals and ways to be developed and the one we want to use is to insert data into tables" }, { "code": null, "e": 1321, "s": 1158, "text": "We can do that with Python using the PyRFC package, but the first use of it is not so simple, so to help with that I’ve created some functions and documentations." }, { "code": null, "e": 1334, "s": 1321, "text": "Let’s begin!" }, { "code": null, "e": 1463, "s": 1334, "text": "SAP NW RFC SDK is the abbreviation for SAP NetWeaver Remote Function Call System Development Kit, this lets you manage the RFCs." }, { "code": null, "e": 1679, "s": 1463, "text": "I’ve found a really good manual from Informatica of how to download it, but it’s for an older version and some icons are quite different now, so I’ve written the steps and reprinted the images to have it up to date." }, { "code": null, "e": 1777, "s": 1679, "text": "If you want to see the manual of Informatica, it is linked at the end of the article as a Source." }, { "code": null, "e": 1918, "s": 1777, "text": "One difficult thing about downloading this content is that you need an SAP account to do it, so try to get one before starting this journey." }, { "code": null, "e": 1951, "s": 1918, "text": "Coming back, the download steps:" }, { "code": null, "e": 2017, "s": 1951, "text": "Go to the SAP Service Marketplace: http://service.sap.com/support" }, { "code": null, "e": 2113, "s": 2017, "text": "Enter your SAP Service Marketplace user name and password. The SAP Support Portal page appears." }, { "code": null, "e": 2147, "s": 2113, "text": "Click the Download Software icon." }, { "code": null, "e": 2223, "s": 2147, "text": "Observation, once you are logged in the user icon changes its color to blue" }, { "code": null, "e": 2265, "s": 2223, "text": "Click the Support Packages & Patches tab." }, { "code": null, "e": 2298, "s": 2265, "text": "Click By Category from the list." }, { "code": null, "e": 2341, "s": 2298, "text": "Click Additional Components from the list." }, { "code": null, "e": 2377, "s": 2341, "text": "Click SAP NW RFC SDK from the list." }, { "code": null, "e": 2429, "s": 2377, "text": "Click on the most recent version of SAP NW RFC SDK." }, { "code": null, "e": 2488, "s": 2429, "text": "Select the operating system for which you want to download" }, { "code": null, "e": 2543, "s": 2488, "text": "Click the hyperlinked .zip file to download libraries." }, { "code": null, "e": 2617, "s": 2543, "text": "Extract the files and folders that are inside the .zip to your SAP folder" }, { "code": null, "e": 2685, "s": 2617, "text": "The highlighted folders and files were what was inside of the .zip." }, { "code": null, "e": 2744, "s": 2685, "text": "Once you’ve done that everything is set from the SAP side." }, { "code": null, "e": 2862, "s": 2744, "text": "It’s a little bit easier than the last step, just write and run, separately, these two lines on your Python terminal." }, { "code": null, "e": 2899, "s": 2862, "text": "pip install pyrfcpip install pynwrfc" }, { "code": null, "e": 3085, "s": 2899, "text": "I think you might only need to run the second one, but I’ve installed both of them and I prefer to say to you to install them too instead of you not being able to use the PyRFC package." }, { "code": null, "e": 3132, "s": 3085, "text": "Cool, now you’ve reached the interesting part!" }, { "code": null, "e": 3277, "s": 3132, "text": "Obs: If you have to turn on your Virtual Private Network (VPN) to access SAP you will also need to have it turned on when using these functions." }, { "code": null, "e": 3361, "s": 3277, "text": "For this development, we’ll have two files: constants.py and sap_rfc_connection.py." }, { "code": null, "e": 3542, "s": 3361, "text": "Inside constants.py we store the three things, the dictionary with SAP logon credentials, RFC function and table names, and the number of rows you are going to insert per RFC call." }, { "code": null, "e": 3600, "s": 3542, "text": "Now, in sap_rfc_connection.py we have two main functions:" }, { "code": null, "e": 3614, "s": 3600, "text": "rfc_func_desc" }, { "code": null, "e": 4880, "s": 3614, "text": "def rfc_func_desc(dict_sap_con, func_name): '''consult the RFC description and needed input fields Parameters ---------- dict_sap_con : dict key to create connection with SAP, must contain: user, passwd, ashost, sysnr, client func_name : str name of the function that you want to verify Returns ------- funct_desc : pyrfc.pyrfc.FunctionDescription RFC functional description object ''' print(f'{time.ctime()}, Start getting function description from RFC') print(f'{time.ctime()}, Start SAP connection') # create connection with SAP based on data inside the dict with Connection(**dict_sap_con) as conn: print(f'{time.ctime()}, SAP connection stablished') # get data from the desired RFC function funct_desc = conn.get_function_description(func_name) # display the information about the RFC to user display(funct_desc.parameters[0],funct_desc.parameters[0]['type_description'].fields) # return it as a variable return funct_desc # how the whole command is inside the 'with' when it ends the connection with SAP is closed print(f'{time.ctime()}, SAP connection closed') print(f'{time.ctime()}, End getting function description from RFC')" }, { "code": null, "e": 5221, "s": 4880, "text": "Now an example of how it works, the main goal of this function is to let you get the whole RFC description and stores it into a variable so you can consult it later (and you also can check PyDrive documentation to see all sort of things you can do with it), and display to you what is needed to use the RFC like fields names and data types." }, { "code": null, "e": 5375, "s": 5221, "text": "This is useful because with them we know the structure/columns names of your data frame and the data type you must use in each field to not get an error." }, { "code": null, "e": 5432, "s": 5375, "text": "In my case, I’ve created this data frame bellow to test." }, { "code": null, "e": 5503, "s": 5432, "text": "After the data frame creation, we can continue to the second function." }, { "code": null, "e": 5517, "s": 5503, "text": "df_to_sap_rfc" }, { "code": null, "e": 6380, "s": 5517, "text": "def df_to_sap_rfc(df, dict_sap_con, func_name, rfc_table): '''ingest data that is in a data frame in SAP using a defined RFC, checking if the dataframe has the same size, column names and data types Parameters ---------- df : pandas.DataFrame dataframe that is going to be used to insert data to SAP dict_sap_con : dict dictionary with SAP logon credentials (user, passwd, ashost, sysnr, client) func_name : string name of the RFC function rfc_table : string name of the rfc table you are going to populate Returns ------- None ''' # get needed parameters from RFC lst_param = get_rfc_parameters(dict_sap_con, func_name) # check dataframe input check_input_format(df, lst_param) # insert data lst_res = insert_df_in_sap_rfc( df, dict_sap_con, func_name, rfc_table)" }, { "code": null, "e": 6662, "s": 6380, "text": "This function wraps another three methods inside of it, but to not waste too much time on them the first two are to check if the data frame follows the RFC requested format (column names and data types), and if doesn’t have it stops the execution to not insert wrong data into SAP." }, { "code": null, "e": 6744, "s": 6662, "text": "The real “magic” happens inside the third one, the insert_df_in_sap_rfc function:" }, { "code": null, "e": 9816, "s": 6744, "text": "def insert_df_in_sap_rfc(df, dict_sap_con, func_name, rfc_table): '''Ingest data that is in a data frame in SAP using a defined RFC Parameters ---------- df : pandas.DataFrame dataframe that is going to be used to insert data to SAP dict_sap_con : dict dictionary with SAP logon credentials (user, passwd, ashost, sysnr, client) func_name : string name of the function that you want to remotelly call rfc_table : string name of the table which your RFC populates Returns ------- lst_res : list list of dictionaries with field names and data types used in RFC ''' print(f'{time.ctime()}, Start data ingestion to SAP process') # create an empty list that is going to recive the result lst_res = [] # get the quantity of rows of the dataframe rows_qty = len(df) # define the number of execution, getting the entire part of the division and # adding 1 to it, to execute the last rows that don't achieve the quantity of # an extra execution iter_qty = (rows_qty // c.rows_per_exec) + 1 print(f'{time.ctime()}, Start SAP connection') # create connection with SAP based on data inside the dict with Connection(**dict_sap_con) as conn: print(f'{time.ctime()}, SAP connection stablished') # for each iteration for i in range(iter_qty): # define the first and last row for this execution f_r = i*c.rows_per_exec l_r = min((i+1)*c.rows_per_exec, rows_qty) # define an auxiliar dataframe with only the rows of this iteration df_aux = df.iloc[f_r:l_r] print(f'{time.ctime()}, Rows defined') # convert this dataframe to a json format, oriented by records # this is the needed format to do a multirow input with a RFC # by last all the json data must be inside of a list lst_dicts_rows = eval(df_aux.to_json(orient='records')) # once we have the desired rows well formatted we must tell for # which table we are going to insert it dict_insert = {rfc_table: lst_dicts_rows} print(f'{time.ctime()}, RFC input format applied') print(f'{time.ctime()}, Start sending rows {f_r} to {l_r-1}') # with everything set just call the RFC by its name # and pass the connection dict try: result = conn.call(func_name, **dict_insert) exec_ind = True except: result = None exec_ind = False print(f'{time.ctime()}, Rows {f_r} to {l_r-1} sent') # save the row's numbers, execution indicator and the result of the call in the list # as a dict lst_res.append({'row':f'{f_r}_{l_r-1}', 'exec_ind':exec_ind, 'rfc_result':result}) # how the whole command is inside the 'with' when it ends the connection with SAP is closed print(f'{time.ctime()}, SAP connection closed') print(f'{time.ctime()}, End data ingestion to SAP process') return lst_res" }, { "code": null, "e": 10004, "s": 9816, "text": "Long story short, this piece of code gets the number of rows per execution that you define in constants.py and calculate the number of iterations to fully insert your data frame into SAP." }, { "code": null, "e": 10228, "s": 10004, "text": "After that, it is going to split your data frame into slices, convert them to a .json oriented by records format and put all inside a list, and to finish, it is stored inside of a dictionary whose key is the RFC table name." }, { "code": null, "e": 10361, "s": 10228, "text": "This come and go might be a little confusing, but it creates a dictionary that lets us insert multiple rows at once to an SAP table." }, { "code": null, "e": 10435, "s": 10361, "text": "In the end, if everything was set well you will have something like this:" }, { "code": null, "e": 10524, "s": 10435, "text": "If you got interested in these files you can see them in my Git Hub with the link below:" }, { "code": null, "e": 10535, "s": 10524, "text": "github.com" }, { "code": null, "e": 10676, "s": 10535, "text": "If you are thinking to use PyRFC in a process that you must repeat it periodically, perhaps this article bellow may help you to schedule it." }, { "code": null, "e": 10687, "s": 10676, "text": "medium.com" }, { "code": null, "e": 10791, "s": 10687, "text": "Well, with this I think you can now use Python and RFC to insert data into SAP with a little more ease!" }, { "code": null, "e": 10827, "s": 10791, "text": "I hope this article has helped you!" } ]
Time Series - Variations of ARIMA
In the previous chapter, we have now seen how ARIMA model works, and its limitations that it cannot handle seasonal data or multivariate time series and hence, new models were introduced to include these features. A glimpse of these new models is given here − It is a generalized version of auto regression model for multivariate stationary time series. It is characterized by ‘p’ parameter. It is a generalized version of moving average model for multivariate stationary time series. It is characterized by ‘q’ parameter. It is the combination of VAR and VMA and a generalized version of ARMA model for multivariate stationary time series. It is characterized by ‘p’ and ‘q’ parameters. Much like, ARMA is capable of acting like an AR model by setting ‘q’ parameter as 0 and as a MA model by setting ‘p’ parameter as 0, VARMA is also capable of acting like an VAR model by setting ‘q’ parameter as 0 and as a VMA model by setting ‘p’ parameter as 0. In [209]: df_multi = df[['T', 'C6H6(GT)']] split = len(df) - int(0.2*len(df)) train_multi, test_multi = df_multi[0:split], df_multi[split:] In [211]: from statsmodels.tsa.statespace.varmax import VARMAX model = VARMAX(train_multi, order = (2,1)) model_fit = model.fit() c:\users\naveksha\appdata\local\programs\python\python37\lib\site-packages\statsmodels\tsa\statespace\varmax.py:152: EstimationWarning: Estimation of VARMA(p,q) models is not generically robust, due especially to identification issues. EstimationWarning) c:\users\naveksha\appdata\local\programs\python\python37\lib\site-packages\statsmodels\tsa\base\tsa_model.py:171: ValueWarning: No frequency information was provided, so inferred frequency H will be used. % freq, ValueWarning) c:\users\naveksha\appdata\local\programs\python\python37\lib\site-packages\statsmodels\base\model.py:508: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals "Check mle_retvals", ConvergenceWarning) In [213]: predictions_multi = model_fit.forecast( steps=len(test_multi)) c:\users\naveksha\appdata\local\programs\python\python37\lib\site-packages\statsmodels\tsa\base\tsa_model.py:320: FutureWarning: Creating a DatetimeIndex by passing range endpoints is deprecated. Use `pandas.date_range` instead. freq = base_index.freq) c:\users\naveksha\appdata\local\programs\python\python37\lib\site-packages\statsmodels\tsa\statespace\varmax.py:152: EstimationWarning: Estimation of VARMA(p,q) models is not generically robust, due especially to identification issues. EstimationWarning) In [231]: plt.plot(train_multi['T']) plt.plot(test_multi['T']) plt.plot(predictions_multi.iloc[:,0:1], '--') plt.show() plt.plot(train_multi['C6H6(GT)']) plt.plot(test_multi['C6H6(GT)']) plt.plot(predictions_multi.iloc[:,1:2], '--') plt.show() The above code shows how VARMA model can be used to model multivariate time series, although this model may not be best suited on our data. It is an extension of VARMA model where extra variables called covariates are used to model the primary variable we are interested it. This is the extension of ARIMA model to deal with seasonal data. It divides the data into seasonal and non-seasonal components and models them in a similar fashion. It is characterized by 7 parameters, for non-seasonal part (p,d,q) parameters same as for ARIMA model and for seasonal part (P,D,Q,m) parameters where ‘m’ is the number of seasonal periods and P,D,Q are similar to parameters of ARIMA model. These parameters can be calibrated using grid search or genetic algorithm. This is the extension of SARIMA model to include exogenous variables which help us to model the variable we are interested in. It may be useful to do a co-relation analysis on variables before putting them as exogenous variables. In [251]: from scipy.stats.stats import pearsonr x = train_multi['T'].values y = train_multi['C6H6(GT)'].values corr , p = pearsonr(x,y) print ('Corelation Coefficient =', corr,'\nP-Value =',p) Corelation Coefficient = 0.9701173437269858 P-Value = 0.0 Pearson’s Correlation shows a linear relation between 2 variables, to interpret the results, we first look at the p-value, if it is less that 0.05 then the value of coefficient is significant, else the value of coefficient is not significant. For significant p-value, a positive value of correlation coefficient indicates positive correlation, and a negative value indicates a negative correlation. Hence, for our data, ‘temperature’ and ‘C6H6’ seem to have a highly positive correlation. Therefore, we will In [297]: from statsmodels.tsa.statespace.sarimax import SARIMAX model = SARIMAX(x, exog = y, order = (2, 0, 2), seasonal_order = (2, 0, 1, 1), enforce_stationarity=False, enforce_invertibility = False) model_fit = model.fit(disp = False) c:\users\naveksha\appdata\local\programs\python\python37\lib\site-packages\statsmodels\base\model.py:508: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals "Check mle_retvals", ConvergenceWarning) In [298]: y_ = test_multi['C6H6(GT)'].values predicted = model_fit.predict(exog=y_) test_multi_ = pandas.DataFrame(test) test_multi_['predictions'] = predicted[0:1871] In [299]: plt.plot(train_multi['T']) plt.plot(test_multi_['T']) plt.plot(test_multi_.predictions, '--') Out[299]: [<matplotlib.lines.Line2D at 0x1eab0191c18>] The predictions here seem to take larger variations now as opposed to univariate ARIMA modelling. Needless to say, SARIMAX can be used as an ARX, MAX, ARMAX or ARIMAX model by setting only the corresponding parameters to non-zero values. At times, it may happen that our series is not stationary, yet differencing with ‘d’ parameter taking the value 1 may over-difference it. So, we need to difference the time series using a fractional value. In the world of data science there is no one superior model, the model that works on your data depends greatly on your dataset. Knowledge of various models allows us to choose one that work on our data and experimenting with that model to achieve the best results. And results should be seen as plot as well as error metrics, at times a small error may also be bad, hence, plotting and visualizing the results is essential. In the next chapter, we will be looking at another statistical model, exponential smoothing. 16 Lectures 2 hours Malhar Lathkar 21 Lectures 2.5 hours Sasha Miller 19 Lectures 1 hours Sasha Miller 94 Lectures 13 hours Abhishek And Pukhraj 12 Lectures 2 hours Prof. Paul Cline, Ed.D 11 Lectures 1 hours Prof. Paul Cline, Ed.D Print Add Notes Bookmark this page
[ { "code": null, "e": 2355, "s": 2141, "text": "In the previous chapter, we have now seen how ARIMA model works, and its limitations that it cannot handle seasonal data or multivariate time series and hence, new models were introduced to include these features." }, { "code": null, "e": 2401, "s": 2355, "text": "A glimpse of these new models is given here −" }, { "code": null, "e": 2533, "s": 2401, "text": "It is a generalized version of auto regression model for multivariate stationary time series. It is characterized by ‘p’ parameter." }, { "code": null, "e": 2664, "s": 2533, "text": "It is a generalized version of moving average model for multivariate stationary time series. It is characterized by ‘q’ parameter." }, { "code": null, "e": 3092, "s": 2664, "text": "It is the combination of VAR and VMA and a generalized version of ARMA model for multivariate stationary time series. It is characterized by ‘p’ and ‘q’ parameters. Much like, ARMA is capable of acting like an AR model by setting ‘q’ parameter as 0 and as a MA model by setting ‘p’ parameter as 0, VARMA is also capable of acting like an VAR model by setting ‘q’ parameter as 0 and as a VMA model by setting ‘p’ parameter as 0." }, { "code": null, "e": 3102, "s": 3092, "text": "In [209]:" }, { "code": null, "e": 3233, "s": 3102, "text": "df_multi = df[['T', 'C6H6(GT)']]\nsplit = len(df) - int(0.2*len(df))\ntrain_multi, test_multi = df_multi[0:split], df_multi[split:]\n" }, { "code": null, "e": 3243, "s": 3233, "text": "In [211]:" }, { "code": null, "e": 4110, "s": 3243, "text": "from statsmodels.tsa.statespace.varmax import VARMAX\n\nmodel = VARMAX(train_multi, order = (2,1))\nmodel_fit = model.fit()\nc:\\users\\naveksha\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\statsmodels\\tsa\\statespace\\varmax.py:152: \n EstimationWarning: Estimation of VARMA(p,q) models is not generically robust, \n due especially to identification issues. \n EstimationWarning)\nc:\\users\\naveksha\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:171: \n ValueWarning: No frequency information was provided, so inferred frequency H will be used. \n % freq, ValueWarning)\nc:\\users\\naveksha\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\statsmodels\\base\\model.py:508: \n ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals \n \"Check mle_retvals\", ConvergenceWarning)\n" }, { "code": null, "e": 4120, "s": 4110, "text": "In [213]:" }, { "code": null, "e": 4707, "s": 4120, "text": "predictions_multi = model_fit.forecast( steps=len(test_multi))\nc:\\users\\naveksha\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\statsmodels\\tsa\\base\\tsa_model.py:320: \n FutureWarning: Creating a DatetimeIndex by passing range endpoints is deprecated. Use `pandas.date_range` instead.\n freq = base_index.freq)\nc:\\users\\naveksha\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\statsmodels\\tsa\\statespace\\varmax.py:152: \n EstimationWarning: Estimation of VARMA(p,q) models is not generically robust, due especially to identification issues.\n EstimationWarning)\n" }, { "code": null, "e": 4717, "s": 4707, "text": "In [231]:" }, { "code": null, "e": 4953, "s": 4717, "text": "plt.plot(train_multi['T'])\nplt.plot(test_multi['T'])\nplt.plot(predictions_multi.iloc[:,0:1], '--')\nplt.show()\n\nplt.plot(train_multi['C6H6(GT)'])\nplt.plot(test_multi['C6H6(GT)'])\nplt.plot(predictions_multi.iloc[:,1:2], '--')\nplt.show()\n" }, { "code": null, "e": 5093, "s": 4953, "text": "The above code shows how VARMA model can be used to model multivariate time series, although this model may not be best suited on our data." }, { "code": null, "e": 5228, "s": 5093, "text": "It is an extension of VARMA model where extra variables called covariates are used to model the primary variable we are interested it." }, { "code": null, "e": 5709, "s": 5228, "text": "This is the extension of ARIMA model to deal with seasonal data. It divides the data into seasonal and non-seasonal components and models them in a similar fashion. It is characterized by 7 parameters, for non-seasonal part (p,d,q) parameters same as for ARIMA model and for seasonal part (P,D,Q,m) parameters where ‘m’ is the number of seasonal periods and P,D,Q are similar to parameters of ARIMA model. These parameters can be calibrated using grid search or genetic algorithm." }, { "code": null, "e": 5836, "s": 5709, "text": "This is the extension of SARIMA model to include exogenous variables which help us to model the variable we are interested in." }, { "code": null, "e": 5939, "s": 5836, "text": "It may be useful to do a co-relation analysis on variables before putting them as exogenous variables." }, { "code": null, "e": 5949, "s": 5939, "text": "In [251]:" }, { "code": null, "e": 6193, "s": 5949, "text": "from scipy.stats.stats import pearsonr\nx = train_multi['T'].values\ny = train_multi['C6H6(GT)'].values\n\ncorr , p = pearsonr(x,y)\nprint ('Corelation Coefficient =', corr,'\\nP-Value =',p)\nCorelation Coefficient = 0.9701173437269858\nP-Value = 0.0\n" }, { "code": null, "e": 6592, "s": 6193, "text": "Pearson’s Correlation shows a linear relation between 2 variables, to interpret the results, we first look at the p-value, if it is less that 0.05 then the value of coefficient is significant, else the value of coefficient is not significant. For significant p-value, a positive value of correlation coefficient indicates positive correlation, and a negative value indicates a negative correlation." }, { "code": null, "e": 6701, "s": 6592, "text": "Hence, for our data, ‘temperature’ and ‘C6H6’ seem to have a highly positive correlation. Therefore, we will" }, { "code": null, "e": 6711, "s": 6701, "text": "In [297]:" }, { "code": null, "e": 7186, "s": 6711, "text": "from statsmodels.tsa.statespace.sarimax import SARIMAX\n\nmodel = SARIMAX(x, exog = y, order = (2, 0, 2), seasonal_order = (2, 0, 1, 1), enforce_stationarity=False, enforce_invertibility = False)\nmodel_fit = model.fit(disp = False)\nc:\\users\\naveksha\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\statsmodels\\base\\model.py:508: \n ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals\n \"Check mle_retvals\", ConvergenceWarning)\n" }, { "code": null, "e": 7196, "s": 7186, "text": "In [298]:" }, { "code": null, "e": 7355, "s": 7196, "text": "y_ = test_multi['C6H6(GT)'].values\npredicted = model_fit.predict(exog=y_)\ntest_multi_ = pandas.DataFrame(test)\ntest_multi_['predictions'] = predicted[0:1871]\n" }, { "code": null, "e": 7365, "s": 7355, "text": "In [299]:" }, { "code": null, "e": 7460, "s": 7365, "text": "plt.plot(train_multi['T'])\nplt.plot(test_multi_['T'])\nplt.plot(test_multi_.predictions, '--')\n" }, { "code": null, "e": 7470, "s": 7460, "text": "Out[299]:" }, { "code": null, "e": 7516, "s": 7470, "text": "[<matplotlib.lines.Line2D at 0x1eab0191c18>]\n" }, { "code": null, "e": 7614, "s": 7516, "text": "The predictions here seem to take larger variations now as opposed to univariate ARIMA modelling." }, { "code": null, "e": 7754, "s": 7614, "text": "Needless to say, SARIMAX can be used as an ARX, MAX, ARMAX or ARIMAX model by setting only the corresponding parameters to non-zero values." }, { "code": null, "e": 7960, "s": 7754, "text": "At times, it may happen that our series is not stationary, yet differencing with ‘d’ parameter taking the value 1 may over-difference it. So, we need to difference the time series using a fractional value." }, { "code": null, "e": 8384, "s": 7960, "text": "In the world of data science there is no one superior model, the model that works on your data depends greatly on your dataset. Knowledge of various models allows us to choose one that work on our data and experimenting with that model to achieve the best results. And results should be seen as plot as well as error metrics, at times a small error may also be bad, hence, plotting and visualizing the results is essential." }, { "code": null, "e": 8477, "s": 8384, "text": "In the next chapter, we will be looking at another statistical model, exponential smoothing." }, { "code": null, "e": 8510, "s": 8477, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8526, "s": 8510, "text": " Malhar Lathkar" }, { "code": null, "e": 8561, "s": 8526, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8575, "s": 8561, "text": " Sasha Miller" }, { "code": null, "e": 8608, "s": 8575, "text": "\n 19 Lectures \n 1 hours \n" }, { "code": null, "e": 8622, "s": 8608, "text": " Sasha Miller" }, { "code": null, "e": 8656, "s": 8622, "text": "\n 94 Lectures \n 13 hours \n" }, { "code": null, "e": 8678, "s": 8656, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8711, "s": 8678, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 8735, "s": 8711, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 8768, "s": 8735, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8792, "s": 8768, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 8799, "s": 8792, "text": " Print" }, { "code": null, "e": 8810, "s": 8799, "text": " Add Notes" } ]
8085 program to multiply two 16-bit numbers - GeeksforGeeks
19 Feb, 2021 Problem – Write an assembly language program in 8085 microprocessor to multiply two 16 bit numbers. Assumption – Starting address of program: 2000 Input memory location: 2050, 2051, 2052, 2053 Output memory location: 2054, 2055, 2056, 2057 Example – INPUT: (2050H) = 04H (2051H) = 07H (2052H) = 02H (2053H) = 01H OUTPUT: (2054H) = 08H (2055H) = 12H (2056H) = 07H (2057H) = O0H RESULT: Hence we have multiplied two 16 bit numbers. Algorithm – Load the first data in HL pair. Move content of HL pair to stack pointer. Load the second data in HL pair and move it to DE. Make H register as 00H and L register as 00H. ADD HL pair and stack pointer. Check for carry if carry increment it by 1 else move to next step. Then move E to A and perform OR operation with accumulator and register D. The value of operation is zero, then store the value else goto step 3. Load the first data in HL pair. Move content of HL pair to stack pointer. Load the second data in HL pair and move it to DE. Make H register as 00H and L register as 00H. ADD HL pair and stack pointer. Check for carry if carry increment it by 1 else move to next step. Then move E to A and perform OR operation with accumulator and register D. The value of operation is zero, then store the value else goto step 3. Program – Explanation – Registers B, C, D, E, H, L and accumulator are used for general purpose. LHLD 2050: load HL pair with address 2050. SPHL: save the content of HL in stack pointer. LHLD 2052: load H-L pair with address 2052. XCHG: exchange the content of HL pair with DE. LXI H, 0000H: make H as 00H and L as 00H. LXI B, 0000H: make B as 00h and C as 00H DAD SP: ADD HL pair and stack pointer. JNC 2013: jump to address 2013 if there will be no carry. INX B: increments BC register with 1. DCX D: decrements DE register pair by 1. MOV A, E: move the content of register E to accumulator. ORA D: or the content of accumulator and D register. JNZ 200E: jump to address 200E if there will be no zero. SHLD 2054: store the result to memory address 2054 and 2055 from HL pair register. MOV L, C: move the content of register C to L. MOV H, B: move the content of register B to H. SHLD 2056: store the result to memory address 2056 and 2057 from HL pair register. HLT: terminates the program. LHLD 2050: load HL pair with address 2050. SPHL: save the content of HL in stack pointer. LHLD 2052: load H-L pair with address 2052. XCHG: exchange the content of HL pair with DE. LXI H, 0000H: make H as 00H and L as 00H. LXI B, 0000H: make B as 00h and C as 00H DAD SP: ADD HL pair and stack pointer. JNC 2013: jump to address 2013 if there will be no carry. INX B: increments BC register with 1. DCX D: decrements DE register pair by 1. MOV A, E: move the content of register E to accumulator. ORA D: or the content of accumulator and D register. JNZ 200E: jump to address 200E if there will be no zero. SHLD 2054: store the result to memory address 2054 and 2055 from HL pair register. MOV L, C: move the content of register C to L. MOV H, B: move the content of register B to H. SHLD 2056: store the result to memory address 2056 and 2057 from HL pair register. HLT: terminates the program. mayank5464942 suryapandey0211 microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Direct Access Media (DMA) Controller in Computer Architecture Difference between SRAM and DRAM Memory mapped I/O and Isolated I/O Introduction of Control Unit and its Design Difference between Hardwired and Micro-programmed Control Unit | Set 2 General purpose registers in 8086 microprocessor Computer Organization | Basic Computer Instructions
[ { "code": null, "e": 24806, "s": 24778, "text": "\n19 Feb, 2021" }, { "code": null, "e": 24907, "s": 24806, "text": "Problem – Write an assembly language program in 8085 microprocessor to multiply two 16 bit numbers. " }, { "code": null, "e": 24922, "s": 24907, "text": "Assumption – " }, { "code": null, "e": 24958, "s": 24922, "text": "Starting address of program: 2000 " }, { "code": null, "e": 25006, "s": 24958, "text": "Input memory location: 2050, 2051, 2052, 2053 " }, { "code": null, "e": 25055, "s": 25006, "text": "Output memory location: 2054, 2055, 2056, 2057 " }, { "code": null, "e": 25067, "s": 25055, "text": "Example – " }, { "code": null, "e": 25256, "s": 25067, "text": "INPUT:\n (2050H) = 04H\n (2051H) = 07H \n (2052H) = 02H \n (2053H) = 01H\nOUTPUT:\n (2054H) = 08H\n (2055H) = 12H\n (2056H) = 07H\n (2057H) = O0H" }, { "code": null, "e": 25310, "s": 25256, "text": "RESULT: Hence we have multiplied two 16 bit numbers. " }, { "code": null, "e": 25324, "s": 25310, "text": "Algorithm – " }, { "code": null, "e": 25748, "s": 25324, "text": "Load the first data in HL pair. Move content of HL pair to stack pointer. Load the second data in HL pair and move it to DE. Make H register as 00H and L register as 00H. ADD HL pair and stack pointer. Check for carry if carry increment it by 1 else move to next step. Then move E to A and perform OR operation with accumulator and register D. The value of operation is zero, then store the value else goto step 3. " }, { "code": null, "e": 25782, "s": 25748, "text": "Load the first data in HL pair. " }, { "code": null, "e": 25826, "s": 25782, "text": "Move content of HL pair to stack pointer. " }, { "code": null, "e": 25879, "s": 25826, "text": "Load the second data in HL pair and move it to DE. " }, { "code": null, "e": 25927, "s": 25879, "text": "Make H register as 00H and L register as 00H. " }, { "code": null, "e": 25960, "s": 25927, "text": "ADD HL pair and stack pointer. " }, { "code": null, "e": 26029, "s": 25960, "text": "Check for carry if carry increment it by 1 else move to next step. " }, { "code": null, "e": 26106, "s": 26029, "text": "Then move E to A and perform OR operation with accumulator and register D. " }, { "code": null, "e": 26179, "s": 26106, "text": "The value of operation is zero, then store the value else goto step 3. " }, { "code": null, "e": 26190, "s": 26179, "text": "Program – " }, { "code": null, "e": 26281, "s": 26192, "text": "Explanation – Registers B, C, D, E, H, L and accumulator are used for general purpose. " }, { "code": null, "e": 27196, "s": 26281, "text": "LHLD 2050: load HL pair with address 2050. SPHL: save the content of HL in stack pointer. LHLD 2052: load H-L pair with address 2052. XCHG: exchange the content of HL pair with DE. LXI H, 0000H: make H as 00H and L as 00H. LXI B, 0000H: make B as 00h and C as 00H DAD SP: ADD HL pair and stack pointer. JNC 2013: jump to address 2013 if there will be no carry. INX B: increments BC register with 1. DCX D: decrements DE register pair by 1. MOV A, E: move the content of register E to accumulator. ORA D: or the content of accumulator and D register. JNZ 200E: jump to address 200E if there will be no zero. SHLD 2054: store the result to memory address 2054 and 2055 from HL pair register. MOV L, C: move the content of register C to L. MOV H, B: move the content of register B to H. SHLD 2056: store the result to memory address 2056 and 2057 from HL pair register. HLT: terminates the program. " }, { "code": null, "e": 27241, "s": 27196, "text": "LHLD 2050: load HL pair with address 2050. " }, { "code": null, "e": 27290, "s": 27241, "text": "SPHL: save the content of HL in stack pointer. " }, { "code": null, "e": 27336, "s": 27290, "text": "LHLD 2052: load H-L pair with address 2052. " }, { "code": null, "e": 27385, "s": 27336, "text": "XCHG: exchange the content of HL pair with DE. " }, { "code": null, "e": 27429, "s": 27385, "text": "LXI H, 0000H: make H as 00H and L as 00H. " }, { "code": null, "e": 27472, "s": 27429, "text": "LXI B, 0000H: make B as 00h and C as 00H " }, { "code": null, "e": 27513, "s": 27472, "text": "DAD SP: ADD HL pair and stack pointer. " }, { "code": null, "e": 27573, "s": 27513, "text": "JNC 2013: jump to address 2013 if there will be no carry. " }, { "code": null, "e": 27613, "s": 27573, "text": "INX B: increments BC register with 1. " }, { "code": null, "e": 27656, "s": 27613, "text": "DCX D: decrements DE register pair by 1. " }, { "code": null, "e": 27715, "s": 27656, "text": "MOV A, E: move the content of register E to accumulator. " }, { "code": null, "e": 27770, "s": 27715, "text": "ORA D: or the content of accumulator and D register. " }, { "code": null, "e": 27829, "s": 27770, "text": "JNZ 200E: jump to address 200E if there will be no zero. " }, { "code": null, "e": 27914, "s": 27829, "text": "SHLD 2054: store the result to memory address 2054 and 2055 from HL pair register. " }, { "code": null, "e": 27963, "s": 27914, "text": "MOV L, C: move the content of register C to L. " }, { "code": null, "e": 28012, "s": 27963, "text": "MOV H, B: move the content of register B to H. " }, { "code": null, "e": 28097, "s": 28012, "text": "SHLD 2056: store the result to memory address 2056 and 2057 from HL pair register. " }, { "code": null, "e": 28128, "s": 28097, "text": "HLT: terminates the program. " }, { "code": null, "e": 28144, "s": 28130, "text": "mayank5464942" }, { "code": null, "e": 28160, "s": 28144, "text": "suryapandey0211" }, { "code": null, "e": 28175, "s": 28160, "text": "microprocessor" }, { "code": null, "e": 28194, "s": 28175, "text": "system-programming" }, { "code": null, "e": 28231, "s": 28194, "text": "Computer Organization & Architecture" }, { "code": null, "e": 28246, "s": 28231, "text": "microprocessor" }, { "code": null, "e": 28344, "s": 28246, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28353, "s": 28344, "text": "Comments" }, { "code": null, "e": 28366, "s": 28353, "text": "Old Comments" }, { "code": null, "e": 28402, "s": 28366, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 28437, "s": 28402, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 28528, "s": 28437, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 28590, "s": 28528, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 28623, "s": 28590, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 28658, "s": 28623, "text": "Memory mapped I/O and Isolated I/O" }, { "code": null, "e": 28702, "s": 28658, "text": "Introduction of Control Unit and its Design" }, { "code": null, "e": 28773, "s": 28702, "text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2" }, { "code": null, "e": 28822, "s": 28773, "text": "General purpose registers in 8086 microprocessor" } ]
In-Depth Pandas Tutorial. The Ultimate Python library for working... | by Mandy Gu | Towards Data Science
Earlier this month, Edward Qian and I started working on a set of comprehensive lessons for aspiring Data Scientists, which can be found on our website www.dscrashcourse.com I will be cross-posting slightly modified lessons to Medium to make them available to a broader audience. If you find these articles helpful, check out the site for more lessons and practice problems! pandas is a Python library that makes it easy to read, export and work with relational data. This lesson will expand on its functionality and usage. We typically import pandas as pd to refer to the library using the abbreviated form. All of the code shared below was written in Python 3 with pandas==0.24.2 . From the official documentation, a Series is a one-dimensional ndarray with axis labels. A ndarray is a special data type found in the numpy library which defines an array of fixed size elements. In simpler terms, a Series is a column in a table or spreadsheet with the same data type. Each Series has an index used to indicate the axis labels. We can create a Series using pd.Series(['some', 'array', 'object']) We can look up Series values using the axis labels or by their positional labels. If not specified, the Series axis labels (otherwise known as the Series index) will default to integers. We can set the index to strings too. sample_series = pd.Series(['some', 'array', 'object'], index=list('abc')) # positional indexing: this returns the first value, which is 'some'sample_series[0]# label indexing: this also returns the first value 'some'sample_series['a'] This is what the sample_series looks like. We can slice a Series to grab a range of values. Slicing behavior is different when using the axis labels — contrary to usual Python slices, both the start and the endpoint are included! # positional slicing: this returns the first two values sample_series[:2] # label slicing: this also returns the first two valuessample_series[:'b'] DataFrames are used to define two-dimensional data. Rows are labelled using indices and columns are labelled using column headers. Each column can be interpreted as a Series. We can create a DataFrame using pd.DataFrame({'column 1': [1, 1], 'column 2': [2, 2]}). Alternatively, we can also read tabular data into DataFrames. # Read in a CSV filecsv_dataframe = pd.read_csv('my_csv_file.csv') # Read in an Excel filexls_dataframe = pd.read_excel('my_xls_file.xls') We can index DataFrame columns using square brackets. Let’s use the very simple DataFrame we created as an example. sample_dataframe = pd.DataFrame({'column 1': [1, 1], 'column 2': [2, 2]}) # get the column 'column 1'sample_dataframe['column 1'] For more complex indexing, we can use .iloc or .loc. loc is a label based approach to indexing, which requires the name of the row(s) and column(s) iloc is a positional based approach to indexing, which requires the positions of the value(s) Because we did not specify the axis labels for the rows, they adopted the default integer values. As such, the positional labels and axis labels are the same for this DataFrame. We can retrieve the first row using either of these: sample_dataframe.iloc[0, :]sample_dataframe.loc[0, :] Let’s create another DataFrame to illustrate some of the functionalities. We can pretend that this data is taken from a company that distributes education materials. data = pd.DataFrame({'customer_id': [1,2,3,4,5,6,7,8], 'age': [29,43,22,82,41,33,63,57], 'email_linked': [True,True,False,True,False,False,True,True], 'occupation': ['teacher','highschool teacher','student','retired', 'tutor','unemployed','entrepreneur','professor']}) For larger DataFrames, we can use.head(n) to look at the first n rows. To see the last few rows, we can perform a similar operation using .tail(n). Neither are necessary for our small dataset, but we can still demonstrate using data.head(3). Assume that we want to run an email campaign. We start by extracting relevant columns to conduct our campaign. # use double brackets to index multiple columns, single brackets for one columnemail_data = data[['customer_id', 'email_linked']] Not all of the customers have emails linked, so we definitely want to exclude those that don’t. # the condition goes inside the square brackets email_data = email_data[email_data['email_linked']] Let’s write a very simple function to determine if a customer is an educator. This is how we define an educator. def is_educator(occupation): return 'teacher' in occupation.lower() or occupation.lower() in ['tutor', 'professor', 'lecturer'] We can apply this function onto the occupation column to create a new column. data['is_educator'] = data['occupation'].apply(is_educator) We can also transform all the rows in each column of a DataFrame. This requires that we set axis=0 (which is also the default setting). We can write a column-wise function to remove any columns that contain missing values. This is for demonstration only -- there are better ways to handle missing values (see the official Pandas documentation). def remove_missing_columns(col): if col.isnull().values.any(): return coldata.apply(remove_missing_columns, axis=0) We can also apply a function to transform every column in a row. This requires that we set axis=1. def is_educator_above_50(row): return row['age'] > 50 and is_educator(row['occupation'])data['is_educator_above_50'] = data.apply(is_educator_above_50, axis=1) Groupby operations are useful for analyzing Pandas objects and engineering new features from large amounts of data. All groupby operations can be broken down into the following steps: Split the object into groups Apply a function onto each group Combine the results Typically, the object is split based on some criteria, a summary statistic is calculated for each group and combined into a larger object. We can use a groupby operation to calculate the average age for each occupation. Split the DataFrame by occupation Apply a mean function onto each occupation Combine the mean ages into its own object The code for this operation is very simple: data.groupby(by=['occupation']).mean()['age'] The by parameter indicates how groups are determined, mean() is the statistic of interest and indexing by age grabs the group statistic for age. The output is a series where occupation are the axis labels. We can split groups using multiple parameters, for instance, a combination of occupation and whether or not their email is linked: data.groupby(by=['email_linked', 'occupation']).mean()['age'] In addition to mean, there are other built-in functions that we can apply to each group: min, max, count, sum just to name a few. We can also use agg() to apply any custom functions. The aggregation method is also useful for returning multiple summary statistics. For instance, data.groupby(by=['occupation']).agg(['mean', 'sum'])['age'] will return the average age as well as the sum of age for each group. These attributes help us explore and get familiar with new DataFrames. data.columns returns a list of all the columns data.shape returns the dimensions in the form of (number of rows, number of columns) data.dtypes returns the data types of each column data.index returns the range of the index values Refer to the official pandas documentation for syntax, usage and more examples. Book: Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython If you enjoyed this article, you might want to check out my other articles on Data Science, Math and Programming. Follow me on Medium for the latest updates!
[ { "code": null, "e": 345, "s": 171, "text": "Earlier this month, Edward Qian and I started working on a set of comprehensive lessons for aspiring Data Scientists, which can be found on our website www.dscrashcourse.com" }, { "code": null, "e": 546, "s": 345, "text": "I will be cross-posting slightly modified lessons to Medium to make them available to a broader audience. If you find these articles helpful, check out the site for more lessons and practice problems!" }, { "code": null, "e": 855, "s": 546, "text": "pandas is a Python library that makes it easy to read, export and work with relational data. This lesson will expand on its functionality and usage. We typically import pandas as pd to refer to the library using the abbreviated form. All of the code shared below was written in Python 3 with pandas==0.24.2 ." }, { "code": null, "e": 1200, "s": 855, "text": "From the official documentation, a Series is a one-dimensional ndarray with axis labels. A ndarray is a special data type found in the numpy library which defines an array of fixed size elements. In simpler terms, a Series is a column in a table or spreadsheet with the same data type. Each Series has an index used to indicate the axis labels." }, { "code": null, "e": 1268, "s": 1200, "text": "We can create a Series using pd.Series(['some', 'array', 'object'])" }, { "code": null, "e": 1492, "s": 1268, "text": "We can look up Series values using the axis labels or by their positional labels. If not specified, the Series axis labels (otherwise known as the Series index) will default to integers. We can set the index to strings too." }, { "code": null, "e": 1727, "s": 1492, "text": "sample_series = pd.Series(['some', 'array', 'object'], index=list('abc')) # positional indexing: this returns the first value, which is 'some'sample_series[0]# label indexing: this also returns the first value 'some'sample_series['a']" }, { "code": null, "e": 1770, "s": 1727, "text": "This is what the sample_series looks like." }, { "code": null, "e": 1957, "s": 1770, "text": "We can slice a Series to grab a range of values. Slicing behavior is different when using the axis labels — contrary to usual Python slices, both the start and the endpoint are included!" }, { "code": null, "e": 2107, "s": 1957, "text": "# positional slicing: this returns the first two values sample_series[:2] # label slicing: this also returns the first two valuessample_series[:'b']" }, { "code": null, "e": 2370, "s": 2107, "text": "DataFrames are used to define two-dimensional data. Rows are labelled using indices and columns are labelled using column headers. Each column can be interpreted as a Series. We can create a DataFrame using pd.DataFrame({'column 1': [1, 1], 'column 2': [2, 2]})." }, { "code": null, "e": 2432, "s": 2370, "text": "Alternatively, we can also read tabular data into DataFrames." }, { "code": null, "e": 2571, "s": 2432, "text": "# Read in a CSV filecsv_dataframe = pd.read_csv('my_csv_file.csv') # Read in an Excel filexls_dataframe = pd.read_excel('my_xls_file.xls')" }, { "code": null, "e": 2687, "s": 2571, "text": "We can index DataFrame columns using square brackets. Let’s use the very simple DataFrame we created as an example." }, { "code": null, "e": 2817, "s": 2687, "text": "sample_dataframe = pd.DataFrame({'column 1': [1, 1], 'column 2': [2, 2]}) # get the column 'column 1'sample_dataframe['column 1']" }, { "code": null, "e": 2870, "s": 2817, "text": "For more complex indexing, we can use .iloc or .loc." }, { "code": null, "e": 2965, "s": 2870, "text": "loc is a label based approach to indexing, which requires the name of the row(s) and column(s)" }, { "code": null, "e": 3059, "s": 2965, "text": "iloc is a positional based approach to indexing, which requires the positions of the value(s)" }, { "code": null, "e": 3237, "s": 3059, "text": "Because we did not specify the axis labels for the rows, they adopted the default integer values. As such, the positional labels and axis labels are the same for this DataFrame." }, { "code": null, "e": 3290, "s": 3237, "text": "We can retrieve the first row using either of these:" }, { "code": null, "e": 3344, "s": 3290, "text": "sample_dataframe.iloc[0, :]sample_dataframe.loc[0, :]" }, { "code": null, "e": 3510, "s": 3344, "text": "Let’s create another DataFrame to illustrate some of the functionalities. We can pretend that this data is taken from a company that distributes education materials." }, { "code": null, "e": 3876, "s": 3510, "text": "data = pd.DataFrame({'customer_id': [1,2,3,4,5,6,7,8], 'age': [29,43,22,82,41,33,63,57], 'email_linked': [True,True,False,True,False,False,True,True], 'occupation': ['teacher','highschool teacher','student','retired', 'tutor','unemployed','entrepreneur','professor']})" }, { "code": null, "e": 4118, "s": 3876, "text": "For larger DataFrames, we can use.head(n) to look at the first n rows. To see the last few rows, we can perform a similar operation using .tail(n). Neither are necessary for our small dataset, but we can still demonstrate using data.head(3)." }, { "code": null, "e": 4229, "s": 4118, "text": "Assume that we want to run an email campaign. We start by extracting relevant columns to conduct our campaign." }, { "code": null, "e": 4359, "s": 4229, "text": "# use double brackets to index multiple columns, single brackets for one columnemail_data = data[['customer_id', 'email_linked']]" }, { "code": null, "e": 4455, "s": 4359, "text": "Not all of the customers have emails linked, so we definitely want to exclude those that don’t." }, { "code": null, "e": 4555, "s": 4455, "text": "# the condition goes inside the square brackets email_data = email_data[email_data['email_linked']]" }, { "code": null, "e": 4668, "s": 4555, "text": "Let’s write a very simple function to determine if a customer is an educator. This is how we define an educator." }, { "code": null, "e": 4799, "s": 4668, "text": "def is_educator(occupation): return 'teacher' in occupation.lower() or occupation.lower() in ['tutor', 'professor', 'lecturer']" }, { "code": null, "e": 4877, "s": 4799, "text": "We can apply this function onto the occupation column to create a new column." }, { "code": null, "e": 4937, "s": 4877, "text": "data['is_educator'] = data['occupation'].apply(is_educator)" }, { "code": null, "e": 5282, "s": 4937, "text": "We can also transform all the rows in each column of a DataFrame. This requires that we set axis=0 (which is also the default setting). We can write a column-wise function to remove any columns that contain missing values. This is for demonstration only -- there are better ways to handle missing values (see the official Pandas documentation)." }, { "code": null, "e": 5408, "s": 5282, "text": "def remove_missing_columns(col): if col.isnull().values.any(): return coldata.apply(remove_missing_columns, axis=0)" }, { "code": null, "e": 5507, "s": 5408, "text": "We can also apply a function to transform every column in a row. This requires that we set axis=1." }, { "code": null, "e": 5670, "s": 5507, "text": "def is_educator_above_50(row): return row['age'] > 50 and is_educator(row['occupation'])data['is_educator_above_50'] = data.apply(is_educator_above_50, axis=1)" }, { "code": null, "e": 5854, "s": 5670, "text": "Groupby operations are useful for analyzing Pandas objects and engineering new features from large amounts of data. All groupby operations can be broken down into the following steps:" }, { "code": null, "e": 5883, "s": 5854, "text": "Split the object into groups" }, { "code": null, "e": 5916, "s": 5883, "text": "Apply a function onto each group" }, { "code": null, "e": 5936, "s": 5916, "text": "Combine the results" }, { "code": null, "e": 6156, "s": 5936, "text": "Typically, the object is split based on some criteria, a summary statistic is calculated for each group and combined into a larger object. We can use a groupby operation to calculate the average age for each occupation." }, { "code": null, "e": 6190, "s": 6156, "text": "Split the DataFrame by occupation" }, { "code": null, "e": 6233, "s": 6190, "text": "Apply a mean function onto each occupation" }, { "code": null, "e": 6275, "s": 6233, "text": "Combine the mean ages into its own object" }, { "code": null, "e": 6365, "s": 6275, "text": "The code for this operation is very simple: data.groupby(by=['occupation']).mean()['age']" }, { "code": null, "e": 6571, "s": 6365, "text": "The by parameter indicates how groups are determined, mean() is the statistic of interest and indexing by age grabs the group statistic for age. The output is a series where occupation are the axis labels." }, { "code": null, "e": 6764, "s": 6571, "text": "We can split groups using multiple parameters, for instance, a combination of occupation and whether or not their email is linked: data.groupby(by=['email_linked', 'occupation']).mean()['age']" }, { "code": null, "e": 7028, "s": 6764, "text": "In addition to mean, there are other built-in functions that we can apply to each group: min, max, count, sum just to name a few. We can also use agg() to apply any custom functions. The aggregation method is also useful for returning multiple summary statistics." }, { "code": null, "e": 7172, "s": 7028, "text": "For instance, data.groupby(by=['occupation']).agg(['mean', 'sum'])['age'] will return the average age as well as the sum of age for each group." }, { "code": null, "e": 7243, "s": 7172, "text": "These attributes help us explore and get familiar with new DataFrames." }, { "code": null, "e": 7290, "s": 7243, "text": "data.columns returns a list of all the columns" }, { "code": null, "e": 7375, "s": 7290, "text": "data.shape returns the dimensions in the form of (number of rows, number of columns)" }, { "code": null, "e": 7425, "s": 7375, "text": "data.dtypes returns the data types of each column" }, { "code": null, "e": 7474, "s": 7425, "text": "data.index returns the range of the index values" }, { "code": null, "e": 7554, "s": 7474, "text": "Refer to the official pandas documentation for syntax, usage and more examples." }, { "code": null, "e": 7633, "s": 7554, "text": "Book: Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython" } ]
Difference between TimeSpan Seconds() and TotalSeconds()
TimeSpan Seconds() is part of time, whereas TimeSpan TotalSeconds() converts entire time to seconds. Let us first see the TimeSpan Seconds() method. Live Demo using System; using System.Linq; public class Demo { public static void Main() { TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0); // seconds Console.WriteLine(ts.Seconds); } } 20 Now, let us see how TotalSeconds works for the same TimeSpan value. Live Demo using System; using System.Linq; public class Demo { public static void Main() { TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0); // total seconds Console.WriteLine(ts.TotalSeconds); } } 360020 Now, we will see both of them in the same example. Live Demo using System; using System.Linq; public class Demo { public static void Main() { TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0); // seconds Console.WriteLine(ts.Seconds); // total seconds Console.WriteLine(ts.TotalSeconds); } } 20 360020
[ { "code": null, "e": 1163, "s": 1062, "text": "TimeSpan Seconds() is part of time, whereas TimeSpan TotalSeconds() converts entire time to seconds." }, { "code": null, "e": 1211, "s": 1163, "text": "Let us first see the TimeSpan Seconds() method." }, { "code": null, "e": 1222, "s": 1211, "text": " Live Demo" }, { "code": null, "e": 1419, "s": 1222, "text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0);\n // seconds\n Console.WriteLine(ts.Seconds);\n }\n}" }, { "code": null, "e": 1422, "s": 1419, "text": "20" }, { "code": null, "e": 1490, "s": 1422, "text": "Now, let us see how TotalSeconds works for the same TimeSpan value." }, { "code": null, "e": 1501, "s": 1490, "text": " Live Demo" }, { "code": null, "e": 1709, "s": 1501, "text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0);\n // total seconds\n Console.WriteLine(ts.TotalSeconds);\n }\n}" }, { "code": null, "e": 1716, "s": 1709, "text": "360020" }, { "code": null, "e": 1767, "s": 1716, "text": "Now, we will see both of them in the same example." }, { "code": null, "e": 1778, "s": 1767, "text": " Live Demo" }, { "code": null, "e": 2040, "s": 1778, "text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n TimeSpan ts = new TimeSpan(0, 100, 0, 20, 0);\n // seconds\n Console.WriteLine(ts.Seconds);\n // total seconds\n Console.WriteLine(ts.TotalSeconds);\n }\n}" }, { "code": null, "e": 2050, "s": 2040, "text": "20\n360020" } ]
[TUTORIAL]: Deploy ML model as REST API on Azure and protect it with SSL | by Ivan Zidov | Towards Data Science
Data Scientists often forget that their new awesome models aren’t so useful if they can't be used in production. In this tutorial, I will show you how you can deploy Tensorflow model to Azure Container Instances and protect it with SSL. There will be 3 types of deployment: Deployment #1: Local deployment:Model will be put in a docker container and exposed as an API on localhost. Deployment #2: Global deployment without encryption:Docker containing model will be uploaded to Azure Container Registry. The stored container will be exposed thought an API that you can call. The downside to that is that everyone can access it if they have the IP address and it is not encrypted. Deployment #3: Global deployment encrypted with SSL:Docker containing model will be uploaded to Azure Container Registry. We will create Certificate Authority (CA) and self-signed certificates for API usage. Linux machine with sudo options Docker installed on Linux Azure CLI installed on Linux openssl installed on Linux Valid subscription for Azure NOTE: If you don’t have valid subscription, you can create a free account for Azure and receive 2 weeks of Trial period. Train Tensorflow model and save it with:tf.saved_model.save(model, "path / to / model") OR: Here is a demo model that represents f(x)= 2*x -1. It was saved to “./demo_model/” import os import numpy as np import tensorflow as tf xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float) model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') history = model.fit(xs, ys, epochs=500, verbose=0) print("Finished training the model") MODEL_DIR = "./demo_model" version = 1 export_path = os.path.join(MODEL_DIR, str(version)) model.save(export_path, save_format="tf") print('\nexport_path = {}'.format(export_path)) I won’t go into the details of Tensorflow Serving because there is a great Coursera course. This code is used above is code used from this course, but only compressed for this demo. You can learn more about TFServing from here. Open terminal and navigate to the directory where you have saved the model. $ MODEL_NAME=demo_model #REPLACE with your model$ MODEL_PATH="./$MODEL_NAME"$ CONTAINER_NAME="$MODEL_NAME"$ sudo docker run -d --name serving_base tensorflow/serving$ sudo docker cp "$MODEL_PATH" serving_base:"/models/$MODEL_NAME"$ sudo docker commit --change "ENV MODEL_NAME $MODEL_NAME" serving_base "$CONTAINER_NAME"$ sudo docker run -d -p 8501:8501 "$MODEL_NAME" Now you have your model exposed thought an API on localhost, and you can be call it from terminal: $ curl -d '{"signature_name": "serving_default", "instances": [[10.0],[9.0]]}' -X POST "http://localhost:8501/v1/models/$MODEL_NAME:predict" Or from python: import requests import json api_url = "http://localhost:8501/v1/models/demo_model:predict" data = json.dumps({"signature_name": "serving_default", "instances": [[10.0],[9.0]]}) headers = {"content-type": "application/json"} json_response = requests.post(api_url, data=data, headers=headers) print(json_response.text) #STOP docker imagesudo docker container stop IMAGE_ID #DELETE docker image sudo docker container rm IMAGE_ID Deployment #1: COMPLETED! You can now use your model in localhost. BONUS TIP: Another option is port forwarding. You connect to the machine with SSH. ssh -N -f -L localhost:8501:localhost:8501 [email protected] DOWNSIDES: You can only use it locally You need a VPN access to use port forwarding Not scalable Used to store containers with models.Go to Azure portal and find Container Registries. Click on Add new registry button to create a new registry. IMPORTANT: Pick a valid Subscription and Resource group. Registry name has to be unique, and we will also be needing it later so take note of it. (TIP: use lowercase only) Location is mandatory and you should pick the one closest to you Basic SKU should be enough for most cases. You can now click on Review and Create this registry button. IMPORTANT: Navigate to your resource and enable admin user. Take a note of username and password. $ CONTAINER_REGISTRY_NAME=blogdemo #REPLACE (lower letters only)$ sudo az login #login to Azure$ sudo az acr login --name "$CONTAINER_REGISTRY_NAME" $ sudo docker images $ VERSION_NAME="$CONTAINER_REGISTRY_NAME.azurecr.io/version1"$ sudo docker tag 2b458f67dac3 "$VERSION_NAME" #REPLACE$ sudo docker push "$VERSION_NAME" Congrats:You have successfully stored the container with the model After storing the container, it is fairly easy to expose the model. The easiest way is to log in to Azure portal, navigate to Container Instances and click Add button. After naming the container, pick a desired region and choose the registry where you have uploaded the model. NOTE:Size really depends on your model size. The size used in this example is more than enough for this model. I have deployed the model with ~150M parameters (600MB) and it needed 2 vcpu and 4 GB of memory. Now click on Next: Networking button. NOTE: DNS name is optional and it needs to be unique. Click on Review and Create and your model is ready to be used. (To delete an instance just navigate to resource and click on Delete button) USAGE: $ curl -d '{"signature_name": "serving_default", "instances": [[10.0],[9.0]]}' -X POST "http://blogdemo.westeurope.azurecontainer.io:8501/v1/models/$MODEL_NAME:predict" #REPLACE blogdemo.westeurope.azurecontainer.io WITH DNS#OR:$ curl -d '{"signature_name": "serving_default", "instances": [[10.0],[9.0]]}' -X POST "http://IP.ADDRESS:8501/v1/models/$MODEL_NAME:predict" #REPLACE IP.ADDRESS WITH IP Using the model is the same as using the one exposed locally, only difference being the URL. You can use a DNS URL or an IP URL. Deployment #2: COMPLETED! You have deployed a model that can be used over the Internet. You can monitor usage of model and upgrade the size of the container if needed, which makes it scalable. DOWNSIDES: Everyone who knows the IP-ADDRESS can access the model Not encrypted To protect API, we will need encryption. If you use commercial Certificate Authority, you can skip this step. We will create our own and self-sign certificates. $ mkdir certs $ cd certs $ openssl ecparam -genkey -name secp256r1 | openssl ec -out ca.key $ openssl req -new -x509 -days 3650 -key ca.key -out ca.pem You will be prompted to fill-out the form. Fill it out with your information. NOTE:This is an example of elliptic encryption for simplicity. I recommend using an RSA key. This is a great gist that explains how to do it. $ CLIENT_ID=”client”$ CLIENT_SERIAL=01 #when creating new user make sure that serial is unique$ openssl ecparam -genkey -name secp256r1 | openssl ec -out “${CLIENT_ID}.key”$ openssl req -new -key “${CLIENT_ID}.key” -out “${CLIENT_ID}.csr” #password should be empty$ openssl x509 -req -days 3650 -in “${CLIENT_ID}.csr” -CA ca.pem -CAkey ca.key -set_serial “${CLIENT_SERIAL}” -out “${CLIENT_ID}.pem”$ cat “${CLIENT_ID}.key” “${CLIENT_ID}.pem” ca.pem > “${CLIENT_ID}.full.pem”#OPTIONAL:$ openssl pkcs12 -export -out “${CLIENT_ID}.full.pfx” -inkey “${CLIENT_ID}.key” -in “${CLIENT_ID}.pem” -certfile ca.pem#remember passoword and you will pass it with pfx file Why do we need NGINX? To reject all requests that don’t have a valid certificate. Create nginx.config file as follows: $ cd ..$ cat > nginx.conf Copy everything and paste it to a file. After pasting use CTRL+D to close editor. user nginx;worker_processes auto;events { worker_connections 1024;}pid /var/run/nginx.pid;http {server { listen [::]:443 ssl; listen 443 ssl;server_name localhost;ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK; ssl_prefer_server_ciphers on;ssl_session_cache shared:SSL:10m; # a 1mb cache can hold about 4000 sessions, so we can hold 40000 sessions ssl_session_timeout 24h;keepalive_timeout 300; # up from 75 secs defaultadd_header Strict-Transport-Security 'max-age=31536000; includeSubDomains';ssl_certificate /etc/nginx/server.pem; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/ca.pem; ssl_verify_client on; location / { proxy_pass http://localhost:8501; # TODO: replace with correct port proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; } }} I won’t go into the details of NGINX, but here is the link for the details. This configuration is a mixture of this blog and this article. In a nutshell, it only listens to https (port 443) and validates certificate that it receives. If a certificate is valid, it redirects decrypted request to container with model and encrypts response that is sent back to client. Create test-deploy.yaml file for Azure: $ cat > test-deploy.yaml Copy everything and paste it to a file. After pasting use CTRL+D to close editor. location: LOCATIONname: NAMEproperties: containers: - name: model properties: image: IMAGE.azurecr.io/version1:latest ports: - port: 8501 protocol: TCP resources: requests: cpu: 1.0 memoryInGB: 1.5 - name: nginx-with-ssl properties: image: nginx ports: - port: 443 protocol: TCP resources: requests: cpu: 1.0 memoryInGB: 1.5 volumeMounts: - name: nginx-config mountPath: /etc/nginx imageRegistryCredentials: - server: SERVER.azurecr.io username: USERNAME password: PASSWORD volumes: - secret: server.pem: PEM server.key: KEY ca.pem: CA nginx.conf: CONF name: nginx-config ipAddress: ports: - port: 443 protocol: TCP type: Public dnsNameLabel: DNS osType: Linuxtags: nulltype: Microsoft.ContainerInstance/containerGroups We will use the sed command to replace parts of this template. These are the commands that you can run without editing. $ sed -i -e "s/name: NAME/name: $MODEL_NAME/" azure.yaml$ sed -i -e "s/image: IMAGE/image: $CONTAINER_REGISTRY_NAME/" azure.yaml$ sed -i -e "s/server: SERVER/server: $CONTAINER_REGISTRY_NAME/" azure.yaml$ sed -i -e "s/username: USERNAME/username: $CONTAINER_REGISTRY_NAME/" azure.yaml$ sed -i -e "s/server.pem: PEM/server.pem: $(cat ./certs/ca.pem | base64 -w 0)/" azure.yaml$ sed -i -e "s/server.key: KEY/server.key: $(cat ./certs/ca.key| base64 -w 0)/" azure.yaml$ sed -i -e "s/ca.pem: CA/ca.pem: $(cat ./certs/ca.pem | base64 -w 0)/" azure.yaml$ sed -i -e "s/nginx.conf: CONF/nginx.conf: $(cat ./nginx.conf | base64 -w 0)/" azure.yaml These commands have to be edited. Replace the bolded parts with location and password from the registry and use your DNS to replace DNS_NAME. $ sed -i -e "s/location: LOCATION/location: westeurope/" azure.yaml$ sed -i -e "s/password: PASSWORD/password: REGISTRY_PASS/" azure.yaml#TIP: If your generated password has some special characters#like / you will have to manually put \/ infront$ sed -i -e "s/dnsNameLabel: DNS/dnsNameLabel: DNS_NAME/" azure.yaml Replace <AZURE RESOURCE GROUP> with your valid resource group and you are ready to go. $ az container create --resource-group <AZURE RESOURCE GROUP> --name "$MODEL_NAME" -f azure.yaml Make sure that you have a proper path to client.key and client.pem and you can proceed to call the API like this: $ curl -d '{"signature_name": "serving_default", "instances": [[10.0],[9.0]]}' -v --key "./certs/client.key" --cert "./certs/client.full.pem" -X POST -k https://blogdemo.westeurope.azurecontainer.io/v1/models/demo_model:predict#REPLACE blogdemo.westeurope.azurecontainer.io WITH DNS#OR:$ curl -d '{"signature_name": "serving_default", "instances": [[10.0],[9.0]]}' -v --key "./certs/client.key" --cert "./certs/client.full.pem" -X POST -k https://IP.ADDRESS/v1/models/demo_model:predict#REPLACE IP.ADDRESS WITH IP If everything works fine you will get a response like this one: IMPORTANT: Since this is a self-signed certificate, you must add -k flag in cURL. Python version: import requests import jsonapi_url = "https://blogdemo.westeurope.azurecontainer.io/v1/models/demo_model:predict"data = json.dumps({"signature_name": "serving_default", "instances": [[10.0],[9.0]]})headers = {"content-type": "application/json"}json_response = requests.post(api_url, data=data, headers=headers,verify=False,cert=("./certs/client.pem","./certs/client.key"),)print(json_response.text) IMPORTANT: Since this is a self-signed certificate, you must set verify=False When called without a valid certificate: Deployment #3: COMPLETED! You can monitor the usage of the model in Container Instance and you can see request made in nginx logs. Q: Can I deploy a custom model (without TF Serving)?A: Yes. You have to dockerize the model and if you use the right ports, everything else should work as expected. Q: Can I deploy it to AWS?A: Yes, by using nginx.config and CA configuration seen in this blog. Q: Can I store the container on Docker Hub?A: Yes. Just replace image with username/repo:version from Docker Hub and remove imageRegistryCredentials from YAML file.
[ { "code": null, "e": 409, "s": 172, "text": "Data Scientists often forget that their new awesome models aren’t so useful if they can't be used in production. In this tutorial, I will show you how you can deploy Tensorflow model to Azure Container Instances and protect it with SSL." }, { "code": null, "e": 446, "s": 409, "text": "There will be 3 types of deployment:" }, { "code": null, "e": 554, "s": 446, "text": "Deployment #1: Local deployment:Model will be put in a docker container and exposed as an API on localhost." }, { "code": null, "e": 852, "s": 554, "text": "Deployment #2: Global deployment without encryption:Docker containing model will be uploaded to Azure Container Registry. The stored container will be exposed thought an API that you can call. The downside to that is that everyone can access it if they have the IP address and it is not encrypted." }, { "code": null, "e": 1060, "s": 852, "text": "Deployment #3: Global deployment encrypted with SSL:Docker containing model will be uploaded to Azure Container Registry. We will create Certificate Authority (CA) and self-signed certificates for API usage." }, { "code": null, "e": 1092, "s": 1060, "text": "Linux machine with sudo options" }, { "code": null, "e": 1118, "s": 1092, "text": "Docker installed on Linux" }, { "code": null, "e": 1147, "s": 1118, "text": "Azure CLI installed on Linux" }, { "code": null, "e": 1174, "s": 1147, "text": "openssl installed on Linux" }, { "code": null, "e": 1203, "s": 1174, "text": "Valid subscription for Azure" }, { "code": null, "e": 1324, "s": 1203, "text": "NOTE: If you don’t have valid subscription, you can create a free account for Azure and receive 2 weeks of Trial period." }, { "code": null, "e": 1412, "s": 1324, "text": "Train Tensorflow model and save it with:tf.saved_model.save(model, \"path / to / model\")" }, { "code": null, "e": 1416, "s": 1412, "text": "OR:" }, { "code": null, "e": 1499, "s": 1416, "text": "Here is a demo model that represents f(x)= 2*x -1. It was saved to “./demo_model/”" }, { "code": null, "e": 2083, "s": 1499, "text": "import os import numpy as np import tensorflow as tf xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float) model = tf.keras.Sequential([tf.keras.layers.Dense(units=1, input_shape=[1])]) model.compile(optimizer='sgd', loss='mean_squared_error') history = model.fit(xs, ys, epochs=500, verbose=0) print(\"Finished training the model\") MODEL_DIR = \"./demo_model\" version = 1 export_path = os.path.join(MODEL_DIR, str(version)) model.save(export_path, save_format=\"tf\") print('\\nexport_path = {}'.format(export_path))" }, { "code": null, "e": 2311, "s": 2083, "text": "I won’t go into the details of Tensorflow Serving because there is a great Coursera course. This code is used above is code used from this course, but only compressed for this demo. You can learn more about TFServing from here." }, { "code": null, "e": 2387, "s": 2311, "text": "Open terminal and navigate to the directory where you have saved the model." }, { "code": null, "e": 2754, "s": 2387, "text": "$ MODEL_NAME=demo_model #REPLACE with your model$ MODEL_PATH=\"./$MODEL_NAME\"$ CONTAINER_NAME=\"$MODEL_NAME\"$ sudo docker run -d --name serving_base tensorflow/serving$ sudo docker cp \"$MODEL_PATH\" serving_base:\"/models/$MODEL_NAME\"$ sudo docker commit --change \"ENV MODEL_NAME $MODEL_NAME\" serving_base \"$CONTAINER_NAME\"$ sudo docker run -d -p 8501:8501 \"$MODEL_NAME\"" }, { "code": null, "e": 2853, "s": 2754, "text": "Now you have your model exposed thought an API on localhost, and you can be call it from terminal:" }, { "code": null, "e": 2994, "s": 2853, "text": "$ curl -d '{\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]}' -X POST \"http://localhost:8501/v1/models/$MODEL_NAME:predict\"" }, { "code": null, "e": 3010, "s": 2994, "text": "Or from python:" }, { "code": null, "e": 3327, "s": 3010, "text": "import requests import json api_url = \"http://localhost:8501/v1/models/demo_model:predict\" data = json.dumps({\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]}) headers = {\"content-type\": \"application/json\"} json_response = requests.post(api_url, data=data, headers=headers) print(json_response.text)" }, { "code": null, "e": 3437, "s": 3327, "text": "#STOP docker imagesudo docker container stop IMAGE_ID #DELETE docker image sudo docker container rm IMAGE_ID" }, { "code": null, "e": 3463, "s": 3437, "text": "Deployment #1: COMPLETED!" }, { "code": null, "e": 3504, "s": 3463, "text": "You can now use your model in localhost." }, { "code": null, "e": 3587, "s": 3504, "text": "BONUS TIP: Another option is port forwarding. You connect to the machine with SSH." }, { "code": null, "e": 3646, "s": 3587, "text": "ssh -N -f -L localhost:8501:localhost:8501 [email protected]" }, { "code": null, "e": 3657, "s": 3646, "text": "DOWNSIDES:" }, { "code": null, "e": 3685, "s": 3657, "text": "You can only use it locally" }, { "code": null, "e": 3730, "s": 3685, "text": "You need a VPN access to use port forwarding" }, { "code": null, "e": 3743, "s": 3730, "text": "Not scalable" }, { "code": null, "e": 3889, "s": 3743, "text": "Used to store containers with models.Go to Azure portal and find Container Registries. Click on Add new registry button to create a new registry." }, { "code": null, "e": 3900, "s": 3889, "text": "IMPORTANT:" }, { "code": null, "e": 3946, "s": 3900, "text": "Pick a valid Subscription and Resource group." }, { "code": null, "e": 4061, "s": 3946, "text": "Registry name has to be unique, and we will also be needing it later so take note of it. (TIP: use lowercase only)" }, { "code": null, "e": 4126, "s": 4061, "text": "Location is mandatory and you should pick the one closest to you" }, { "code": null, "e": 4169, "s": 4126, "text": "Basic SKU should be enough for most cases." }, { "code": null, "e": 4230, "s": 4169, "text": "You can now click on Review and Create this registry button." }, { "code": null, "e": 4328, "s": 4230, "text": "IMPORTANT: Navigate to your resource and enable admin user. Take a note of username and password." }, { "code": null, "e": 4498, "s": 4328, "text": "$ CONTAINER_REGISTRY_NAME=blogdemo #REPLACE (lower letters only)$ sudo az login #login to Azure$ sudo az acr login --name \"$CONTAINER_REGISTRY_NAME\" $ sudo docker images" }, { "code": null, "e": 4649, "s": 4498, "text": "$ VERSION_NAME=\"$CONTAINER_REGISTRY_NAME.azurecr.io/version1\"$ sudo docker tag 2b458f67dac3 \"$VERSION_NAME\" #REPLACE$ sudo docker push \"$VERSION_NAME\"" }, { "code": null, "e": 4716, "s": 4649, "text": "Congrats:You have successfully stored the container with the model" }, { "code": null, "e": 4784, "s": 4716, "text": "After storing the container, it is fairly easy to expose the model." }, { "code": null, "e": 4993, "s": 4784, "text": "The easiest way is to log in to Azure portal, navigate to Container Instances and click Add button. After naming the container, pick a desired region and choose the registry where you have uploaded the model." }, { "code": null, "e": 5201, "s": 4993, "text": "NOTE:Size really depends on your model size. The size used in this example is more than enough for this model. I have deployed the model with ~150M parameters (600MB) and it needed 2 vcpu and 4 GB of memory." }, { "code": null, "e": 5239, "s": 5201, "text": "Now click on Next: Networking button." }, { "code": null, "e": 5293, "s": 5239, "text": "NOTE: DNS name is optional and it needs to be unique." }, { "code": null, "e": 5433, "s": 5293, "text": "Click on Review and Create and your model is ready to be used. (To delete an instance just navigate to resource and click on Delete button)" }, { "code": null, "e": 5440, "s": 5433, "text": "USAGE:" }, { "code": null, "e": 5838, "s": 5440, "text": "$ curl -d '{\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]}' -X POST \"http://blogdemo.westeurope.azurecontainer.io:8501/v1/models/$MODEL_NAME:predict\" #REPLACE blogdemo.westeurope.azurecontainer.io WITH DNS#OR:$ curl -d '{\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]}' -X POST \"http://IP.ADDRESS:8501/v1/models/$MODEL_NAME:predict\" #REPLACE IP.ADDRESS WITH IP" }, { "code": null, "e": 5967, "s": 5838, "text": "Using the model is the same as using the one exposed locally, only difference being the URL. You can use a DNS URL or an IP URL." }, { "code": null, "e": 5993, "s": 5967, "text": "Deployment #2: COMPLETED!" }, { "code": null, "e": 6160, "s": 5993, "text": "You have deployed a model that can be used over the Internet. You can monitor usage of model and upgrade the size of the container if needed, which makes it scalable." }, { "code": null, "e": 6171, "s": 6160, "text": "DOWNSIDES:" }, { "code": null, "e": 6226, "s": 6171, "text": "Everyone who knows the IP-ADDRESS can access the model" }, { "code": null, "e": 6240, "s": 6226, "text": "Not encrypted" }, { "code": null, "e": 6401, "s": 6240, "text": "To protect API, we will need encryption. If you use commercial Certificate Authority, you can skip this step. We will create our own and self-sign certificates." }, { "code": null, "e": 6553, "s": 6401, "text": "$ mkdir certs $ cd certs $ openssl ecparam -genkey -name secp256r1 | openssl ec -out ca.key $ openssl req -new -x509 -days 3650 -key ca.key -out ca.pem" }, { "code": null, "e": 6631, "s": 6553, "text": "You will be prompted to fill-out the form. Fill it out with your information." }, { "code": null, "e": 6773, "s": 6631, "text": "NOTE:This is an example of elliptic encryption for simplicity. I recommend using an RSA key. This is a great gist that explains how to do it." }, { "code": null, "e": 7430, "s": 6773, "text": "$ CLIENT_ID=”client”$ CLIENT_SERIAL=01 #when creating new user make sure that serial is unique$ openssl ecparam -genkey -name secp256r1 | openssl ec -out “${CLIENT_ID}.key”$ openssl req -new -key “${CLIENT_ID}.key” -out “${CLIENT_ID}.csr” #password should be empty$ openssl x509 -req -days 3650 -in “${CLIENT_ID}.csr” -CA ca.pem -CAkey ca.key -set_serial “${CLIENT_SERIAL}” -out “${CLIENT_ID}.pem”$ cat “${CLIENT_ID}.key” “${CLIENT_ID}.pem” ca.pem > “${CLIENT_ID}.full.pem”#OPTIONAL:$ openssl pkcs12 -export -out “${CLIENT_ID}.full.pfx” -inkey “${CLIENT_ID}.key” -in “${CLIENT_ID}.pem” -certfile ca.pem#remember passoword and you will pass it with pfx file" }, { "code": null, "e": 7452, "s": 7430, "text": "Why do we need NGINX?" }, { "code": null, "e": 7512, "s": 7452, "text": "To reject all requests that don’t have a valid certificate." }, { "code": null, "e": 7549, "s": 7512, "text": "Create nginx.config file as follows:" }, { "code": null, "e": 7575, "s": 7549, "text": "$ cd ..$ cat > nginx.conf" }, { "code": null, "e": 7657, "s": 7575, "text": "Copy everything and paste it to a file. After pasting use CTRL+D to close editor." }, { "code": null, "e": 9349, "s": 7657, "text": "user nginx;worker_processes auto;events { worker_connections 1024;}pid /var/run/nginx.pid;http {server { listen [::]:443 ssl; listen 443 ssl;server_name localhost;ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK; ssl_prefer_server_ciphers on;ssl_session_cache shared:SSL:10m; # a 1mb cache can hold about 4000 sessions, so we can hold 40000 sessions ssl_session_timeout 24h;keepalive_timeout 300; # up from 75 secs defaultadd_header Strict-Transport-Security 'max-age=31536000; includeSubDomains';ssl_certificate /etc/nginx/server.pem; ssl_certificate_key /etc/nginx/server.key; ssl_client_certificate /etc/nginx/ca.pem; ssl_verify_client on; location / { proxy_pass http://localhost:8501; # TODO: replace with correct port proxy_set_header Connection \"\"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; } }}" }, { "code": null, "e": 9716, "s": 9349, "text": "I won’t go into the details of NGINX, but here is the link for the details. This configuration is a mixture of this blog and this article. In a nutshell, it only listens to https (port 443) and validates certificate that it receives. If a certificate is valid, it redirects decrypted request to container with model and encrypts response that is sent back to client." }, { "code": null, "e": 9756, "s": 9716, "text": "Create test-deploy.yaml file for Azure:" }, { "code": null, "e": 9781, "s": 9756, "text": "$ cat > test-deploy.yaml" }, { "code": null, "e": 9863, "s": 9781, "text": "Copy everything and paste it to a file. After pasting use CTRL+D to close editor." }, { "code": null, "e": 10765, "s": 9863, "text": "location: LOCATIONname: NAMEproperties: containers: - name: model properties: image: IMAGE.azurecr.io/version1:latest ports: - port: 8501 protocol: TCP resources: requests: cpu: 1.0 memoryInGB: 1.5 - name: nginx-with-ssl properties: image: nginx ports: - port: 443 protocol: TCP resources: requests: cpu: 1.0 memoryInGB: 1.5 volumeMounts: - name: nginx-config mountPath: /etc/nginx imageRegistryCredentials: - server: SERVER.azurecr.io username: USERNAME password: PASSWORD volumes: - secret: server.pem: PEM server.key: KEY ca.pem: CA nginx.conf: CONF name: nginx-config ipAddress: ports: - port: 443 protocol: TCP type: Public dnsNameLabel: DNS osType: Linuxtags: nulltype: Microsoft.ContainerInstance/containerGroups" }, { "code": null, "e": 10885, "s": 10765, "text": "We will use the sed command to replace parts of this template. These are the commands that you can run without editing." }, { "code": null, "e": 11523, "s": 10885, "text": "$ sed -i -e \"s/name: NAME/name: $MODEL_NAME/\" azure.yaml$ sed -i -e \"s/image: IMAGE/image: $CONTAINER_REGISTRY_NAME/\" azure.yaml$ sed -i -e \"s/server: SERVER/server: $CONTAINER_REGISTRY_NAME/\" azure.yaml$ sed -i -e \"s/username: USERNAME/username: $CONTAINER_REGISTRY_NAME/\" azure.yaml$ sed -i -e \"s/server.pem: PEM/server.pem: $(cat ./certs/ca.pem | base64 -w 0)/\" azure.yaml$ sed -i -e \"s/server.key: KEY/server.key: $(cat ./certs/ca.key| base64 -w 0)/\" azure.yaml$ sed -i -e \"s/ca.pem: CA/ca.pem: $(cat ./certs/ca.pem | base64 -w 0)/\" azure.yaml$ sed -i -e \"s/nginx.conf: CONF/nginx.conf: $(cat ./nginx.conf | base64 -w 0)/\" azure.yaml" }, { "code": null, "e": 11665, "s": 11523, "text": "These commands have to be edited. Replace the bolded parts with location and password from the registry and use your DNS to replace DNS_NAME." }, { "code": null, "e": 11979, "s": 11665, "text": "$ sed -i -e \"s/location: LOCATION/location: westeurope/\" azure.yaml$ sed -i -e \"s/password: PASSWORD/password: REGISTRY_PASS/\" azure.yaml#TIP: If your generated password has some special characters#like / you will have to manually put \\/ infront$ sed -i -e \"s/dnsNameLabel: DNS/dnsNameLabel: DNS_NAME/\" azure.yaml" }, { "code": null, "e": 12066, "s": 11979, "text": "Replace <AZURE RESOURCE GROUP> with your valid resource group and you are ready to go." }, { "code": null, "e": 12163, "s": 12066, "text": "$ az container create --resource-group <AZURE RESOURCE GROUP> --name \"$MODEL_NAME\" -f azure.yaml" }, { "code": null, "e": 12277, "s": 12163, "text": "Make sure that you have a proper path to client.key and client.pem and you can proceed to call the API like this:" }, { "code": null, "e": 12791, "s": 12277, "text": "$ curl -d '{\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]}' -v --key \"./certs/client.key\" --cert \"./certs/client.full.pem\" -X POST -k https://blogdemo.westeurope.azurecontainer.io/v1/models/demo_model:predict#REPLACE blogdemo.westeurope.azurecontainer.io WITH DNS#OR:$ curl -d '{\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]}' -v --key \"./certs/client.key\" --cert \"./certs/client.full.pem\" -X POST -k https://IP.ADDRESS/v1/models/demo_model:predict#REPLACE IP.ADDRESS WITH IP" }, { "code": null, "e": 12855, "s": 12791, "text": "If everything works fine you will get a response like this one:" }, { "code": null, "e": 12937, "s": 12855, "text": "IMPORTANT: Since this is a self-signed certificate, you must add -k flag in cURL." }, { "code": null, "e": 12953, "s": 12937, "text": "Python version:" }, { "code": null, "e": 13352, "s": 12953, "text": "import requests import jsonapi_url = \"https://blogdemo.westeurope.azurecontainer.io/v1/models/demo_model:predict\"data = json.dumps({\"signature_name\": \"serving_default\", \"instances\": [[10.0],[9.0]]})headers = {\"content-type\": \"application/json\"}json_response = requests.post(api_url, data=data, headers=headers,verify=False,cert=(\"./certs/client.pem\",\"./certs/client.key\"),)print(json_response.text)" }, { "code": null, "e": 13430, "s": 13352, "text": "IMPORTANT: Since this is a self-signed certificate, you must set verify=False" }, { "code": null, "e": 13471, "s": 13430, "text": "When called without a valid certificate:" }, { "code": null, "e": 13497, "s": 13471, "text": "Deployment #3: COMPLETED!" }, { "code": null, "e": 13602, "s": 13497, "text": "You can monitor the usage of the model in Container Instance and you can see request made in nginx logs." }, { "code": null, "e": 13767, "s": 13602, "text": "Q: Can I deploy a custom model (without TF Serving)?A: Yes. You have to dockerize the model and if you use the right ports, everything else should work as expected." }, { "code": null, "e": 13863, "s": 13767, "text": "Q: Can I deploy it to AWS?A: Yes, by using nginx.config and CA configuration seen in this blog." } ]
MFC - Internet Programming
Microsoft provides many APIs for programming both client and server applications. Many new applications are being written for the Internet, and as technologies, browser capabilities, and security options change, new types of applications will be written. Your custom application can retrieve information and provide data on the Internet. MFC provides a class CSocket for writing network communications programs with Windows Sockets. Here is a list of methods in CSocket class. Attach Attaches a SOCKET handle to a CSocket object. CancelBlockingCall Cancels a blocking call that is currently in progress. Create Creates a socket. FromHandle Returns a pointer to a CSocket object, given a SOCKET handle. IsBlocking Determines whether a blocking call is in progress. Let us look into a simple example by creating a MFS SDI application. Step 1 − Enter MFCServer in the name field and click OK. Step 2 − On Advanced Features tab, check the Windows sockets option. Step 3 − Once the project is created, add a new MFC class CServerSocket. Step 4 − Select the CSocket as base class and click Finish. Step 5 − Add more MFC class CReceivingSocket. Step 6 − CRecevingSocket will receive incoming messages from client. In CMFCServerApp, the header file includes the following files − #include "ServerSocket.h" #include "MFCServerView.h" Step 7 − Add the following two class variables in CMFCServerApp class. CServerSocket m_serverSocket; CMFCServerView m_pServerView; Step 8 − In CMFCServerApp::InitInstance() method, create the socket and specify the port and then call the Listen method as shown below. m_serverSocket.Create(6666); m_serverSocket.Listen(); Step 9 − Include the following header file in CMFCServerView header file. #include "MFCServerDoc.h" Step 10 − Override the OnAccept function from Socket class. Step 11 − Select CServerSocket in class view and the highlighted icon in Properties window. Now, Add OnAccept. Here is the implementation of OnAccept function. void CServerSocket::OnAccept(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class AfxMessageBox(L"Connection accepted"); CSocket::OnAccept(nErrorCode); } Step 12 − Add OnReceive() function. void CServerSocket::OnReceive(int nErrorCode) { // TODO: Add your specialized code here and/or call the base class AfxMessageBox(L"Data Received"); CSocket::OnReceive(nErrorCode); } Step 13 − Add OnReceive() function in CReceivingSocket class. Right-click on the CMFCServerView class in solution explorer and select Add → AddFunction. Step 14 − Enter the above mentioned information and click finish. Step 15 − Add the following CStringArray variable in CMFCServerView header file. CStringArray m_msgArray; Step 16 − Here is the implementation of AddMsg() function. void CMFCServerView::AddMsg(CString message) { m_msgArray.Add(message); Invalidate(); } Step 17 − Update the constructor as shown in the following code. CMFCServerView::CMFCServerView() { ((CMFCServerApp*)AfxGetApp()) -> m_pServerView = this; } Step 18 − Here is the implementation of OnDraw() function, which display messages. void CMFCServerView::OnDraw(CDC* pDC) { int y = 100; for (int i = 0; m_msgArray.GetSize(); i++) { pDC->TextOut(100, y, m_msgArray.GetAt(i)); y += 50; } CMFCServerDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } Step 19 − The server side is now complete. It will receive message from the client. Step 1 − Let us create a new MFC dialog based application for client side application. Step 2 − On Advanced Features tab, check the Windows sockets option as shown above. Step 3 − Once the project is created, design your dialog box as shown in the following snapshot. Step 4 − Add event handlers for Connect and Send buttons. Step 5 − Add value variables for all the three edit controls. For port edit control, select the variable type UINT. Step 6 − Add MFC class for connecting and sending messages. Step 7 − Include the header file of CClientSocket class in the header file CMFCClientDemoApp class and add the class variable. Similarly, add the class variable in CMFCClientDemoDlg header file as well. CClientSocket m_clientSocket; Step 8 − Here is the implementation of Connect button event handler. void CMFCClientDemoDlg::OnBnClickedButtonConnect() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_clientSocket.Create(); if (m_clientSocket.Connect(m_ipAddress, m_port)) { AfxMessageBox(L"Connection Successfull"); }else { AfxMessageBox(L"Connection Failed"); } DWORD error = GetLastError(); } Step 9 − Here is the implementation of Send button event handler. void CMFCClientDemoDlg::OnBnClickedButtonSend() { // TODO: Add your control notification handler code here UpdateData(TRUE); if (m_clientSocket.Send(m_message.GetBuffer(m_message.GetLength()), m_message.GetLength())) { }else { AfxMessageBox(L"Failed to send message"); } } Step 10 − First run the Server application and then the client application. Enter the local host ip and port and click Connect. Step 11 − You will now see the message on Server side as shown in the following snapshot. Print Add Notes Bookmark this page
[ { "code": null, "e": 2405, "s": 2067, "text": "Microsoft provides many APIs for programming both client and server applications. Many new applications are being written for the Internet, and as technologies, browser capabilities, and security options change, new types of applications will be written. Your custom application can retrieve information and provide data on the Internet." }, { "code": null, "e": 2500, "s": 2405, "text": "MFC provides a class CSocket for writing network communications programs with Windows Sockets." }, { "code": null, "e": 2544, "s": 2500, "text": "Here is a list of methods in CSocket class." }, { "code": null, "e": 2551, "s": 2544, "text": "Attach" }, { "code": null, "e": 2597, "s": 2551, "text": "Attaches a SOCKET handle to a CSocket object." }, { "code": null, "e": 2616, "s": 2597, "text": "CancelBlockingCall" }, { "code": null, "e": 2671, "s": 2616, "text": "Cancels a blocking call that is currently in progress." }, { "code": null, "e": 2678, "s": 2671, "text": "Create" }, { "code": null, "e": 2696, "s": 2678, "text": "Creates a socket." }, { "code": null, "e": 2707, "s": 2696, "text": "FromHandle" }, { "code": null, "e": 2769, "s": 2707, "text": "Returns a pointer to a CSocket object, given a SOCKET handle." }, { "code": null, "e": 2780, "s": 2769, "text": "IsBlocking" }, { "code": null, "e": 2831, "s": 2780, "text": "Determines whether a blocking call is in progress." }, { "code": null, "e": 2900, "s": 2831, "text": "Let us look into a simple example by creating a MFS SDI application." }, { "code": null, "e": 2957, "s": 2900, "text": "Step 1 − Enter MFCServer in the name field and click OK." }, { "code": null, "e": 3026, "s": 2957, "text": "Step 2 − On Advanced Features tab, check the Windows sockets option." }, { "code": null, "e": 3099, "s": 3026, "text": "Step 3 − Once the project is created, add a new MFC class CServerSocket." }, { "code": null, "e": 3159, "s": 3099, "text": "Step 4 − Select the CSocket as base class and click Finish." }, { "code": null, "e": 3205, "s": 3159, "text": "Step 5 − Add more MFC class CReceivingSocket." }, { "code": null, "e": 3274, "s": 3205, "text": "Step 6 − CRecevingSocket will receive incoming messages from client." }, { "code": null, "e": 3339, "s": 3274, "text": "In CMFCServerApp, the header file includes the following files −" }, { "code": null, "e": 3392, "s": 3339, "text": "#include \"ServerSocket.h\"\n#include \"MFCServerView.h\"" }, { "code": null, "e": 3463, "s": 3392, "text": "Step 7 − Add the following two class variables in CMFCServerApp class." }, { "code": null, "e": 3524, "s": 3463, "text": "CServerSocket m_serverSocket;\nCMFCServerView m_pServerView;\n" }, { "code": null, "e": 3661, "s": 3524, "text": "Step 8 − In CMFCServerApp::InitInstance() method, create the socket and specify the port and then call the Listen method as shown below." }, { "code": null, "e": 3716, "s": 3661, "text": "m_serverSocket.Create(6666);\nm_serverSocket.Listen();\n" }, { "code": null, "e": 3790, "s": 3716, "text": "Step 9 − Include the following header file in CMFCServerView header file." }, { "code": null, "e": 3816, "s": 3790, "text": "#include \"MFCServerDoc.h\"" }, { "code": null, "e": 3876, "s": 3816, "text": "Step 10 − Override the OnAccept function from Socket class." }, { "code": null, "e": 4036, "s": 3876, "text": "Step 11 − Select CServerSocket in class view and the highlighted icon in Properties window. Now, Add OnAccept. Here is the implementation of OnAccept function." }, { "code": null, "e": 4232, "s": 4036, "text": "void CServerSocket::OnAccept(int nErrorCode) {\n\n // TODO: Add your specialized code here and/or call the base class\n AfxMessageBox(L\"Connection accepted\");\n CSocket::OnAccept(nErrorCode);\n}" }, { "code": null, "e": 4268, "s": 4232, "text": "Step 12 − Add OnReceive() function." }, { "code": null, "e": 4464, "s": 4268, "text": "void CServerSocket::OnReceive(int nErrorCode) { \n \n // TODO: Add your specialized code here and/or call the base class\n AfxMessageBox(L\"Data Received\");\n CSocket::OnReceive(nErrorCode);\n}" }, { "code": null, "e": 4526, "s": 4464, "text": "Step 13 − Add OnReceive() function in CReceivingSocket class." }, { "code": null, "e": 4617, "s": 4526, "text": "Right-click on the CMFCServerView class in solution explorer and select Add → AddFunction." }, { "code": null, "e": 4683, "s": 4617, "text": "Step 14 − Enter the above mentioned information and click finish." }, { "code": null, "e": 4764, "s": 4683, "text": "Step 15 − Add the following CStringArray variable in CMFCServerView header file." }, { "code": null, "e": 4790, "s": 4764, "text": "CStringArray m_msgArray;\n" }, { "code": null, "e": 4849, "s": 4790, "text": "Step 16 − Here is the implementation of AddMsg() function." }, { "code": null, "e": 4944, "s": 4849, "text": "void CMFCServerView::AddMsg(CString message) {\n\n m_msgArray.Add(message);\n Invalidate();\n}" }, { "code": null, "e": 5009, "s": 4944, "text": "Step 17 − Update the constructor as shown in the following code." }, { "code": null, "e": 5105, "s": 5009, "text": "CMFCServerView::CMFCServerView() {\n\n ((CMFCServerApp*)AfxGetApp()) -> m_pServerView = this;\n}" }, { "code": null, "e": 5188, "s": 5105, "text": "Step 18 − Here is the implementation of OnDraw() function, which display messages." }, { "code": null, "e": 5507, "s": 5188, "text": "void CMFCServerView::OnDraw(CDC* pDC) {\n\n int y = 100;\n for (int i = 0; m_msgArray.GetSize(); i++) {\n \n pDC->TextOut(100, y, m_msgArray.GetAt(i));\n y += 50;\n }\n CMFCServerDoc* pDoc = GetDocument();\n ASSERT_VALID(pDoc);\n if (!pDoc)\n return;\n\n // TODO: add draw code for native data here\n}" }, { "code": null, "e": 5591, "s": 5507, "text": "Step 19 − The server side is now complete. It will receive message from the client." }, { "code": null, "e": 5678, "s": 5591, "text": "Step 1 − Let us create a new MFC dialog based application for client side application." }, { "code": null, "e": 5762, "s": 5678, "text": "Step 2 − On Advanced Features tab, check the Windows sockets option as shown above." }, { "code": null, "e": 5859, "s": 5762, "text": "Step 3 − Once the project is created, design your dialog box as shown in the following snapshot." }, { "code": null, "e": 5917, "s": 5859, "text": "Step 4 − Add event handlers for Connect and Send buttons." }, { "code": null, "e": 6033, "s": 5917, "text": "Step 5 − Add value variables for all the three edit controls. For port edit control, select the variable type UINT." }, { "code": null, "e": 6093, "s": 6033, "text": "Step 6 − Add MFC class for connecting and sending messages." }, { "code": null, "e": 6296, "s": 6093, "text": "Step 7 − Include the header file of CClientSocket class in the header file CMFCClientDemoApp class and add the class variable. Similarly, add the class variable in CMFCClientDemoDlg header file as well." }, { "code": null, "e": 6326, "s": 6296, "text": "CClientSocket m_clientSocket;" }, { "code": null, "e": 6395, "s": 6326, "text": "Step 8 − Here is the implementation of Connect button event handler." }, { "code": null, "e": 6754, "s": 6395, "text": "void CMFCClientDemoDlg::OnBnClickedButtonConnect() {\n\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n m_clientSocket.Create();\n if (m_clientSocket.Connect(m_ipAddress, m_port)) {\n AfxMessageBox(L\"Connection Successfull\");\n }else {\n AfxMessageBox(L\"Connection Failed\");\n }\n DWORD error = GetLastError();\n}" }, { "code": null, "e": 6820, "s": 6754, "text": "Step 9 − Here is the implementation of Send button event handler." }, { "code": null, "e": 7119, "s": 6820, "text": "void CMFCClientDemoDlg::OnBnClickedButtonSend() {\n\n // TODO: Add your control notification handler code here\n UpdateData(TRUE);\n if (m_clientSocket.Send(m_message.GetBuffer(m_message.GetLength()), m_message.GetLength())) {\n \n }else {\n AfxMessageBox(L\"Failed to send message\");\n }\n}" }, { "code": null, "e": 7247, "s": 7119, "text": "Step 10 − First run the Server application and then the client application. Enter the local host ip and port and click Connect." }, { "code": null, "e": 7337, "s": 7247, "text": "Step 11 − You will now see the message on Server side as shown in the following snapshot." }, { "code": null, "e": 7344, "s": 7337, "text": " Print" }, { "code": null, "e": 7355, "s": 7344, "text": " Add Notes" } ]
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks
28 Jun, 2021 Consider the relation X(P, Q, R, S, T, U) with the following set of functional dependencies F = { {P, R} → {S,T}, {P, S, U} → {Q, R} } Which of the following is the trivial functional dependency in F+ is closure of F? (A) {P,R}→{S,T}(B) {P,R}→{R,T}(C) {P,S}→{S}(D) {P,S,U}→{Q}Answer: (C)Explanation: A functional dependency X -> Y is trivial if Y is a subset of X.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-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2004 | Question 3 GATE | GATE-IT-2004 | Question 71 GATE | GATE-CS-2006 | Question 49 GATE | GATE CS 2019 | Question 27
[ { "code": null, "e": 24418, "s": 24390, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24510, "s": 24418, "text": "Consider the relation X(P, Q, R, S, T, U) with the following set of functional dependencies" }, { "code": null, "e": 24573, "s": 24510, "text": "F = {\n {P, R} → {S,T}, \n {P, S, U} → {Q, R}\n }" }, { "code": null, "e": 24656, "s": 24573, "text": "Which of the following is the trivial functional dependency in F+ is closure of F?" }, { "code": null, "e": 24824, "s": 24656, "text": "(A) {P,R}→{S,T}(B) {P,R}→{R,T}(C) {P,S}→{S}(D) {P,S,U}→{Q}Answer: (C)Explanation: A functional dependency X -> Y is trivial if Y is a subset of X.Quiz of this Question" }, { "code": null, "e": 24845, "s": 24824, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 24871, "s": 24845, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 24876, "s": 24871, "text": "GATE" }, { "code": null, "e": 24974, "s": 24876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25008, "s": 24974, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25050, "s": 25008, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25092, "s": 25050, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25126, "s": 25092, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 25160, "s": 25126, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 25193, "s": 25160, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25226, "s": 25193, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25260, "s": 25226, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25294, "s": 25260, "text": "GATE | GATE-CS-2006 | Question 49" } ]
What is stored procedure and how can we create MySQL stored procedures?
Stored procedure, in the context of regular computing language, may be defined as a subroutine like a subprogram that is stored in a database. In the context of MySQL, it is a segment of declarative SQL statements stored inside the database catalog. Before writing stored procedures in MySQL, we must have to check the version because MySQL 5 introduces stored procedure. Following is the syntax for creating a stored procedure − CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic ...] routine_body proc_parameter: [ IN | OUT | INOUT ] param_name type type: Any valid MySQL data type characteristic: COMMENT 'string' | LANGUAGE SQL | [NOT] DETERMINISTIC | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER | INVOKER } routine_body: Valid SQL routine statement Following is an example in which we created a simple procedure to get all the records from the table ‘student_info’ which have the following data − mysql> select * from student_info; +-----+---------+------------+------------+ | id | Name | Address | Subject | +-----+---------+------------+------------+ | 100 | Aarav | Delhi | Computers | | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | +------+--------+------------+------------+ 4 rows in set (0.00 sec) Now, with the help of following queries we created the stored procedure named allrecords() mysql> Delimiter // mysql> Create Procedure allrecords() -> BEGIN -> Select * from Student_info; -> END// Query OK, 0 rows affected (0.02 sec) mysql> DELIMITER ;
[ { "code": null, "e": 1492, "s": 1062, "text": "Stored procedure, in the context of regular computing language, may be defined as a subroutine like a subprogram that is stored in a database. In the context of MySQL, it is a segment of declarative SQL statements stored inside the database catalog. Before writing stored procedures in MySQL, we must have to check the version because MySQL 5 introduces stored procedure. Following is the syntax for creating a stored procedure −" }, { "code": null, "e": 1911, "s": 1492, "text": "CREATE [DEFINER = { user | CURRENT_USER }]\nPROCEDURE sp_name ([proc_parameter[,...]])\n[characteristic ...] routine_body\nproc_parameter: [ IN | OUT | INOUT ] param_name type\ntype:\nAny valid MySQL data type\ncharacteristic:\nCOMMENT 'string'\n| LANGUAGE SQL\n| [NOT] DETERMINISTIC\n| { CONTAINS SQL | NO SQL | READS SQL DATA\n| MODIFIES SQL DATA }\n| SQL SECURITY { DEFINER | INVOKER }\nroutine_body:\nValid SQL routine statement" }, { "code": null, "e": 2059, "s": 1911, "text": "Following is an example in which we created a simple procedure to get all the records from the table ‘student_info’ which have the following data −" }, { "code": null, "e": 2471, "s": 2059, "text": "mysql> select * from student_info;\n+-----+---------+------------+------------+\n| id | Name | Address | Subject |\n+-----+---------+------------+------------+\n| 100 | Aarav | Delhi | Computers |\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n+------+--------+------------+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2562, "s": 2471, "text": "Now, with the help of following queries we created the stored procedure named allrecords()" }, { "code": null, "e": 2736, "s": 2562, "text": "mysql> Delimiter //\nmysql> Create Procedure allrecords()\n -> BEGIN\n -> Select * from Student_info;\n -> END//\nQuery OK, 0 rows affected (0.02 sec)\nmysql> DELIMITER ;" } ]
How to Install xlrd in Python in Windows? - GeeksforGeeks
26 Sep, 2021 The xlrd module in python is used to retrieve information from a spreadsheet. In this article, we will look into the process of installing the xldr module in a Windows machine. The only thing that you need for installing the xlrd module on Windows are: Python PIP or Conda (depending upon user preference) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c anaconda xlrd Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge Users who prefer to use pip can use the below command to install the xlrd package on Windows: pip install xlrd You will get a similar message once the installation is complete: Use the below code in your Python ide to verify successful installation of the xlrd package: Python3 import xlrdxlrd.__version__ If successfully installed you will get the following output: sooda367 Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Re-rendering Components in ReactJS Python NOT EQUAL operator How to build a basic CRUD app with Node.js and ReactJS ? Banking Transaction System using Java How to parse JSON Data into React Table Component ? How to Find the Wi-Fi Password Using CMD in Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows? Java Tutorial How to Install FFmpeg on Windows?
[ { "code": null, "e": 24611, "s": 24583, "text": "\n26 Sep, 2021" }, { "code": null, "e": 24788, "s": 24611, "text": "The xlrd module in python is used to retrieve information from a spreadsheet. In this article, we will look into the process of installing the xldr module in a Windows machine." }, { "code": null, "e": 24864, "s": 24788, "text": "The only thing that you need for installing the xlrd module on Windows are:" }, { "code": null, "e": 24871, "s": 24864, "text": "Python" }, { "code": null, "e": 24917, "s": 24871, "text": "PIP or Conda (depending upon user preference)" }, { "code": null, "e": 25039, "s": 24917, "text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:" }, { "code": null, "e": 25070, "s": 25039, "text": "conda install -c anaconda xlrd" }, { "code": null, "e": 25100, "s": 25070, "text": "Type y for yes when prompted." }, { "code": null, "e": 25166, "s": 25100, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 25239, "s": 25166, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 25336, "s": 25239, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 25381, "s": 25336, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 25467, "s": 25381, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 25513, "s": 25467, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 25607, "s": 25513, "text": "Users who prefer to use pip can use the below command to install the xlrd package on Windows:" }, { "code": null, "e": 25624, "s": 25607, "text": "pip install xlrd" }, { "code": null, "e": 25690, "s": 25624, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 25783, "s": 25690, "text": "Use the below code in your Python ide to verify successful installation of the xlrd package:" }, { "code": null, "e": 25791, "s": 25783, "text": "Python3" }, { "code": "import xlrdxlrd.__version__", "e": 25819, "s": 25791, "text": null }, { "code": null, "e": 25880, "s": 25819, "text": "If successfully installed you will get the following output:" }, { "code": null, "e": 25889, "s": 25880, "text": "sooda367" }, { "code": null, "e": 25904, "s": 25889, "text": "Blogathon-2021" }, { "code": null, "e": 25919, "s": 25904, "text": "how-to-install" }, { "code": null, "e": 25926, "s": 25919, "text": "Picked" }, { "code": null, "e": 25936, "s": 25926, "text": "Blogathon" }, { "code": null, "e": 25943, "s": 25936, "text": "How To" }, { "code": null, "e": 25962, "s": 25943, "text": "Installation Guide" }, { "code": null, "e": 26060, "s": 25962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26069, "s": 26060, "text": "Comments" }, { "code": null, "e": 26082, "s": 26069, "text": "Old Comments" }, { "code": null, "e": 26117, "s": 26082, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 26143, "s": 26117, "text": "Python NOT EQUAL operator" }, { "code": null, "e": 26200, "s": 26143, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 26238, "s": 26200, "text": "Banking Transaction System using Java" }, { "code": null, "e": 26290, "s": 26238, "text": "How to parse JSON Data into React Table Component ?" }, { "code": null, "e": 26343, "s": 26290, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 26370, "s": 26343, "text": "How to Align Text in HTML?" }, { "code": null, "e": 26415, "s": 26370, "text": "How to Install OpenCV for Python on Windows?" }, { "code": null, "e": 26429, "s": 26415, "text": "Java Tutorial" } ]
Number of 1 Bits | Practice | GeeksforGeeks
Given a positive integer N, print count of set bits in it. Example 1: Input: N = 6 Output: 2 Explanation: Binary representation is '110' So the count of the set bit is 2. Example 2: Input: 8 Output: 1 Explanation: Binary representation is '1000' So the count of the set bit is 1. Your Task: You don't need to read input or print anything. Your task is to complete the function setBits() which takes an Integer N and returns the count of number of set bits. Expected Time Complexity: O(LogN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 109 +1 ayush2024cs113412 hours ago int setBits(int n) { int cnt; while(n>0){ if((n&1)>0){ cnt++;} n=n>>1; } return cnt; } 0 aravindmn75831 day ago // { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: int setBits(int N) { // Write Your Code here return __builtin_popcount(N); } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int N; cin >> N; Solution ob; int cnt = ob.setBits(N); cout << cnt << endl; } return 0; } // } Driver Code Ends +1 gaurabhkumarjha271020012 days ago // one line solution in c++ return __builtin_popcount (N); 0 atulharsh274Premium1 week ago //one line solution for this problem. return N?(N&1) + setBits(N>>1) : 0; 0 mankesh0161 week ago int cnt=1; while(N&=N-1) cnt++; return cnt; +1 devadarsh72 weeks ago Java fast solution| O(k) time-complexity, where k is the number of set bits(1's) |0.21s class Solution { static int setBits(int n) { int x=0; while(n!=0) { x=x+1; n=n&(n-1); } return x; } } 0 rahuldwvdi3 weeks ago Time Taken: 0.2/1.3 note: performing (n-1) makes the last set bit as 0 an all bits after it as 1 class Solution { static int setBits(int n) { //brian kernighan approach int res = 0; while(n>0){ n = n&(n-1); res++; } return res; } } 0 milindprajapatmst191 month ago class Solution { public: int setBits(int N) { int cnt = 0; while (N) { cnt += (N & 1); N >>= 1; } return cnt; } }; 0 jhadeepali26101 month ago int setBits(int N) { int cnt=0; while (N) { N=(N&(N-1)); //rightmost set bit is removed here cnt++; } return cnt; } 0 tirtha19025681 month ago class Solution { static int setBits(int N) { int cnt = 0; while(N>0){ int temp = N%2; if(temp == 1) cnt++; N = N/2; } return cnt; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 298, "s": 238, "text": "Given a positive integer N, print count of set bits in it. " }, { "code": null, "e": 309, "s": 298, "text": "Example 1:" }, { "code": null, "e": 411, "s": 309, "text": "Input:\nN = 6\nOutput:\n2\nExplanation:\nBinary representation is '110' \nSo the count of the set bit is 2." }, { "code": null, "e": 422, "s": 411, "text": "Example 2:" }, { "code": null, "e": 521, "s": 422, "text": "Input:\n8\nOutput:\n1\nExplanation:\nBinary representation is '1000' \nSo the count of the set bit is 1." }, { "code": null, "e": 700, "s": 521, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function setBits() which takes an Integer N and returns the count of number of set bits." }, { "code": null, "e": 765, "s": 700, "text": "Expected Time Complexity: O(LogN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 790, "s": 765, "text": "Constraints:\n1 ≤ N ≤ 109" }, { "code": null, "e": 793, "s": 790, "text": "+1" }, { "code": null, "e": 821, "s": 793, "text": "ayush2024cs113412 hours ago" }, { "code": null, "e": 1043, "s": 821, "text": "int setBits(int n) { int cnt; while(n>0){ if((n&1)>0){ cnt++;} n=n>>1; } return cnt; }" }, { "code": null, "e": 1045, "s": 1043, "text": "0" }, { "code": null, "e": 1068, "s": 1045, "text": "aravindmn75831 day ago" }, { "code": null, "e": 1538, "s": 1068, "text": "// { Driver Code Starts\n#include <bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution {\n public:\n int setBits(int N) {\n // Write Your Code here\n return __builtin_popcount(N);\n }\n};\n\n// { Driver Code Starts.\nint main() {\n int t;\n cin >> t;\n while (t--) {\n int N;\n cin >> N;\n\n Solution ob;\n int cnt = ob.setBits(N);\n cout << cnt << endl;\n }\n return 0;\n}\n // } Driver Code Ends" }, { "code": null, "e": 1541, "s": 1538, "text": "+1" }, { "code": null, "e": 1575, "s": 1541, "text": "gaurabhkumarjha271020012 days ago" }, { "code": null, "e": 1637, "s": 1575, "text": "// one line solution in c++\n return __builtin_popcount (N);" }, { "code": null, "e": 1639, "s": 1637, "text": "0" }, { "code": null, "e": 1669, "s": 1639, "text": "atulharsh274Premium1 week ago" }, { "code": null, "e": 1707, "s": 1669, "text": "//one line solution for this problem." }, { "code": null, "e": 1744, "s": 1707, "text": " return N?(N&1) + setBits(N>>1) : 0;" }, { "code": null, "e": 1746, "s": 1744, "text": "0" }, { "code": null, "e": 1767, "s": 1746, "text": "mankesh0161 week ago" }, { "code": null, "e": 1841, "s": 1767, "text": " int cnt=1;\n \n while(N&=N-1)\n cnt++;\n \n return cnt;" }, { "code": null, "e": 1844, "s": 1841, "text": "+1" }, { "code": null, "e": 1866, "s": 1844, "text": "devadarsh72 weeks ago" }, { "code": null, "e": 1954, "s": 1866, "text": "Java fast solution| O(k) time-complexity, where k is the number of set bits(1's) |0.21s" }, { "code": null, "e": 2118, "s": 1954, "text": "class Solution {\n static int setBits(int n) {\n int x=0;\n while(n!=0)\n { x=x+1;\n n=n&(n-1);\n }\n return x;\n }\n}" }, { "code": null, "e": 2120, "s": 2118, "text": "0" }, { "code": null, "e": 2142, "s": 2120, "text": "rahuldwvdi3 weeks ago" }, { "code": null, "e": 2162, "s": 2142, "text": "Time Taken: 0.2/1.3" }, { "code": null, "e": 2240, "s": 2162, "text": "note: performing (n-1) makes the last set bit as 0 an all bits after it as 1 " }, { "code": null, "e": 2447, "s": 2240, "text": "class Solution {\n static int setBits(int n) {\n //brian kernighan approach\n int res = 0;\n while(n>0){\n n = n&(n-1);\n res++;\n }\n return res;\n }\n}" }, { "code": null, "e": 2449, "s": 2447, "text": "0" }, { "code": null, "e": 2480, "s": 2449, "text": "milindprajapatmst191 month ago" }, { "code": null, "e": 2661, "s": 2480, "text": "class Solution {\n public:\n int setBits(int N) {\n int cnt = 0;\n while (N) {\n cnt += (N & 1);\n N >>= 1;\n }\n return cnt;\n }\n};" }, { "code": null, "e": 2663, "s": 2661, "text": "0" }, { "code": null, "e": 2689, "s": 2663, "text": "jhadeepali26101 month ago" }, { "code": null, "e": 2865, "s": 2689, "text": " int setBits(int N) { int cnt=0; while (N) { N=(N&(N-1)); //rightmost set bit is removed here cnt++; } return cnt; }" }, { "code": null, "e": 2867, "s": 2865, "text": "0" }, { "code": null, "e": 2892, "s": 2867, "text": "tirtha19025681 month ago" }, { "code": null, "e": 3093, "s": 2892, "text": "class Solution {\n static int setBits(int N) {\n int cnt = 0;\n while(N>0){\n int temp = N%2;\n if(temp == 1) cnt++;\n N = N/2;\n }\n return cnt;\n }\n}" }, { "code": null, "e": 3239, "s": 3093, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3275, "s": 3239, "text": " Login to access your submissions. " }, { "code": null, "e": 3285, "s": 3275, "text": "\nProblem\n" }, { "code": null, "e": 3295, "s": 3285, "text": "\nContest\n" }, { "code": null, "e": 3358, "s": 3295, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3506, "s": 3358, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3714, "s": 3506, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3820, "s": 3714, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Swing Examples - Add Title Border to JPanel
Following example showcase how to add title to border of a JPanel in a Java Swing application. We are using the following APIs. BorderFactory.createTitledBorder() − To create a titled border. BorderFactory.createTitledBorder() − To create a titled border. JPanel.setBorder(border) − To set the desired border to the JPanel. JPanel.setBorder(border) − To set the desired border to the JPanel. import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.LayoutManager; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(JFrame frame){ //Create a border Border blackline = BorderFactory.createTitledBorder("Title"); JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JPanel panel1 = new JPanel(); String spaces = " "; panel1.add(new JLabel(spaces + "Title border to JPanel" + spaces)); panel1.setBorder(blackline); panel.add(panel1); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2134, "s": 2039, "text": "Following example showcase how to add title to border of a JPanel in a Java Swing application." }, { "code": null, "e": 2167, "s": 2134, "text": "We are using the following APIs." }, { "code": null, "e": 2231, "s": 2167, "text": "BorderFactory.createTitledBorder() − To create a titled border." }, { "code": null, "e": 2295, "s": 2231, "text": "BorderFactory.createTitledBorder() − To create a titled border." }, { "code": null, "e": 2363, "s": 2295, "text": "JPanel.setBorder(border) − To set the desired border to the JPanel." }, { "code": null, "e": 2431, "s": 2363, "text": "JPanel.setBorder(border) − To set the desired border to the JPanel." }, { "code": null, "e": 3641, "s": 2431, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.border.Border;\n\npublic class SwingTester {\n\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(JFrame frame){\n //Create a border\n Border blackline = BorderFactory.createTitledBorder(\"Title\");\n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JPanel panel1 = new JPanel();\n String spaces = \" \";\n\n panel1.add(new JLabel(spaces + \"Title border to JPanel\" + spaces)); \n panel1.setBorder(blackline);\n\n panel.add(panel1);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}" }, { "code": null, "e": 3648, "s": 3641, "text": " Print" }, { "code": null, "e": 3659, "s": 3648, "text": " Add Notes" } ]
SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters The underscore sign (_) represents one, single character Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?) instead of the underscore (_). The percent sign and the underscore can also be used in combinations! Tip: You can also combine any number of conditions using AND or OR operators. Here are some examples showing different LIKE operators with '%' and '_' wildcards: The table below shows the complete "Customers" table from the Northwind sample database: The following SQL statement selects all customers with a CustomerName starting with "a": The following SQL statement selects all customers with a CustomerName ending with "a": The following SQL statement selects all customers with a CustomerName that have "or" in any position: The following SQL statement selects all customers with a CustomerName that have "r" in the second position: The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3 characters in length: The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o": The following SQL statement selects all customers with a CustomerName that does NOT start with "a": Select all records where the value of the City column starts with the letter "a". SELECT * FROM Customers ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 92, "s": 0, "text": "The LIKE operator is used in a \nWHERE clause to search for a specified pattern in a column." }, { "code": null, "e": 167, "s": 92, "text": "There are two wildcards often used in conjunction with the \nLIKE operator:" }, { "code": null, "e": 234, "s": 167, "text": " The percent sign (%) represents zero, one, or multiple characters" }, { "code": null, "e": 292, "s": 234, "text": " The underscore sign (_) represents one, single character" }, { "code": null, "e": 418, "s": 292, "text": "Note: MS Access uses an asterisk (*) instead of the percent \nsign (%), and a question mark (?) instead of the underscore (_)." }, { "code": null, "e": 488, "s": 418, "text": "The percent sign and the underscore can also be used in combinations!" }, { "code": null, "e": 567, "s": 488, "text": "Tip: You can also combine any number of conditions using \nAND or OR operators." }, { "code": null, "e": 651, "s": 567, "text": "Here are some examples showing different LIKE operators with '%' and '_' wildcards:" }, { "code": null, "e": 740, "s": 651, "text": "The table below shows the complete \"Customers\" table from the Northwind sample database:" }, { "code": null, "e": 830, "s": 740, "text": "The following SQL statement selects all customers with a CustomerName starting with \n\"a\":" }, { "code": null, "e": 917, "s": 830, "text": "The following SQL statement selects all customers with a CustomerName ending with \"a\":" }, { "code": null, "e": 1020, "s": 917, "text": "The following SQL statement selects all customers with a CustomerName that \nhave \"or\" in any position:" }, { "code": null, "e": 1129, "s": 1020, "text": "The following SQL statement selects all customers with a CustomerName that \nhave \"r\" in the second position:" }, { "code": null, "e": 1262, "s": 1129, "text": "The following SQL statement selects all customers with a CustomerName that \nstarts with \"a\" and are at least 3 characters in length:" }, { "code": null, "e": 1372, "s": 1262, "text": "The following SQL statement selects all customers with a ContactName that \nstarts with \"a\" and ends with \"o\":" }, { "code": null, "e": 1474, "s": 1372, "text": "The following SQL statement selects all customers with a CustomerName that \ndoes \nNOT start with \"a\":" }, { "code": null, "e": 1556, "s": 1474, "text": "Select all records where the value of the City column starts with the letter \"a\"." }, { "code": null, "e": 1583, "s": 1556, "text": "SELECT * FROM Customers\n;\n" }, { "code": null, "e": 1602, "s": 1583, "text": "Start the Exercise" }, { "code": null, "e": 1635, "s": 1602, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1677, "s": 1635, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1784, "s": 1677, "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": 1803, "s": 1784, "text": "[email protected]" } ]
How to get the table name of the current ResultSet using JDBC?
You can get the name of the table in the current ResultSet object using the getTableName() method of the ResultSetMetaData interface. This method accepts an integer value representing the index of a column and, returns a String value representing the name of the table that contains the given column. Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below − CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements − insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following JDBC program establishes connection with MySQL database, retrieves and displays the name of the table. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class ResultSetMetaData_getTableName { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); //retrieving the ResultSetMetaData object ResultSetMetaData resultSetMetaData = rs.getMetaData(); //Retrieving the column name String tableName = resultSetMetaData.getTableName(4); System.out.println("Name of the table : "+ tableName); } } Connection established...... Name of the table: myplayers
[ { "code": null, "e": 1363, "s": 1062, "text": "You can get the name of the table in the current ResultSet object using the getTableName() method of the ResultSetMetaData interface. This method accepts an integer value representing the index of a column and, returns a String value representing the name of the table that contains the given column." }, { "code": null, "e": 1463, "s": 1363, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 1656, "s": 1463, "text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 1731, "s": 1656, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −" }, { "code": null, "e": 2393, "s": 1731, "text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 2506, "s": 2393, "text": "Following JDBC program establishes connection with MySQL database, retrieves and displays the name of the table." }, { "code": null, "e": 3629, "s": 2506, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.ResultSetMetaData;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSetMetaData_getTableName {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select * from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //retrieving the ResultSetMetaData object\n ResultSetMetaData resultSetMetaData = rs.getMetaData();\n //Retrieving the column name\n String tableName = resultSetMetaData.getTableName(4);\n System.out.println(\"Name of the table : \"+ tableName);\n }\n}" }, { "code": null, "e": 3687, "s": 3629, "text": "Connection established......\nName of the table: myplayers" } ]
Python program to read input from console
Suppose we have to take firstname and lastname from console and write a prompt like "Hello <firstname> <lastname>, you are welcome!". To get the result we can use the format() class.We can placeholder into the string using {}, then pass arguments into format() function. So, if the input is like Ashish Dutta, then the output will be "Hello Ashish Dutta, you are welcome!" To solve this, we will follow these steps − fn := take first input from the console fn := take first input from the console ln := take second input from the console ln := take second input from the console ret := "Hello a {} {}, you are welcome!" then call format with this string like format(fn, ln) ret := "Hello a {} {}, you are welcome!" then call format with this string like format(fn, ln) return ret return ret Let us see the following implementation to get better understanding def solve(): fn = input() ln = input() ret = "Hello {} {}, you are welcome!".format(fn, ln) return ret print(solve()) Ashish Dutta Hello Ashish Dutta, you are welcome!
[ { "code": null, "e": 1333, "s": 1062, "text": "Suppose we have to take firstname and lastname from console and write a prompt like \"Hello <firstname> <lastname>, you are welcome!\". To get the result we can use the format() class.We can placeholder into the string using {}, then pass arguments into format() function." }, { "code": null, "e": 1435, "s": 1333, "text": "So, if the input is like Ashish Dutta, then the output will be \"Hello Ashish Dutta, you are welcome!\"" }, { "code": null, "e": 1479, "s": 1435, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1519, "s": 1479, "text": "fn := take first input from the console" }, { "code": null, "e": 1559, "s": 1519, "text": "fn := take first input from the console" }, { "code": null, "e": 1600, "s": 1559, "text": "ln := take second input from the console" }, { "code": null, "e": 1641, "s": 1600, "text": "ln := take second input from the console" }, { "code": null, "e": 1736, "s": 1641, "text": "ret := \"Hello a {} {}, you are welcome!\" then call format with this string like format(fn, ln)" }, { "code": null, "e": 1831, "s": 1736, "text": "ret := \"Hello a {} {}, you are welcome!\" then call format with this string like format(fn, ln)" }, { "code": null, "e": 1842, "s": 1831, "text": "return ret" }, { "code": null, "e": 1853, "s": 1842, "text": "return ret" }, { "code": null, "e": 1921, "s": 1853, "text": "Let us see the following implementation to get better understanding" }, { "code": null, "e": 2052, "s": 1921, "text": "def solve():\n fn = input()\n ln = input()\n ret = \"Hello {} {}, you are welcome!\".format(fn, ln)\n return ret\n\nprint(solve())" }, { "code": null, "e": 2065, "s": 2052, "text": "Ashish\nDutta" }, { "code": null, "e": 2103, "s": 2065, "text": "Hello Ashish Dutta, you are welcome!\n" } ]
Road detection using segmentation models and albumentations libraries on Keras | by Insaf Ashrapov | Towards Data Science
In this article, I will show how to write own data generator and how to use albumentations as augmentation library. Along with segmentation_models library, which provides dozens of pretrained heads to Unet and other unet-like architectures. For the full code go to Github. Link to dataset. Check out my Machine & Deep Learning blog https://diyago.github.io/ The task of semantic image segmentation is to label each pixel of an image with a corresponding class of what is being represented. For such a task, Unet architecture with different variety of improvements has shown the best result. The core idea behind it just few convolution blocks, which extracts deep and different type of image features, following by so-called deconvolution or upsample blocks, which restore the initial shape of the input image. Besides after each convolution layer, we have some skip-connections, which help the network to remember about initial image and help against fading gradients. For more detailed information you can read the arxiv article or another article. We came for practice, let us go for it. For segmentation we don’t need much data to start getting a decent result, even 100 annotated photos will be enough. For now, we will be using Massachusetts Roads Dataset from https://www.cs.toronto.edu/~vmnih/data/, there about 1100+ annotated train images, they even provide validation and test dataset. Unfortunately, there is no download button, so we have to use a script. This script will get the job done (it might take some time to complete). Lets take a look at image examples: Annotation and image quality seem to be pretty good, the network should be able to detect roads. First of all, you need Keras with TensorFlow to be installed. For Unet construction, we will be using Pavel Yakubovskiy`s library called segmentation_models, for data augmentation albumentation library. I will write more details about them later. Both libraries get updated pretty frequently, so I prefer to update them directly from git. As a data generator, we will be using our custom generator. It should inherit keras.utils.Sequence and should have defined such methods: __init__ (class initializing) __len__ (return lengths of dataset) on_epoch_end (behavior at the end of epochs) __getitem__ (generated batch for feeding into a network) One main advantage of using a custom generator is that you can work with every format data you have and you can do whatever you want — just don’t forget about generating the desired output(batch) for keras. Here we defining __init__ method. The main part of it is setting paths for images (self.image_filenames) and mask names (self.mask_names). Don’t forget to sort them, because for self.image_filenames[i] corresponding mask should be self.mask_names[i]. Next important thing __getitem__. Usually, we can not store all images in RAM, so every time we generate a new batch of data we should read corresponding images. Below we define the method for training. For that, we create an empty numpy array (np.empty), which will store images and mask. Then we read images by read_image_mask method, apply augmentation into each pair of image and mask. Eventually, we return batch (X, y), which is ready to be fitted into the network. Next, we define generators, which will be fed into a network: Data augmentation is a strategy that enables to significantly increase the diversity of data available for training models, without actually collecting new data. It helps to prevent over-fitting and make the model more robust. There are plenty of libraries for such task: imaging, augmentor, solt, built-in methods to keras/pytorch, or you can write your custom augmentation with OpenCV library. But I highly recommend albumentations library. It’s super fast and convenient to use. For usage examples go to the official repository or take a look at example notebooks. In our task, we will be using basic augmentations such as flips and contrast with non-trivial such ElasticTransform. Example of them you can in the image above. After defining the desired augmentation you can easily get your output this: We will be using common callbacks: ModelCheckpoint — allows you to save weights of the model while training ReduceLROnPlateau — reduces training if a validation metric stops to increase EarlyStopping — stop training once metric on validation stops to increase several epochs TensorBoard — a great way to monitor training progress. Link to the official documentation As the model, we will be using Unet. The easiest way to use it just get from segmentation_models library. backbone_name: name of classification model for using as an encoder. EfficientNet currently is state-of-the-art in the classification model, so let us try it. While it should give faster inference and has less training params, it consumes more GPU memory than well-known resnet models. There are many other options to try encoder_weights — using imagenet weights speeds up training encoder_freeze: if True set all layers of an encoder (backbone model) as non-trainable. It might be useful firstly to freeze and train model and then unfreeze decoder_filters — you can specify numbers of decoder block. In some cases, a heavier encoder with a simplified decoder might be useful. After initializing Unet model, you should compile it. Also, we set IOU ( intersection over union) as metric we will to monitor and bce_jaccard_loss (binary cross-entropy plus jaccard loss) as the loss we will optimize. I gave links, so won’t go here for further detail for them. After starting training you can for watching tensorboard logs. As we can see model train pretty well, even after 50 epoch we didn’t reach global/local optima. So we have 0.558 IOU on validation, but every pixel prediction higher than 0 we count as a mask. By picking the appropriate threshold we can further increase our result by 0.039 (7%). Metrics are quite interesting for sure, but a much more insightful model prediction. From the images below we see that our network caught up the task pretty good, which is great. For the inference code and for calculating metrics you can read full code. @phdthesis{MnihThesis, author = {Volodymyr Mnih}, title = {Machine Learning for Aerial Image Labeling}, school = {University of Toronto}, year = {2013}}
[ { "code": null, "e": 337, "s": 47, "text": "In this article, I will show how to write own data generator and how to use albumentations as augmentation library. Along with segmentation_models library, which provides dozens of pretrained heads to Unet and other unet-like architectures. For the full code go to Github. Link to dataset." }, { "code": null, "e": 405, "s": 337, "text": "Check out my Machine & Deep Learning blog https://diyago.github.io/" }, { "code": null, "e": 1098, "s": 405, "text": "The task of semantic image segmentation is to label each pixel of an image with a corresponding class of what is being represented. For such a task, Unet architecture with different variety of improvements has shown the best result. The core idea behind it just few convolution blocks, which extracts deep and different type of image features, following by so-called deconvolution or upsample blocks, which restore the initial shape of the input image. Besides after each convolution layer, we have some skip-connections, which help the network to remember about initial image and help against fading gradients. For more detailed information you can read the arxiv article or another article." }, { "code": null, "e": 1138, "s": 1098, "text": "We came for practice, let us go for it." }, { "code": null, "e": 1589, "s": 1138, "text": "For segmentation we don’t need much data to start getting a decent result, even 100 annotated photos will be enough. For now, we will be using Massachusetts Roads Dataset from https://www.cs.toronto.edu/~vmnih/data/, there about 1100+ annotated train images, they even provide validation and test dataset. Unfortunately, there is no download button, so we have to use a script. This script will get the job done (it might take some time to complete)." }, { "code": null, "e": 1625, "s": 1589, "text": "Lets take a look at image examples:" }, { "code": null, "e": 1722, "s": 1625, "text": "Annotation and image quality seem to be pretty good, the network should be able to detect roads." }, { "code": null, "e": 2061, "s": 1722, "text": "First of all, you need Keras with TensorFlow to be installed. For Unet construction, we will be using Pavel Yakubovskiy`s library called segmentation_models, for data augmentation albumentation library. I will write more details about them later. Both libraries get updated pretty frequently, so I prefer to update them directly from git." }, { "code": null, "e": 2198, "s": 2061, "text": "As a data generator, we will be using our custom generator. It should inherit keras.utils.Sequence and should have defined such methods:" }, { "code": null, "e": 2228, "s": 2198, "text": "__init__ (class initializing)" }, { "code": null, "e": 2264, "s": 2228, "text": "__len__ (return lengths of dataset)" }, { "code": null, "e": 2309, "s": 2264, "text": "on_epoch_end (behavior at the end of epochs)" }, { "code": null, "e": 2366, "s": 2309, "text": "__getitem__ (generated batch for feeding into a network)" }, { "code": null, "e": 2573, "s": 2366, "text": "One main advantage of using a custom generator is that you can work with every format data you have and you can do whatever you want — just don’t forget about generating the desired output(batch) for keras." }, { "code": null, "e": 2824, "s": 2573, "text": "Here we defining __init__ method. The main part of it is setting paths for images (self.image_filenames) and mask names (self.mask_names). Don’t forget to sort them, because for self.image_filenames[i] corresponding mask should be self.mask_names[i]." }, { "code": null, "e": 3296, "s": 2824, "text": "Next important thing __getitem__. Usually, we can not store all images in RAM, so every time we generate a new batch of data we should read corresponding images. Below we define the method for training. For that, we create an empty numpy array (np.empty), which will store images and mask. Then we read images by read_image_mask method, apply augmentation into each pair of image and mask. Eventually, we return batch (X, y), which is ready to be fitted into the network." }, { "code": null, "e": 3358, "s": 3296, "text": "Next, we define generators, which will be fed into a network:" }, { "code": null, "e": 3585, "s": 3358, "text": "Data augmentation is a strategy that enables to significantly increase the diversity of data available for training models, without actually collecting new data. It helps to prevent over-fitting and make the model more robust." }, { "code": null, "e": 3926, "s": 3585, "text": "There are plenty of libraries for such task: imaging, augmentor, solt, built-in methods to keras/pytorch, or you can write your custom augmentation with OpenCV library. But I highly recommend albumentations library. It’s super fast and convenient to use. For usage examples go to the official repository or take a look at example notebooks." }, { "code": null, "e": 4087, "s": 3926, "text": "In our task, we will be using basic augmentations such as flips and contrast with non-trivial such ElasticTransform. Example of them you can in the image above." }, { "code": null, "e": 4164, "s": 4087, "text": "After defining the desired augmentation you can easily get your output this:" }, { "code": null, "e": 4199, "s": 4164, "text": "We will be using common callbacks:" }, { "code": null, "e": 4272, "s": 4199, "text": "ModelCheckpoint — allows you to save weights of the model while training" }, { "code": null, "e": 4350, "s": 4272, "text": "ReduceLROnPlateau — reduces training if a validation metric stops to increase" }, { "code": null, "e": 4439, "s": 4350, "text": "EarlyStopping — stop training once metric on validation stops to increase several epochs" }, { "code": null, "e": 4530, "s": 4439, "text": "TensorBoard — a great way to monitor training progress. Link to the official documentation" }, { "code": null, "e": 4636, "s": 4530, "text": "As the model, we will be using Unet. The easiest way to use it just get from segmentation_models library." }, { "code": null, "e": 4958, "s": 4636, "text": "backbone_name: name of classification model for using as an encoder. EfficientNet currently is state-of-the-art in the classification model, so let us try it. While it should give faster inference and has less training params, it consumes more GPU memory than well-known resnet models. There are many other options to try" }, { "code": null, "e": 5018, "s": 4958, "text": "encoder_weights — using imagenet weights speeds up training" }, { "code": null, "e": 5177, "s": 5018, "text": "encoder_freeze: if True set all layers of an encoder (backbone model) as non-trainable. It might be useful firstly to freeze and train model and then unfreeze" }, { "code": null, "e": 5313, "s": 5177, "text": "decoder_filters — you can specify numbers of decoder block. In some cases, a heavier encoder with a simplified decoder might be useful." }, { "code": null, "e": 5592, "s": 5313, "text": "After initializing Unet model, you should compile it. Also, we set IOU ( intersection over union) as metric we will to monitor and bce_jaccard_loss (binary cross-entropy plus jaccard loss) as the loss we will optimize. I gave links, so won’t go here for further detail for them." }, { "code": null, "e": 5751, "s": 5592, "text": "After starting training you can for watching tensorboard logs. As we can see model train pretty well, even after 50 epoch we didn’t reach global/local optima." }, { "code": null, "e": 5935, "s": 5751, "text": "So we have 0.558 IOU on validation, but every pixel prediction higher than 0 we count as a mask. By picking the appropriate threshold we can further increase our result by 0.039 (7%)." }, { "code": null, "e": 6189, "s": 5935, "text": "Metrics are quite interesting for sure, but a much more insightful model prediction. From the images below we see that our network caught up the task pretty good, which is great. For the inference code and for calculating metrics you can read full code." } ]
How to get the value in a particular cell inside the worksheet in Selenium with python?
We can get the value in a particular cell inside the worksheet in Selenium. Excel is a spreadsheet which is saved with the .xlsx extension. An excel workbook has multiple sheets and each sheet consists of rows and columns. Out of all the worksheets, while we are accessing a particular sheet that is called as an active sheet. Each cell inside a sheet has a unique address which is a combination of row and column numbers. The column number starts from alphabetic character A and row number starts from the number 1. A cell can contain numerous types of values and they are the main component of a worksheet. To work with excel in Selenium with python, we need to take help of OpenPyXL library. This library is responsible for reading and writing operations on Excel, having the extensions like xlsx, xlsm, xltm, xltx. To install OpenPyXL library, we have to execute the command pip install openpyxl. This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel. To get the value inside the worksheet, first of all we need to load the entire workbook by specifying the path where it is located. This is achieved with load_workbook() method. Next we need to identify the active sheet among all the worksheets with the help of active method. To access a cell inside the active worksheet, we need the help of row and column number and the cell method which accepts the row and column number as arguments. For example, to point to the cell corresponding to row 2 and column 3, we need to mention sheet.cell(row=2,column=3). After identification of the cell, we need to use a value method to extract the value out of our required cell. wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx") # to identify the active sheet sh = wrkbk.active # get the value of row 2 and column 3 c=sh.cell(row=2,column=3) Coding Implementation to get the value of a particular cell. import openpyxl # load excel with its path wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx") # to get the active work sheet sh = wrkbk.active # get the value of row 2 and column 3 c=sh.cell(row=2,column=3 # to print the value in console print(" The value is ", c.value)
[ { "code": null, "e": 1285, "s": 1062, "text": "We can get the value in a particular cell inside the worksheet in Selenium.\nExcel is a spreadsheet which is saved with the .xlsx extension. An excel workbook\nhas multiple sheets and each sheet consists of rows and columns." }, { "code": null, "e": 1485, "s": 1285, "text": "Out of all the worksheets, while we are accessing a particular sheet that is called as\nan active sheet. Each cell inside a sheet has a unique address which is a combination\nof row and column numbers." }, { "code": null, "e": 1671, "s": 1485, "text": "The column number starts from alphabetic character A and row number starts from\nthe number 1. A cell can contain numerous types of values and they are the main\ncomponent of a worksheet." }, { "code": null, "e": 1881, "s": 1671, "text": "To work with excel in Selenium with python, we need to take help of OpenPyXL\nlibrary. This library is responsible for reading and writing operations on Excel,\nhaving the extensions like xlsx, xlsm, xltm, xltx." }, { "code": null, "e": 1963, "s": 1881, "text": "To install OpenPyXL library, we have to execute the command pip install openpyxl." }, { "code": null, "e": 2127, "s": 1963, "text": "This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel." }, { "code": null, "e": 2404, "s": 2127, "text": "To get the value inside the worksheet, first of all we need to load the entire\nworkbook by specifying the path where it is located. This is achieved with\nload_workbook() method. Next we need to identify the active sheet among all the\nworksheets with the help of active method." }, { "code": null, "e": 2684, "s": 2404, "text": "To access a cell inside the active worksheet, we need the help of row and column\nnumber and the cell method which accepts the row and column number as\narguments. For example, to point to the cell corresponding to row 2 and column 3,\nwe need to mention sheet.cell(row=2,column=3)." }, { "code": null, "e": 2795, "s": 2684, "text": "After identification of the cell, we need to use a value method to extract the value\nout of our required cell." }, { "code": null, "e": 2963, "s": 2795, "text": "wrkbk = load_workbook(\"C:\\\\work\\\\SeleniumPython.xlsx\")\n# to identify the active sheet\nsh = wrkbk.active\n# get the value of row 2 and column 3\nc=sh.cell(row=2,column=3)" }, { "code": null, "e": 3024, "s": 2963, "text": "Coding Implementation to get the value of a particular cell." }, { "code": null, "e": 3299, "s": 3024, "text": "import openpyxl\n# load excel with its path\nwrkbk = load_workbook(\"C:\\\\work\\\\SeleniumPython.xlsx\")\n# to get the active work sheet\nsh = wrkbk.active\n# get the value of row 2 and column 3\nc=sh.cell(row=2,column=3\n# to print the value in console\nprint(\" The value is \", c.value)" } ]
How to display JTextArea in the form of a table with GridLayout in Java?
Display a component in the form of rows and columns using the GridLayout. Here, we have set a panel, within which we will create a layout with 3 rows and 5 columns − JPanel panel = new JPanel(new GridLayout(3, 5, 5, 5)); Now, loop through and display JTextArea from 1 to 15 i.e. 3 rows and 5 columns − for (int i = 1; i <= 15; i++) { panel.add(new JTextArea("Displaying TextArea "+String.valueOf(i))); } The following is an example to display text area in the form of a table with GridLayout - package my; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("GridLayout Demo"); JPanel panel = new JPanel(new GridLayout(3, 5, 5, 5)); for (int i = 1; i <= 15; i++) { panel.add(new JTextArea("Displaying TextArea "+String.valueOf(i))); } frame.add(panel); frame.setSize(650, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1228, "s": 1062, "text": "Display a component in the form of rows and columns using the GridLayout. Here, we have set a panel, within which we will create a layout with 3 rows and 5 columns −" }, { "code": null, "e": 1283, "s": 1228, "text": "JPanel panel = new JPanel(new GridLayout(3, 5, 5, 5));" }, { "code": null, "e": 1364, "s": 1283, "text": "Now, loop through and display JTextArea from 1 to 15 i.e. 3 rows and 5 columns −" }, { "code": null, "e": 1469, "s": 1364, "text": "for (int i = 1; i <= 15; i++) {\n panel.add(new JTextArea(\"Displaying TextArea \"+String.valueOf(i)));\n}" }, { "code": null, "e": 1559, "s": 1469, "text": "The following is an example to display text area in the form of a table with GridLayout -" }, { "code": null, "e": 2080, "s": 1559, "text": "package my;\nimport java.awt.GridLayout;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JTextArea;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"GridLayout Demo\");\n JPanel panel = new JPanel(new GridLayout(3, 5, 5, 5));\n for (int i = 1; i <= 15; i++) {\n panel.add(new JTextArea(\"Displaying TextArea \"+String.valueOf(i)));\n }\n frame.add(panel);\n frame.setSize(650, 300);\n frame.setVisible(true);\n }\n}" } ]
Valid Parenthesis String in C++
Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid. To solve this, we will follow these steps − Traverse through the expression until it has exhaustedif the current character is opening bracket like (, { or [, then push into stackif the current character is closing bracket like ), } or ], then pop from stack, andcheck whether the popped bracket is corresponding starting bracket of thecurrent character, then it is fine, otherwise, that is not balanced. if the current character is opening bracket like (, { or [, then push into stack if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced. After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced. Let us see the following implementation to get better understanding − Live Demo #include <iostream> #include <stack> using namespace std; bool isBalancedExp(string exp) { stack<char> stk; char x; for (int i=0; i<exp.length(); i++) { if (exp[i]=='('||exp[i]=='['||exp[i]=='{') { stk.push(exp[i]); continue; } if (stk.empty()) return false; switch (exp[i]) { case ')': x = stk.top(); stk.pop(); if (x=='{' || x=='[') return false; break; case '}': x = stk.top(); stk.pop(); if (x=='(' || x=='[') return false; break; case ']': x = stk.top(); stk.pop(); if (x =='(' || x == '{') return false; break; } } return (stk.empty()); } int main() { string expresion = "()[(){()}]"; if (isBalancedExp(expresion)) cout << "This is Balanced Expression"; else cout << "This is Not Balanced Expression"; } "()[(){()}]" This is Balanced Expression
[ { "code": null, "e": 1314, "s": 1062, "text": "Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid." }, { "code": null, "e": 1358, "s": 1314, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1718, "s": 1358, "text": "Traverse through the expression until it has exhaustedif the current character is opening bracket like (, { or [, then push into stackif the current character is closing bracket like ), } or ], then pop from stack, andcheck whether the popped bracket is corresponding starting bracket of thecurrent character, then it is fine, otherwise, that is not balanced." }, { "code": null, "e": 1799, "s": 1718, "text": "if the current character is opening bracket like (, { or [, then push into stack" }, { "code": null, "e": 1884, "s": 1799, "text": "if the current character is closing bracket like ), } or ], then pop from stack, and" }, { "code": null, "e": 1958, "s": 1884, "text": "check whether the popped bracket is corresponding starting bracket of the" }, { "code": null, "e": 2027, "s": 1958, "text": "current character, then it is fine, otherwise, that is not balanced." }, { "code": null, "e": 2147, "s": 2027, "text": "After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced." }, { "code": null, "e": 2217, "s": 2147, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2228, "s": 2217, "text": " Live Demo" }, { "code": null, "e": 3193, "s": 2228, "text": "#include <iostream>\n#include <stack>\nusing namespace std;\nbool isBalancedExp(string exp) {\n stack<char> stk;\n char x;\n for (int i=0; i<exp.length(); i++) {\n if (exp[i]=='('||exp[i]=='['||exp[i]=='{') {\n stk.push(exp[i]);\n continue;\n }\n if (stk.empty())\n return false;\n switch (exp[i]) {\n case ')':\n x = stk.top();\n stk.pop();\n if (x=='{' || x=='[')\n return false;\n break;\n case '}':\n x = stk.top();\n stk.pop();\n if (x=='(' || x=='[')\n return false;\n break;\n case ']':\n x = stk.top();\n stk.pop();\n if (x =='(' || x == '{')\n return false;\n break;\n }\n }\n return (stk.empty());\n}\nint main() {\n string expresion = \"()[(){()}]\";\n if (isBalancedExp(expresion))\n cout << \"This is Balanced Expression\";\n else\n cout << \"This is Not Balanced Expression\";\n}" }, { "code": null, "e": 3206, "s": 3193, "text": "\"()[(){()}]\"" }, { "code": null, "e": 3234, "s": 3206, "text": "This is Balanced Expression" } ]
How to create bulk users in the active directory using PowerShell?
To create bulk users in the AD using PowerShell, there are multiple methods. For example, let say if you want to create 50 sample users for the lab environment without considering the other required properties, then you can use the below command, $pass = Read-Host "Enter Account Password " -AsSecureString 1..50 | foreach{ New-ADUser -Name "TempUser$_" -AccountPassword $pass -Path "OU=LabUsers,DC=labdomain,DC=local" -ChangePasswordAtLogon $true -Enabled $true -PasThru} The above command will create 50 Temp users in the OU named LABUSERS and one time we need to enter the password while running the script and when users log in with the same password, they need to change password at logon individually. Another way to create bulk users in the active directory is using the text files containing AD users. For example, $pass = Read-Host "Enter Account Password " foreach($ADAccount in (Get-Content c:\temp\ADAccounts.txt)){ New-ADUser -Name $ADAccount -AccountPassword $pass - Path "OU=LabUsers,DC=labdomain,DC=local" -ChangePasswordAtLogon $true -Enabled $true } In the above example, a list of AD Accounts in the text file called ADAccounts.txt is placed at c:\temp. This is the best way to create multiple users account with multiple properties as a CSV file. We can store the data into the CSV file and can jump on each line to create the user account with that specific properties. Suppose we have a CSV file stored in the folder C:\temp and the file name called NewUsers.CSV. The content of the file is as below. Code is as below. $pass = Read-Host "Enter AD user password " foreach($account in (Import-Csv C:\Temp\NewUsers.csv)){ New-ADUser -Name $account.Name ` -DisplayName $account.FirstName ` -Surname $account.Surname ` -EmployeeID $account.EMPNumber ` -Country $account.Country ` -Path "OU=LabUsers,DC=labdomain,DC=local" ` -Enabled $true ` -AccountPassword $pass ` -ChangePasswordAtLogon $true ` -PassThru }
[ { "code": null, "e": 1309, "s": 1062, "text": "To create bulk users in the AD using PowerShell, there are multiple methods. For example, let say if you want to create 50 sample users for the lab environment without considering the other required properties, then you can use the below command," }, { "code": null, "e": 1535, "s": 1309, "text": "$pass = Read-Host \"Enter Account Password \" -AsSecureString 1..50 | foreach{ New-ADUser -Name \"TempUser$_\" -AccountPassword $pass -Path \"OU=LabUsers,DC=labdomain,DC=local\" -ChangePasswordAtLogon $true -Enabled $true -PasThru}" }, { "code": null, "e": 1770, "s": 1535, "text": "The above command will create 50 Temp users in the OU named LABUSERS and one time we need to enter the password while running the script and when users log in with the same password, they need to change password at logon individually." }, { "code": null, "e": 1885, "s": 1770, "text": "Another way to create bulk users in the active directory is using the text files containing AD users. For example," }, { "code": null, "e": 2130, "s": 1885, "text": "$pass = Read-Host \"Enter Account Password \" foreach($ADAccount in (Get-Content c:\\temp\\ADAccounts.txt)){ New-ADUser -Name $ADAccount -AccountPassword $pass - Path \"OU=LabUsers,DC=labdomain,DC=local\" -ChangePasswordAtLogon $true -Enabled $true }" }, { "code": null, "e": 2235, "s": 2130, "text": "In the above example, a list of AD Accounts in the text file called ADAccounts.txt is placed at c:\\temp." }, { "code": null, "e": 2453, "s": 2235, "text": "This is the best way to create multiple users account with multiple properties as a CSV file. We can store the data into the CSV file and can jump on each line to create the user account with that specific properties." }, { "code": null, "e": 2585, "s": 2453, "text": "Suppose we have a CSV file stored in the folder C:\\temp and the file name called NewUsers.CSV. The content of the file is as below." }, { "code": null, "e": 2603, "s": 2585, "text": "Code is as below." }, { "code": null, "e": 2988, "s": 2603, "text": "$pass = Read-Host \"Enter AD user password \" foreach($account in (Import-Csv C:\\Temp\\NewUsers.csv)){\nNew-ADUser -Name $account.Name ` -DisplayName $account.FirstName `\n-Surname $account.Surname `\n-EmployeeID $account.EMPNumber ` -Country $account.Country `\n-Path \"OU=LabUsers,DC=labdomain,DC=local\" ` -Enabled $true `\n-AccountPassword $pass ` -ChangePasswordAtLogon $true `\n-PassThru }" } ]
Java Swing Login Example | Swing Login with Validations
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws This example shows you how to create a simple swing login form. Java Swing Login form with required validations. package com.swing.examples; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; public class LoginDemo extends JFrame implements ActionListener { JPanel panel; JLabel user_label, password_label, message; JTextField userName_text; JPasswordField password_text; JButton submit, cancel; LoginDemo() { // User Label user_label = new JLabel(); user_label.setText("User Name :"); userName_text = new JTextField(); // Password password_label = new JLabel(); password_label.setText("Password :"); password_text = new JPasswordField(); // Submit submit = new JButton("SUBMIT"); panel = new JPanel(new GridLayout(3, 1)); panel.add(user_label); panel.add(userName_text); panel.add(password_label); panel.add(password_text); message = new JLabel(); panel.add(message); panel.add(submit); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Adding the listeners to components.. submit.addActionListener(this); add(panel, BorderLayout.CENTER); setTitle("Please Login Here !"); setSize(300, 100); setVisible(true); } public static void main(String[] args) { new LoginDemo(); } @Override public void actionPerformed(ActionEvent ae) { String userName = userName_text.getText(); String password = password_text.getText(); if (userName.trim().equals("admin") && password.trim().equals("admin")) { message.setText(" Hello " + userName + ""); } else { message.setText(" Invalid user.. "); } } } Swing Login form out put with basic validations : User : admin Password : admin Error Validation : Success Validation : Happy Learning 🙂 How to change Look and Feel of Swing setLookAndFeel Java JComboBox Editable Example Java Swing JLabel Example Java Swing JSplitPane Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing Advanced JTable Example Java Swing JTabbedPane Example Java Swing JMenu Example Java Swing JToolBar Example Java Swing JOptionPane Example Java Swing JTree Example How to create Java Smiley Swing How to create Java Rainbow using Swing Java Swing BorderFactory Example How to change Look and Feel of Swing setLookAndFeel Java JComboBox Editable Example Java Swing JLabel Example Java Swing JSplitPane Example Java Swing ProgressBar Example Java Swing JTable Example Java Swing Advanced JTable Example Java Swing JTabbedPane Example Java Swing JMenu Example Java Swing JToolBar Example Java Swing JOptionPane Example Java Swing JTree Example How to create Java Smiley Swing How to create Java Rainbow using Swing Java Swing BorderFactory Example Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 462, "s": 398, "text": "This example shows you how to create a simple swing login form." }, { "code": null, "e": 511, "s": 462, "text": "Java Swing Login form with required validations." }, { "code": null, "e": 2602, "s": 511, "text": "package com.swing.examples;\n\nimport java.awt.BorderLayout;\nimport java.awt.GridLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\n\npublic class LoginDemo extends JFrame implements ActionListener {\n\n JPanel panel;\n JLabel user_label, password_label, message;\n JTextField userName_text;\n JPasswordField password_text;\n JButton submit, cancel;\n\n LoginDemo() {\n \n // User Label\n user_label = new JLabel();\n user_label.setText(\"User Name :\");\n userName_text = new JTextField();\n \n // Password\n\n password_label = new JLabel();\n password_label.setText(\"Password :\");\n password_text = new JPasswordField();\n\n // Submit\n\n submit = new JButton(\"SUBMIT\");\n\n panel = new JPanel(new GridLayout(3, 1));\n\n panel.add(user_label);\n panel.add(userName_text);\n panel.add(password_label);\n panel.add(password_text);\n\n message = new JLabel();\n panel.add(message);\n panel.add(submit);\n \n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n // Adding the listeners to components..\n submit.addActionListener(this);\n add(panel, BorderLayout.CENTER);\n setTitle(\"Please Login Here !\");\n setSize(300, 100);\n setVisible(true);\n\n }\n\n public static void main(String[] args) {\n new LoginDemo();\n }\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n String userName = userName_text.getText();\n String password = password_text.getText();\n if (userName.trim().equals(\"admin\") && password.trim().equals(\"admin\")) {\n message.setText(\" Hello \" + userName\n + \"\");\n } else {\n message.setText(\" Invalid user.. \");\n }\n\n }\n\n}" }, { "code": null, "e": 2682, "s": 2602, "text": "Swing Login form out put with basic validations :\nUser : admin\nPassword : admin" }, { "code": null, "e": 2703, "s": 2682, "text": "\nError Validation :\n" }, { "code": null, "e": 2741, "s": 2703, "text": "Success Validation : Happy Learning 🙂" }, { "code": null, "e": 3219, "s": 2741, "text": "\nHow to change Look and Feel of Swing setLookAndFeel\nJava JComboBox Editable Example\nJava Swing JLabel Example\nJava Swing JSplitPane Example\nJava Swing ProgressBar Example\nJava Swing JTable Example\nJava Swing Advanced JTable Example\nJava Swing JTabbedPane Example\nJava Swing JMenu Example\nJava Swing JToolBar Example\nJava Swing JOptionPane Example\nJava Swing JTree Example\nHow to create Java Smiley Swing\nHow to create Java Rainbow using Swing\nJava Swing BorderFactory Example\n" }, { "code": null, "e": 3271, "s": 3219, "text": "How to change Look and Feel of Swing setLookAndFeel" }, { "code": null, "e": 3303, "s": 3271, "text": "Java JComboBox Editable Example" }, { "code": null, "e": 3329, "s": 3303, "text": "Java Swing JLabel Example" }, { "code": null, "e": 3359, "s": 3329, "text": "Java Swing JSplitPane Example" }, { "code": null, "e": 3390, "s": 3359, "text": "Java Swing ProgressBar Example" }, { "code": null, "e": 3416, "s": 3390, "text": "Java Swing JTable Example" }, { "code": null, "e": 3451, "s": 3416, "text": "Java Swing Advanced JTable Example" }, { "code": null, "e": 3482, "s": 3451, "text": "Java Swing JTabbedPane Example" }, { "code": null, "e": 3507, "s": 3482, "text": "Java Swing JMenu Example" }, { "code": null, "e": 3535, "s": 3507, "text": "Java Swing JToolBar Example" }, { "code": null, "e": 3566, "s": 3535, "text": "Java Swing JOptionPane Example" }, { "code": null, "e": 3591, "s": 3566, "text": "Java Swing JTree Example" }, { "code": null, "e": 3623, "s": 3591, "text": "How to create Java Smiley Swing" }, { "code": null, "e": 3662, "s": 3623, "text": "How to create Java Rainbow using Swing" }, { "code": null, "e": 3695, "s": 3662, "text": "Java Swing BorderFactory Example" }, { "code": null, "e": 3701, "s": 3699, "text": "Δ" }, { "code": null, "e": 3725, "s": 3701, "text": " Install Java on Mac OS" }, { "code": null, "e": 3753, "s": 3725, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3782, "s": 3753, "text": " Install Minikube on Windows" }, { "code": null, "e": 3817, "s": 3782, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3844, "s": 3817, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3871, "s": 3844, "text": " Install Gradle on Windows" }, { "code": null, "e": 3900, "s": 3871, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3926, "s": 3900, "text": " Install PuTTY on windows" }, { "code": null, "e": 3952, "s": 3926, "text": " Install Mysql on Windows" }, { "code": null, "e": 3988, "s": 3952, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 4022, "s": 3988, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 4048, "s": 4022, "text": " Install Maven on Windows" }, { "code": null, "e": 4073, "s": 4048, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 4107, "s": 4073, "text": " Install Maven on Windows Command" }, { "code": null, "e": 4142, "s": 4107, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 4166, "s": 4142, "text": " Install Ant on Windows" }, { "code": null, "e": 4195, "s": 4166, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 4227, "s": 4195, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 4260, "s": 4227, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 4285, "s": 4260, "text": " Java8 – Install Windows" }, { "code": null, "e": 4302, "s": 4285, "text": " Java8 – foreach" }, { "code": null, "e": 4330, "s": 4302, "text": " Java8 – forEach with index" }, { "code": null, "e": 4361, "s": 4330, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 4393, "s": 4361, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 4413, "s": 4393, "text": " Java8 – GroupingBy" }, { "code": null, "e": 4433, "s": 4413, "text": " Java8 – SummingInt" }, { "code": null, "e": 4457, "s": 4433, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 4487, "s": 4457, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 4519, "s": 4487, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 4555, "s": 4519, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 4599, "s": 4555, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 4631, "s": 4599, "text": " Howto – Convert List to String" }, { "code": null, "e": 4672, "s": 4631, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 4709, "s": 4672, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4749, "s": 4709, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 4778, "s": 4749, "text": " Howto – Convert List to Map" }, { "code": null, "e": 4810, "s": 4778, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 4830, "s": 4810, "text": " Howto – Sort a Map" }, { "code": null, "e": 4852, "s": 4830, "text": " Howto – Filter a Map" }, { "code": null, "e": 4882, "s": 4852, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 4933, "s": 4882, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 4969, "s": 4933, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 5001, "s": 4969, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 5036, "s": 5001, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 5059, "s": 5036, "text": " Howto – Merge Streams" }, { "code": null, "e": 5106, "s": 5059, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 5131, "s": 5106, "text": " Howto -Get Stream count" }, { "code": null, "e": 5175, "s": 5131, "text": " Howto – Get Min and Max values in a Stream" } ]
Data Structure and Algorithms Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection. Linear Search ( Array A, Value x) Step 1: Set i to 1 Step 2: if i > n then go to step 7 Step 3: if A[i] = x then go to step 6 Step 4: Set i to i + 1 Step 5: Go to Step 2 Step 6: Print Element x Found at index i and go to step 8 Step 7: Print element not found Step 8: Exit procedure linear_search (list, value) for each item in the list if match item == value return the item's location end if end for end procedure To know about linear search implementation in C programming language, please click-here. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2861, "s": 2580, "text": "Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection." }, { "code": null, "e": 3136, "s": 2861, "text": "Linear Search ( Array A, Value x)\n\nStep 1: Set i to 1\nStep 2: if i > n then go to step 7\nStep 3: if A[i] = x then go to step 6\nStep 4: Set i to i + 1\nStep 5: Go to Step 2\nStep 6: Print Element x Found at index i and go to step 8\nStep 7: Print element not found\nStep 8: Exit\n" }, { "code": null, "e": 3308, "s": 3136, "text": "procedure linear_search (list, value)\n\n for each item in the list\n if match item == value\n return the item's location\n end if\n end for\n\nend procedure" }, { "code": null, "e": 3397, "s": 3308, "text": "To know about linear search implementation in C programming language, please click-here." }, { "code": null, "e": 3432, "s": 3397, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3444, "s": 3432, "text": " Ravi Kiran" }, { "code": null, "e": 3479, "s": 3444, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 3498, "s": 3479, "text": " Arnab Chakraborty" }, { "code": null, "e": 3533, "s": 3498, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3548, "s": 3533, "text": " Parth Panjabi" }, { "code": null, "e": 3581, "s": 3548, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 3600, "s": 3581, "text": " Arnab Chakraborty" }, { "code": null, "e": 3634, "s": 3600, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3662, "s": 3634, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3698, "s": 3662, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3726, "s": 3698, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3733, "s": 3726, "text": " Print" }, { "code": null, "e": 3744, "s": 3733, "text": " Add Notes" } ]
How to Check the Battery Level in Android Programmatically? - GeeksforGeeks
23 Feb, 2021 Sometimes, it is useful to determine the current battery level. One may choose to reduce the rate of your background updates if the battery charge is below a certain level. But one cannot continuously monitor the battery state. In general, the impact of constantly monitoring the battery level has a more significant impact on the battery than the application’s normal behavior. So it’s always better to only monitor substantial changes in battery level. A sample GIF 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 Kotlin 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 Kotlin as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file, which represents the UI of the project. Add a Button, so whenever the user will click on the Button a Toast message with battery percentage will be popped up on the screen. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/showBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="show battery percentage" /> </RelativeLayout> Step 3: Working with the MainActivity.kt file Finally, go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.BatteryManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare button, that will show battery percentage when clicked val btn = findViewById<Button>(R.id.showBtn) btn.setOnClickListener{ // Call battery manager service val bm = applicationContext.getSystemService(BATTERY_SERVICE) as BatteryManager // Get the battery percentage and store it in a INT variable val batLevel:Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) // Display the variable using a Toast Toast.makeText(applicationContext,"Battery is $batLevel%",Toast.LENGTH_LONG).show() } }} Android-Misc Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android 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 Android UI Layouts Retrofit with Kotlin Coroutine in Android Kotlin Array Android Menus MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25036, "s": 25008, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25658, "s": 25036, "text": "Sometimes, it is useful to determine the current battery level. One may choose to reduce the rate of your background updates if the battery charge is below a certain level. But one cannot continuously monitor the battery state. In general, the impact of constantly monitoring the battery level has a more significant impact on the battery than the application’s normal behavior. So it’s always better to only monitor substantial changes in battery level. A sample GIF 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 Kotlin language. " }, { "code": null, "e": 25687, "s": 25658, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25851, "s": 25687, "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 Kotlin as the programming language." }, { "code": null, "e": 25899, "s": 25851, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 26156, "s": 25899, "text": "Go to the activity_main.xml file, which represents the UI of the project. Add a Button, so whenever the user will click on the Button a Toast message with battery percentage will be popped up on the screen. Below is the code for the activity_main.xml file." }, { "code": null, "e": 26160, "s": 26156, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/showBtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"show battery percentage\" /> </RelativeLayout>", "e": 26747, "s": 26160, "text": null }, { "code": null, "e": 26793, "s": 26747, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 26986, "s": 26793, "text": "Finally, go to the MainActivity.kt file, and refer the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 26993, "s": 26986, "text": "Kotlin" }, { "code": "import android.os.BatteryManagerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare button, that will show battery percentage when clicked val btn = findViewById<Button>(R.id.showBtn) btn.setOnClickListener{ // Call battery manager service val bm = applicationContext.getSystemService(BATTERY_SERVICE) as BatteryManager // Get the battery percentage and store it in a INT variable val batLevel:Int = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) // Display the variable using a Toast Toast.makeText(applicationContext,\"Battery is $batLevel%\",Toast.LENGTH_LONG).show() } }}", "e": 27943, "s": 26993, "text": null }, { "code": null, "e": 27956, "s": 27943, "text": "Android-Misc" }, { "code": null, "e": 27964, "s": 27956, "text": "Android" }, { "code": null, "e": 27971, "s": 27964, "text": "Kotlin" }, { "code": null, "e": 27979, "s": 27971, "text": "Android" }, { "code": null, "e": 28077, "s": 27979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28086, "s": 28077, "text": "Comments" }, { "code": null, "e": 28099, "s": 28086, "text": "Old Comments" }, { "code": null, "e": 28141, "s": 28099, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28180, "s": 28141, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28230, "s": 28180, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 28281, "s": 28230, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 28319, "s": 28281, "text": "Android Listview in Java with Example" }, { "code": null, "e": 28338, "s": 28319, "text": "Android UI Layouts" }, { "code": null, "e": 28380, "s": 28338, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28393, "s": 28380, "text": "Kotlin Array" }, { "code": null, "e": 28407, "s": 28393, "text": "Android Menus" } ]
How to write a case insensitive Python regular expression without re.compile?
We can pass re.IGNORECASE to the flags parameter of search, match, or sub − import re print (re.search('bush', 'BuSh', re.IGNORECASE)) print (re.match('bush', 'BuSh', re.IGNORECASE)) print (re.sub('bush', 'xxxx', 'Bushmeat', flags=re.IGNORECASE)) <_sre.SRE_Match object at 0x0000000005316648> <_sre.SRE_Match object at 0x0000000005316648> xxxxmeat
[ { "code": null, "e": 1138, "s": 1062, "text": "We can pass re.IGNORECASE to the flags parameter of search, match, or sub −" }, { "code": null, "e": 1309, "s": 1138, "text": "import re\nprint (re.search('bush', 'BuSh', re.IGNORECASE))\nprint (re.match('bush', 'BuSh', re.IGNORECASE))\nprint (re.sub('bush', 'xxxx', 'Bushmeat', flags=re.IGNORECASE))" }, { "code": null, "e": 1410, "s": 1309, "text": "<_sre.SRE_Match object at 0x0000000005316648>\n<_sre.SRE_Match object at 0x0000000005316648>\nxxxxmeat" } ]
Convert from float to String in Java
To convert float to string, use the toString() method. It represents a value in a string. Let’s say the following is our float. float f = 0.9F; Converting the float value to string. String s = Float.toString(f); Let us see the complete example to convert float to String in Java with output. Live Demo public class Demo { public static void main(String args[]) { float f = 0.9F; String s = Float.toString(f); System.out.println(s); } } 0.9
[ { "code": null, "e": 1152, "s": 1062, "text": "To convert float to string, use the toString() method. It represents a value in a string." }, { "code": null, "e": 1190, "s": 1152, "text": "Let’s say the following is our float." }, { "code": null, "e": 1206, "s": 1190, "text": "float f = 0.9F;" }, { "code": null, "e": 1244, "s": 1206, "text": "Converting the float value to string." }, { "code": null, "e": 1274, "s": 1244, "text": "String s = Float.toString(f);" }, { "code": null, "e": 1354, "s": 1274, "text": "Let us see the complete example to convert float to String in Java with output." }, { "code": null, "e": 1365, "s": 1354, "text": " Live Demo" }, { "code": null, "e": 1523, "s": 1365, "text": "public class Demo {\n public static void main(String args[]) {\n float f = 0.9F;\n String s = Float.toString(f);\n System.out.println(s);\n }\n}" }, { "code": null, "e": 1527, "s": 1523, "text": "0.9" } ]
How to search a string in backwards direction in Python?
Python has a rfind() method which searches from the end of a string for the occurrence of a substring. It returns the index of the last occurrence if found, else -1. You can use it as follows: >>> "CocacolaPepsi".rfind('cola') 4 >>> 'CocacolaPepsi'.rfind('coke') -1
[ { "code": null, "e": 1255, "s": 1062, "text": "Python has a rfind() method which searches from the end of a string for the occurrence of a substring. It returns the index of the last occurrence if found, else -1. You can use it as follows:" }, { "code": null, "e": 1328, "s": 1255, "text": ">>> \"CocacolaPepsi\".rfind('cola')\n4\n>>> 'CocacolaPepsi'.rfind('coke')\n-1" } ]
Maximum consecutive numbers present in an array in C++
We are given with an array of positive integers. The goal is to find the maximum number of consecutive numbers present in it. First of all we will sort the array and then compare adjacent elements arr[j]==arr[i]+1 (j=i+1), if difference is 1 then increment count and indexes i++,j++ else change count=1. Store the maximum count found so far stored in maxc. Arr[]= { 100,21,24,73,22,23 } Maximum consecutive numbers in array : 4 Explanation − Sorted array is − { 21,22,23,24,73,100 } initialize count=1,maxcount=1 1. 22=21+1 count=2 maxcount=2 i++,j++ 2. 23=22+2 count=3 maxcount=3 i++,j++ 3. 24=23+1 count=4 maxcount=4 i++,j++ 4. 73=24+1 X count=1 maxcount=4 i++,j++ 5. 100=73+1 X count=1 maxcount=4 i++,j++ Maximum consecutive numbers is 4 { 21,22,23,24 } Arr[]= { 11,41,21,42,61,43,9,44 } Maximum consecutive numbers in array : 4 Explanation − Sorted array is − { 9,11,21,41,42,43,44,61 } initialize count=1,maxcount=1 1. 11=9+1 X count=1 maxcount=1 i++,j++ 2. 21=11+1 X count=1 maxcount=1 i++,j++ 3. 41=21+1 X count=1 maxcount=1 i++,j++ 4. 42=41+1 count=2 maxcount=2 i++,j++ 5. 43=42+1 count=3 maxcount=3 i++,j++ 6. 44=43+1 count=4 maxcount=4 i++,j++ 7. 61=44+1 X count=1 maxcount=4 i++,j++ Maximum consecutive numbers is 4 { 41,42,43,44 } The integer array Arr[] is used to store the integers. The integer array Arr[] is used to store the integers. Integer ‘n’ stores the length of the array. Integer ‘n’ stores the length of the array. Function subs( int arr[], int n) takes an array , its size as input and returns the maximum consecutive numbers present in the array. Function subs( int arr[], int n) takes an array , its size as input and returns the maximum consecutive numbers present in the array. First of all we will sort the array using sort(arr,arr+n) First of all we will sort the array using sort(arr,arr+n) Now initialize the count=1 and maxc=1. Now initialize the count=1 and maxc=1. Starting from the first two elements, arr[0] and arr[1] inside two for loops, compare if arr[j]==arr[i]+1 ( j=i+1), if true then increment count and i by 1. Starting from the first two elements, arr[0] and arr[1] inside two for loops, compare if arr[j]==arr[i]+1 ( j=i+1), if true then increment count and i by 1. If the above condition is false again change count to 1. Update maxc with highest count found so far ( maxc=count>maxc?count:maxc ). If the above condition is false again change count to 1. Update maxc with highest count found so far ( maxc=count>maxc?count:maxc ). In the end return maxc as number of maximum consecutive elements as result. In the end return maxc as number of maximum consecutive elements as result. Live Demo #include <iostream> #include <algorithm> using namespace std; int subs(int arr[],int n){ std::sort(arr,arr+n); int count=1; int maxc=1; for(int i=0;i<n-1;i++){ for(int j=i+1;j<n;j++){ if(arr[j]==arr[i]+1){ count++; i++; } else count=1; maxc=count>maxc?count:maxc; } } return maxc; } int main(){ int arr[] = { 10,9,8,7,3,2,1,4,5,6 }; int n = sizeof(arr) / sizeof(int); cout << "Maximum consecutive numbers present in an array :"<<subs(arr, n); return 0; } Maximum consecutive numbers present in an array : 10
[ { "code": null, "e": 1419, "s": 1062, "text": "We are given with an array of positive integers. The goal is to find the maximum number of\nconsecutive numbers present in it. First of all we will sort the array and then compare adjacent\nelements arr[j]==arr[i]+1 (j=i+1), if difference is 1 then increment count and indexes i++,j++ else\nchange count=1. Store the maximum count found so far stored in maxc." }, { "code": null, "e": 1449, "s": 1419, "text": "Arr[]= { 100,21,24,73,22,23 }" }, { "code": null, "e": 1490, "s": 1449, "text": "Maximum consecutive numbers in array : 4" }, { "code": null, "e": 1575, "s": 1490, "text": "Explanation − Sorted array is − { 21,22,23,24,73,100 } initialize count=1,maxcount=1" }, { "code": null, "e": 1770, "s": 1575, "text": "1. 22=21+1 count=2 maxcount=2 i++,j++\n2. 23=22+2 count=3 maxcount=3 i++,j++\n3. 24=23+1 count=4 maxcount=4 i++,j++\n4. 73=24+1 X count=1 maxcount=4 i++,j++\n5. 100=73+1 X count=1 maxcount=4 i++,j++" }, { "code": null, "e": 1819, "s": 1770, "text": "Maximum consecutive numbers is 4 { 21,22,23,24 }" }, { "code": null, "e": 1853, "s": 1819, "text": "Arr[]= { 11,41,21,42,61,43,9,44 }" }, { "code": null, "e": 1894, "s": 1853, "text": "Maximum consecutive numbers in array : 4" }, { "code": null, "e": 1983, "s": 1894, "text": "Explanation − Sorted array is − { 9,11,21,41,42,43,44,61 } initialize count=1,maxcount=1" }, { "code": null, "e": 2256, "s": 1983, "text": "1. 11=9+1 X count=1 maxcount=1 i++,j++\n2. 21=11+1 X count=1 maxcount=1 i++,j++\n3. 41=21+1 X count=1 maxcount=1 i++,j++\n4. 42=41+1 count=2 maxcount=2 i++,j++\n5. 43=42+1 count=3 maxcount=3 i++,j++\n6. 44=43+1 count=4 maxcount=4 i++,j++\n7. 61=44+1 X count=1 maxcount=4 i++,j++" }, { "code": null, "e": 2305, "s": 2256, "text": "Maximum consecutive numbers is 4 { 41,42,43,44 }" }, { "code": null, "e": 2360, "s": 2305, "text": "The integer array Arr[] is used to store the integers." }, { "code": null, "e": 2415, "s": 2360, "text": "The integer array Arr[] is used to store the integers." }, { "code": null, "e": 2459, "s": 2415, "text": "Integer ‘n’ stores the length of the array." }, { "code": null, "e": 2503, "s": 2459, "text": "Integer ‘n’ stores the length of the array." }, { "code": null, "e": 2637, "s": 2503, "text": "Function subs( int arr[], int n) takes an array , its size as input and returns the maximum\nconsecutive numbers present in the array." }, { "code": null, "e": 2771, "s": 2637, "text": "Function subs( int arr[], int n) takes an array , its size as input and returns the maximum\nconsecutive numbers present in the array." }, { "code": null, "e": 2829, "s": 2771, "text": "First of all we will sort the array using sort(arr,arr+n)" }, { "code": null, "e": 2887, "s": 2829, "text": "First of all we will sort the array using sort(arr,arr+n)" }, { "code": null, "e": 2926, "s": 2887, "text": "Now initialize the count=1 and maxc=1." }, { "code": null, "e": 2965, "s": 2926, "text": "Now initialize the count=1 and maxc=1." }, { "code": null, "e": 3122, "s": 2965, "text": "Starting from the first two elements, arr[0] and arr[1] inside two for loops, compare if\narr[j]==arr[i]+1 ( j=i+1), if true then increment count and i by 1." }, { "code": null, "e": 3279, "s": 3122, "text": "Starting from the first two elements, arr[0] and arr[1] inside two for loops, compare if\narr[j]==arr[i]+1 ( j=i+1), if true then increment count and i by 1." }, { "code": null, "e": 3412, "s": 3279, "text": "If the above condition is false again change count to 1. Update maxc with highest count\nfound so far ( maxc=count>maxc?count:maxc )." }, { "code": null, "e": 3545, "s": 3412, "text": "If the above condition is false again change count to 1. Update maxc with highest count\nfound so far ( maxc=count>maxc?count:maxc )." }, { "code": null, "e": 3621, "s": 3545, "text": "In the end return maxc as number of maximum consecutive elements as result." }, { "code": null, "e": 3697, "s": 3621, "text": "In the end return maxc as number of maximum consecutive elements as result." }, { "code": null, "e": 3708, "s": 3697, "text": " Live Demo" }, { "code": null, "e": 4278, "s": 3708, "text": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nint subs(int arr[],int n){\n std::sort(arr,arr+n);\n int count=1;\n int maxc=1;\n for(int i=0;i<n-1;i++){\n for(int j=i+1;j<n;j++){\n if(arr[j]==arr[i]+1){\n count++;\n i++;\n }\n else\n count=1;\n maxc=count>maxc?count:maxc;\n }\n }\n return maxc;\n}\nint main(){\n int arr[] = { 10,9,8,7,3,2,1,4,5,6 };\n int n = sizeof(arr) / sizeof(int);\n cout << \"Maximum consecutive numbers present in an array :\"<<subs(arr, n);\n return 0;\n}" }, { "code": null, "e": 4331, "s": 4278, "text": "Maximum consecutive numbers present in an array : 10" } ]
ReactJS UI Ant Design Notification Component - GeeksforGeeks
01 Jun, 2021 Ant Design Library has this component pre-built, and it is very easy to integrate as well. Notification Component is used to display a notification message globally. We can use the following approach in ReactJS to use the Ant Design Notification Component. Notification Config Props: bottom: When the placement is bottomRight or bottomLeft, it is used to denote the distance from the bottom of the viewport. btn: It is used for the customized close button. className: It is used for the customized CSS class. closeIcon: It is used for the custom close icon. description: It is used to denote the content of the notification box. duration: It is used to set the time before Notification is closed. Unit is seconds. getContainer: It is used to return the mount node for the notification. icon: It is used for the customized icon. key: It is used for the unique identity of the Notification. message: It is used to denote the title of the notification box. placement: It is used to position the Notification. Values can be topLeft, topRight, bottomLeft, and bottomRight. style: It is used for the customized inline style. top: When placement is topRight or topLeft, it is used to denote the distance from the top of the viewport. onClick: It is a callback function that is triggered when the notification is clicked. onClose: It is a callback function that is triggered when the notification is closed. Notification Default Config Props: bottom: When the placement is bottomRight or bottomLeft, it is used to denote the distance from the bottom of the viewport. closeIcon: It is used for the custom close icon. duration: It is used to set the time before Notification is closed. Unit is seconds. getContainer: It is used to return the mount node for the notification. placement: It is used to position the Notification. Values can be topLeft, topRight, bottomLeft, and bottomRight. rtl: It is used to indicate whether to enable RTL mode or not. top: When placement is topRight or topLeft, it is used to denote the distance from the top of the viewport. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd Step 3: After creating the ReactJS application, Install the required module using the following command: npm install antd Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import "antd/dist/antd.css";import { Button, notification } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Notification Component</h4> <Button type="primary" onClick={() => { notification.open({ message: 'Sample-Notification-Title', description: 'Sample Notification Description', onClick: () => { console.log('Notification Clicked!'); }, }); }}> Click to see Notification Box </Button> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://ant.design/components/notification/ ReactJS-Ant Design ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? Create a Responsive Navbar using ReactJS How to pass data from one component to other component in ReactJS ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 34158, "s": 34130, "text": "\n01 Jun, 2021" }, { "code": null, "e": 34415, "s": 34158, "text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Notification Component is used to display a notification message globally. We can use the following approach in ReactJS to use the Ant Design Notification Component." }, { "code": null, "e": 34442, "s": 34415, "text": "Notification Config Props:" }, { "code": null, "e": 34566, "s": 34442, "text": "bottom: When the placement is bottomRight or bottomLeft, it is used to denote the distance from the bottom of the viewport." }, { "code": null, "e": 34615, "s": 34566, "text": "btn: It is used for the customized close button." }, { "code": null, "e": 34667, "s": 34615, "text": "className: It is used for the customized CSS class." }, { "code": null, "e": 34716, "s": 34667, "text": "closeIcon: It is used for the custom close icon." }, { "code": null, "e": 34787, "s": 34716, "text": "description: It is used to denote the content of the notification box." }, { "code": null, "e": 34872, "s": 34787, "text": "duration: It is used to set the time before Notification is closed. Unit is seconds." }, { "code": null, "e": 34944, "s": 34872, "text": "getContainer: It is used to return the mount node for the notification." }, { "code": null, "e": 34986, "s": 34944, "text": "icon: It is used for the customized icon." }, { "code": null, "e": 35047, "s": 34986, "text": "key: It is used for the unique identity of the Notification." }, { "code": null, "e": 35112, "s": 35047, "text": "message: It is used to denote the title of the notification box." }, { "code": null, "e": 35226, "s": 35112, "text": "placement: It is used to position the Notification. Values can be topLeft, topRight, bottomLeft, and bottomRight." }, { "code": null, "e": 35277, "s": 35226, "text": "style: It is used for the customized inline style." }, { "code": null, "e": 35385, "s": 35277, "text": "top: When placement is topRight or topLeft, it is used to denote the distance from the top of the viewport." }, { "code": null, "e": 35472, "s": 35385, "text": "onClick: It is a callback function that is triggered when the notification is clicked." }, { "code": null, "e": 35558, "s": 35472, "text": "onClose: It is a callback function that is triggered when the notification is closed." }, { "code": null, "e": 35593, "s": 35558, "text": "Notification Default Config Props:" }, { "code": null, "e": 35717, "s": 35593, "text": "bottom: When the placement is bottomRight or bottomLeft, it is used to denote the distance from the bottom of the viewport." }, { "code": null, "e": 35766, "s": 35717, "text": "closeIcon: It is used for the custom close icon." }, { "code": null, "e": 35851, "s": 35766, "text": "duration: It is used to set the time before Notification is closed. Unit is seconds." }, { "code": null, "e": 35923, "s": 35851, "text": "getContainer: It is used to return the mount node for the notification." }, { "code": null, "e": 36037, "s": 35923, "text": "placement: It is used to position the Notification. Values can be topLeft, topRight, bottomLeft, and bottomRight." }, { "code": null, "e": 36100, "s": 36037, "text": "rtl: It is used to indicate whether to enable RTL mode or not." }, { "code": null, "e": 36208, "s": 36100, "text": "top: When placement is topRight or topLeft, it is used to denote the distance from the top of the viewport." }, { "code": null, "e": 36258, "s": 36208, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 36353, "s": 36258, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 36417, "s": 36353, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 36449, "s": 36417, "text": "npx create-react-app foldername" }, { "code": null, "e": 36562, "s": 36449, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 36662, "s": 36562, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 36676, "s": 36662, "text": "cd foldername" }, { "code": null, "e": 36797, "s": 36676, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd" }, { "code": null, "e": 36902, "s": 36797, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 36919, "s": 36902, "text": "npm install antd" }, { "code": null, "e": 36971, "s": 36919, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 36989, "s": 36971, "text": "Project Structure" }, { "code": null, "e": 37119, "s": 36989, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 37126, "s": 37119, "text": "App.js" }, { "code": "import React from 'react'import \"antd/dist/antd.css\";import { Button, notification } from 'antd'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Notification Component</h4> <Button type=\"primary\" onClick={() => { notification.open({ message: 'Sample-Notification-Title', description: 'Sample Notification Description', onClick: () => { console.log('Notification Clicked!'); }, }); }}> Click to see Notification Box </Button> </div> );}", "e": 37755, "s": 37126, "text": null }, { "code": null, "e": 37868, "s": 37755, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 37878, "s": 37868, "text": "npm start" }, { "code": null, "e": 37977, "s": 37878, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 38032, "s": 37977, "text": "Reference: https://ant.design/components/notification/" }, { "code": null, "e": 38051, "s": 38032, "text": "ReactJS-Ant Design" }, { "code": null, "e": 38059, "s": 38051, "text": "ReactJS" }, { "code": null, "e": 38076, "s": 38059, "text": "Web Technologies" }, { "code": null, "e": 38174, "s": 38076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38183, "s": 38174, "text": "Comments" }, { "code": null, "e": 38196, "s": 38183, "text": "Old Comments" }, { "code": null, "e": 38239, "s": 38196, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38284, "s": 38239, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 38349, "s": 38284, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 38390, "s": 38349, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 38458, "s": 38390, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 38500, "s": 38458, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 38533, "s": 38500, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38595, "s": 38533, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 38638, "s": 38595, "text": "How to fetch data from an API in ReactJS ?" } ]
How to extract variables of an S4 object in R?
Suppose we want to create an S4 with defined name data and two numerical columns called by x and y then we can use setClass("data",representation(x1="numeric",x2="numeric")). Now, if we want to extract the variables of this S4 object then we would need to use @ sign instead of $ sign as in a data frame. > setClass("data1",representation(x1="numeric",x2="numeric")) > data1<-new("data1",x1=rnorm(20),x2=rexp(20,1.12)) > data1 An object of class "data1" Slot "x1": [1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292 [6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297 [11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861 [16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000 Slot "x2": [1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064 [7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206 [13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841 [19] 0.22643380 2.06821215 Extracting x1 and x2: > data1@x1 [1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292 [6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297 [11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861 [16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000 > data1@x2 [1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064 [7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206 [13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841 [19] 0.22643380 2.06821215 > setClass("data2",representation(x1="integer",x2="numeric")) > data2<-new("data2",x1=rpois(200,5),x2=rexp(50,1.12)) > data2 An object of class "data2" Slot "x1": [1] 3 7 4 8 5 7 5 11 6 4 5 3 2 7 5 5 4 3 7 8 12 6 10 6 3 [26] 7 7 6 4 2 6 6 8 7 8 8 5 2 3 4 7 2 4 1 3 4 7 4 10 5 [51] 7 2 4 3 8 6 4 4 6 7 8 4 5 5 3 4 2 7 7 6 1 6 3 5 2 [76] 5 6 7 3 7 5 7 5 8 2 4 4 2 3 6 1 6 5 5 3 4 3 8 5 7 [101] 4 3 8 2 6 3 3 5 1 2 4 6 4 6 2 4 4 4 4 9 4 4 7 2 9 [126] 4 3 4 3 4 7 5 5 2 2 6 4 6 5 5 6 8 4 7 6 3 7 7 7 8 [151] 8 6 4 7 4 4 3 10 4 6 2 5 5 4 4 6 7 5 7 0 6 8 5 8 9 [176] 3 5 5 4 8 4 4 6 5 7 9 6 2 2 2 5 9 3 5 3 3 4 6 2 6 Slot "x2": [1] 0.03141964 0.49307236 0.31423727 0.43521757 0.52619093 0.70795201 [7] 0.35462825 0.59378101 0.10527933 0.70027538 0.44882733 0.43956142 [13] 0.09664605 0.50706106 1.65260142 0.36428909 0.61297587 1.01703946 [19] 0.89316946 0.59825470 1.32223944 1.77853473 0.19214180 4.76283291 [25] 0.51096582 1.07728540 0.94746461 1.03008930 0.80508219 2.91018171 [31] 0.13807893 0.98123535 0.71989867 1.32550897 0.86492233 0.06968105 [37] 0.75559512 0.27958713 0.18840316 1.39449247 3.78111847 0.26038046 [43] 0.02072275 0.81411699 0.89175522 0.13439256 1.16051005 1.00565524 [49] 0.44863428 0.59886756 Extracting x1 and x2: > data2@x1 [1] 3 7 4 8 5 7 5 11 6 4 5 3 2 7 5 5 4 3 7 8 12 6 10 6 3 [26] 7 7 6 4 2 6 6 8 7 8 8 5 2 3 4 7 2 4 1 3 4 7 4 10 5 [51] 7 2 4 3 8 6 4 4 6 7 8 4 5 5 3 4 2 7 7 6 1 6 3 5 2 [76] 5 6 7 3 7 5 7 5 8 2 4 4 2 3 6 1 6 5 5 3 4 3 8 5 7 [101] 4 3 8 2 6 3 3 5 1 2 4 6 4 6 2 4 4 4 4 9 4 4 7 2 9 [126] 4 3 4 3 4 7 5 5 2 2 6 4 6 5 5 6 8 4 7 6 3 7 7 7 8 [151] 8 6 4 7 4 4 3 10 4 6 2 5 5 4 4 6 7 5 7 0 6 8 5 8 9 [176] 3 5 5 4 8 4 4 6 5 7 9 6 2 2 2 5 9 3 5 3 3 4 6 2 6 > data2@x2 [1] 0.03141964 0.49307236 0.31423727 0.43521757 0.52619093 0.70795201 [7] 0.35462825 0.59378101 0.10527933 0.70027538 0.44882733 0.43956142 [13] 0.09664605 0.50706106 1.65260142 0.36428909 0.61297587 1.01703946 [19] 0.89316946 0.59825470 1.32223944 1.77853473 0.19214180 4.76283291 [25] 0.51096582 1.07728540 0.94746461 1.03008930 0.80508219 2.91018171 [31] 0.13807893 0.98123535 0.71989867 1.32550897 0.86492233 0.06968105 [37] 0.75559512 0.27958713 0.18840316 1.39449247 3.78111847 0.26038046 [43] 0.02072275 0.81411699 0.89175522 0.13439256 1.16051005 1.00565524 [49] 0.44863428 0.59886756 > setClass("data3",representation(x1="character",x2="numeric")) > data3<-new("data3",x1=sample(LETTERS[1:4],50,replace=TRUE),x2=rexp(50,1.12)) > data3 An object of class "data3" Slot "x1": [1] "C" "D" "A" "C" "D" "D" "C" "D" "C" "A" "A" "B" "C" "D" "C" "D" "C" "A" "D" [20] "C" "C" "A" "B" "B" "C" "D" "D" "B" "B" "C" "A" "C" "D" "A" "C" "D" "A" "C" [39] "C" "C" "B" "C" "B" "B" "D" "C" "A" "C" "A" "A" Slot "x2": [1] 0.15262639 0.18257750 0.66531800 0.90077904 0.31199878 0.15326597 [7] 0.14915567 0.09891334 1.91290294 1.64658850 0.17738544 0.07428495 [13] 0.51221999 1.19112341 0.16764472 1.29586175 0.67945778 0.33704154 [19] 0.21145555 0.28791368 0.95651553 0.48383674 0.76274501 0.71038690 [25] 1.34688895 1.77748828 0.63969314 0.29701294 0.04734766 1.02116237 [31] 0.27368908 0.04268661 0.77449047 3.70772112 0.40526753 0.06333750 [37] 0.26435011 1.03701168 0.08280528 0.86331936 0.15271265 1.45303032 [43] 0.04458336 0.54749522 0.44025731 0.20837975 0.21421977 0.16732185 [49] 1.46172264 0.70931165 Extracting x1 and x2: > data3@x1 [1] "C" "D" "A" "C" "D" "D" "C" "D" "C" "A" "A" "B" "C" "D" "C" "D" "C" "A" "D" [20] "C" "C" "A" "B" "B" "C" "D" "D" "B" "B" "C" "A" "C" "D" "A" "C" "D" "A" "C" [39] "C" "C" "B" "C" "B" "B" "D" "C" "A" "C" "A" "A" > data3@x2 [1] 0.15262639 0.18257750 0.66531800 0.90077904 0.31199878 0.15326597 [7] 0.14915567 0.09891334 1.91290294 1.64658850 0.17738544 0.07428495 [13] 0.51221999 1.19112341 0.16764472 1.29586175 0.67945778 0.33704154 [19] 0.21145555 0.28791368 0.95651553 0.48383674 0.76274501 0.71038690 [25] 1.34688895 1.77748828 0.63969314 0.29701294 0.04734766 1.02116237 [31] 0.27368908 0.04268661 0.77449047 3.70772112 0.40526753 0.06333750 [37] 0.26435011 1.03701168 0.08280528 0.86331936 0.15271265 1.45303032 [43] 0.04458336 0.54749522 0.44025731 0.20837975 0.21421977 0.16732185 [49] 1.46172264 0.70931165 > setClass("data4",representation(x1="logical",x2="numeric")) > data4<-new("data4",x1=sample(as.logical(c(0,1)),50,replace=TRUE),x2=rnorm(50,1,0.50)) > data4 An object of class "data4" Slot "x1": [1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE [13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE [25] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE [37] TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE [49] TRUE FALSE Slot "x2": [1] 1.4535492 0.8230134 0.9926188 0.9236218 0.9568131 1.2355998 [7] -0.2649343 1.4839302 0.6435250 0.8384010 1.4399601 1.3696312 [13] 0.2847440 0.6539318 1.2568808 1.4457016 1.1884043 1.3024577 [19] 1.5923689 1.2796569 0.9942924 0.6104080 0.4510600 0.9901056 [25] 0.9496257 1.1278555 0.5048898 1.0492706 1.5142966 0.8459955 [31] 1.4398791 1.0121801 0.9473674 0.2266796 1.3360711 0.2354370 [37] 0.4838408 1.4131759 0.1566150 1.4218652 1.1542315 2.0074517 [43] 1.0019310 0.3909861 0.6707586 0.9373494 1.4065083 0.1781948 [49] 1.4708116 1.1577926 Extracting x1 and x2: > data4@x1 [1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE [13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE [25] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE [37] TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE [49] TRUE FALSE > data4@x2 [1] 1.4535492 0.8230134 0.9926188 0.9236218 0.9568131 1.2355998 [7] -0.2649343 1.4839302 0.6435250 0.8384010 1.4399601 1.3696312 [13] 0.2847440 0.6539318 1.2568808 1.4457016 1.1884043 1.3024577 [19] 1.5923689 1.2796569 0.9942924 0.6104080 0.4510600 0.9901056 [25] 0.9496257 1.1278555 0.5048898 1.0492706 1.5142966 0.8459955 [31] 1.4398791 1.0121801 0.9473674 0.2266796 1.3360711 0.2354370 [37] 0.4838408 1.4131759 0.1566150 1.4218652 1.1542315 2.0074517 [43] 1.0019310 0.3909861 0.6707586 0.9373494 1.4065083 0.1781948 [49] 1.4708116 1.1577926
[ { "code": null, "e": 1367, "s": 1062, "text": "Suppose we want to create an S4 with defined name data and two numerical columns called by x and y then we can use setClass(\"data\",representation(x1=\"numeric\",x2=\"numeric\")). Now, if we want to extract the variables of this S4 object then we would need to use @ sign instead of $ sign as in a data frame." }, { "code": null, "e": 1489, "s": 1367, "text": "> setClass(\"data1\",representation(x1=\"numeric\",x2=\"numeric\"))\n> data1<-new(\"data1\",x1=rnorm(20),x2=rexp(20,1.12))\n> data1" }, { "code": null, "e": 2044, "s": 1489, "text": "An object of class \"data1\"\nSlot \"x1\":\n[1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292\n[6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297\n[11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861\n[16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000\n\nSlot \"x2\":\n[1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064\n[7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206\n[13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841\n[19] 0.22643380 2.06821215" }, { "code": null, "e": 2066, "s": 2044, "text": "Extracting x1 and x2:" }, { "code": null, "e": 2077, "s": 2066, "text": "> data1@x1" }, { "code": null, "e": 2344, "s": 2077, "text": "[1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292\n[6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297\n[11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861\n[16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000" }, { "code": null, "e": 2355, "s": 2344, "text": "> data1@x2" }, { "code": null, "e": 2593, "s": 2355, "text": "[1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064\n[7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206\n[13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841\n[19] 0.22643380 2.06821215" }, { "code": null, "e": 2718, "s": 2593, "text": "> setClass(\"data2\",representation(x1=\"integer\",x2=\"numeric\"))\n> data2<-new(\"data2\",x1=rpois(200,5),x2=rexp(50,1.12))\n> data2" }, { "code": null, "e": 3810, "s": 2718, "text": "An object of class \"data2\"\nSlot \"x1\":\n[1] 3 7 4 8 5 7 5 11 6 4 5 3 2 7 5 5 4 3 7 8 12 6 10 6 3\n[26] 7 7 6 4 2 6 6 8 7 8 8 5 2 3 4 7 2 4 1 3 4 7 4 10 5\n[51] 7 2 4 3 8 6 4 4 6 7 8 4 5 5 3 4 2 7 7 6 1 6 3 5 2\n[76] 5 6 7 3 7 5 7 5 8 2 4 4 2 3 6 1 6 5 5 3 4 3 8 5 7\n[101] 4 3 8 2 6 3 3 5 1 2 4 6 4 6 2 4 4 4 4 9 4 4 7 2 9\n[126] 4 3 4 3 4 7 5 5 2 2 6 4 6 5 5 6 8 4 7 6 3 7 7 7 8\n[151] 8 6 4 7 4 4 3 10 4 6 2 5 5 4 4 6 7 5 7 0 6 8 5 8 9\n[176] 3 5 5 4 8 4 4 6 5 7 9 6 2 2 2 5 9 3 5 3 3 4 6 2 6\n\nSlot \"x2\":\n[1] 0.03141964 0.49307236 0.31423727 0.43521757 0.52619093 0.70795201\n[7] 0.35462825 0.59378101 0.10527933 0.70027538 0.44882733 0.43956142\n[13] 0.09664605 0.50706106 1.65260142 0.36428909 0.61297587 1.01703946\n[19] 0.89316946 0.59825470 1.32223944 1.77853473 0.19214180 4.76283291\n[25] 0.51096582 1.07728540 0.94746461 1.03008930 0.80508219 2.91018171\n[31] 0.13807893 0.98123535 0.71989867 1.32550897 0.86492233 0.06968105\n[37] 0.75559512 0.27958713 0.18840316 1.39449247 3.78111847 0.26038046\n[43] 0.02072275 0.81411699 0.89175522 0.13439256 1.16051005 1.00565524\n[49] 0.44863428 0.59886756" }, { "code": null, "e": 3832, "s": 3810, "text": "Extracting x1 and x2:" }, { "code": null, "e": 3843, "s": 3832, "text": "> data2@x1" }, { "code": null, "e": 4291, "s": 3843, "text": "[1] 3 7 4 8 5 7 5 11 6 4 5 3 2 7 5 5 4 3 7 8 12 6 10 6 3\n[26] 7 7 6 4 2 6 6 8 7 8 8 5 2 3 4 7 2 4 1 3 4 7 4 10 5\n[51] 7 2 4 3 8 6 4 4 6 7 8 4 5 5 3 4 2 7 7 6 1 6 3 5 2\n[76] 5 6 7 3 7 5 7 5 8 2 4 4 2 3 6 1 6 5 5 3 4 3 8 5 7\n[101] 4 3 8 2 6 3 3 5 1 2 4 6 4 6 2 4 4 4 4 9 4 4 7 2 9\n[126] 4 3 4 3 4 7 5 5 2 2 6 4 6 5 5 6 8 4 7 6 3 7 7 7 8\n[151] 8 6 4 7 4 4 3 10 4 6 2 5 5 4 4 6 7 5 7 0 6 8 5 8 9\n[176] 3 5 5 4 8 4 4 6 5 7 9 6 2 2 2 5 9 3 5 3 3 4 6 2 6" }, { "code": null, "e": 4302, "s": 4291, "text": "> data2@x2" }, { "code": null, "e": 4897, "s": 4302, "text": "[1] 0.03141964 0.49307236 0.31423727 0.43521757 0.52619093 0.70795201\n[7] 0.35462825 0.59378101 0.10527933 0.70027538 0.44882733 0.43956142\n[13] 0.09664605 0.50706106 1.65260142 0.36428909 0.61297587 1.01703946\n[19] 0.89316946 0.59825470 1.32223944 1.77853473 0.19214180 4.76283291\n[25] 0.51096582 1.07728540 0.94746461 1.03008930 0.80508219 2.91018171\n[31] 0.13807893 0.98123535 0.71989867 1.32550897 0.86492233 0.06968105\n[37] 0.75559512 0.27958713 0.18840316 1.39449247 3.78111847 0.26038046\n[43] 0.02072275 0.81411699 0.89175522 0.13439256 1.16051005 1.00565524\n[49] 0.44863428 0.59886756" }, { "code": null, "e": 5048, "s": 4897, "text": "> setClass(\"data3\",representation(x1=\"character\",x2=\"numeric\"))\n> data3<-new(\"data3\",x1=sample(LETTERS[1:4],50,replace=TRUE),x2=rexp(50,1.12))\n> data3" }, { "code": null, "e": 5905, "s": 5048, "text": "An object of class \"data3\"\nSlot \"x1\":\n[1] \"C\" \"D\" \"A\" \"C\" \"D\" \"D\" \"C\" \"D\" \"C\" \"A\" \"A\" \"B\" \"C\" \"D\" \"C\" \"D\" \"C\" \"A\" \"D\"\n[20] \"C\" \"C\" \"A\" \"B\" \"B\" \"C\" \"D\" \"D\" \"B\" \"B\" \"C\" \"A\" \"C\" \"D\" \"A\" \"C\" \"D\" \"A\" \"C\"\n[39] \"C\" \"C\" \"B\" \"C\" \"B\" \"B\" \"D\" \"C\" \"A\" \"C\" \"A\" \"A\"\n\nSlot \"x2\":\n[1] 0.15262639 0.18257750 0.66531800 0.90077904 0.31199878 0.15326597\n[7] 0.14915567 0.09891334 1.91290294 1.64658850 0.17738544 0.07428495\n[13] 0.51221999 1.19112341 0.16764472 1.29586175 0.67945778 0.33704154\n[19] 0.21145555 0.28791368 0.95651553 0.48383674 0.76274501 0.71038690\n[25] 1.34688895 1.77748828 0.63969314 0.29701294 0.04734766 1.02116237\n[31] 0.27368908 0.04268661 0.77449047 3.70772112 0.40526753 0.06333750\n[37] 0.26435011 1.03701168 0.08280528 0.86331936 0.15271265 1.45303032\n[43] 0.04458336 0.54749522 0.44025731 0.20837975 0.21421977 0.16732185\n[49] 1.46172264 0.70931165" }, { "code": null, "e": 5927, "s": 5905, "text": "Extracting x1 and x2:" }, { "code": null, "e": 5938, "s": 5927, "text": "> data3@x1" }, { "code": null, "e": 6152, "s": 5938, "text": "[1] \"C\" \"D\" \"A\" \"C\" \"D\" \"D\" \"C\" \"D\" \"C\" \"A\" \"A\" \"B\" \"C\" \"D\" \"C\" \"D\" \"C\" \"A\" \"D\"\n[20] \"C\" \"C\" \"A\" \"B\" \"B\" \"C\" \"D\" \"D\" \"B\" \"B\" \"C\" \"A\" \"C\" \"D\" \"A\" \"C\" \"D\" \"A\" \"C\"\n[39] \"C\" \"C\" \"B\" \"C\" \"B\" \"B\" \"D\" \"C\" \"A\" \"C\" \"A\" \"A\"" }, { "code": null, "e": 6163, "s": 6152, "text": "> data3@x2" }, { "code": null, "e": 6756, "s": 6163, "text": "[1] 0.15262639 0.18257750 0.66531800 0.90077904 0.31199878 0.15326597\n[7] 0.14915567 0.09891334 1.91290294 1.64658850 0.17738544 0.07428495\n[13] 0.51221999 1.19112341 0.16764472 1.29586175 0.67945778 0.33704154\n[19] 0.21145555 0.28791368 0.95651553 0.48383674 0.76274501 0.71038690\n[25] 1.34688895 1.77748828 0.63969314 0.29701294 0.04734766 1.02116237\n[31] 0.27368908 0.04268661 0.77449047 3.70772112 0.40526753 0.06333750\n[37] 0.26435011 1.03701168 0.08280528 0.86331936 0.15271265 1.45303032\n[43] 0.04458336 0.54749522 0.44025731 0.20837975 0.21421977 0.16732185\n[49] 1.46172264 0.70931165" }, { "code": null, "e": 6914, "s": 6756, "text": "> setClass(\"data4\",representation(x1=\"logical\",x2=\"numeric\"))\n> data4<-new(\"data4\",x1=sample(as.logical(c(0,1)),50,replace=TRUE),x2=rnorm(50,1,0.50))\n> data4" }, { "code": null, "e": 7804, "s": 6914, "text": "An object of class \"data4\"\nSlot \"x1\":\n[1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE\n[13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE\n[25] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE\n[37] TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE\n[49] TRUE FALSE\n\nSlot \"x2\":\n[1] 1.4535492 0.8230134 0.9926188 0.9236218 0.9568131 1.2355998\n[7] -0.2649343 1.4839302 0.6435250 0.8384010 1.4399601 1.3696312\n[13] 0.2847440 0.6539318 1.2568808 1.4457016 1.1884043 1.3024577\n[19] 1.5923689 1.2796569 0.9942924 0.6104080 0.4510600 0.9901056\n[25] 0.9496257 1.1278555 0.5048898 1.0492706 1.5142966 0.8459955\n[31] 1.4398791 1.0121801 0.9473674 0.2266796 1.3360711 0.2354370\n[37] 0.4838408 1.4131759 0.1566150 1.4218652 1.1542315 2.0074517\n[43] 1.0019310 0.3909861 0.6707586 0.9373494 1.4065083 0.1781948\n[49] 1.4708116 1.1577926" }, { "code": null, "e": 7826, "s": 7804, "text": "Extracting x1 and x2:" }, { "code": null, "e": 7837, "s": 7826, "text": "> data4@x1" }, { "code": null, "e": 8133, "s": 7837, "text": "[1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE\n[13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE\n[25] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE\n[37] TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE\n[49] TRUE FALSE" }, { "code": null, "e": 8144, "s": 8133, "text": "> data4@x2" }, { "code": null, "e": 8688, "s": 8144, "text": "[1] 1.4535492 0.8230134 0.9926188 0.9236218 0.9568131 1.2355998\n[7] -0.2649343 1.4839302 0.6435250 0.8384010 1.4399601 1.3696312\n[13] 0.2847440 0.6539318 1.2568808 1.4457016 1.1884043 1.3024577\n[19] 1.5923689 1.2796569 0.9942924 0.6104080 0.4510600 0.9901056\n[25] 0.9496257 1.1278555 0.5048898 1.0492706 1.5142966 0.8459955\n[31] 1.4398791 1.0121801 0.9473674 0.2266796 1.3360711 0.2354370\n[37] 0.4838408 1.4131759 0.1566150 1.4218652 1.1542315 2.0074517\n[43] 1.0019310 0.3909861 0.6707586 0.9373494 1.4065083 0.1781948\n[49] 1.4708116 1.1577926" } ]
How to customize search bar in Next.js - GeeksforGeeks
22 Oct, 2021 In this article, we will learn How we can add a customized search bar in the NextJS project using Algolia. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally. Approach: To add our customized search bar first we are going to create an account in algolia that enables us to search content in milliseconds. After that, we will get the API keys that we will use later in our app. Then we will create a new index to upload our data. On the homepage of our app, we will fetch the data from algolia using the API keys and algoliasearch module. Then we will create our customized search bar. Step 1: You can create a new NextJs project using the below command: npx create-next-app gfg Step 2: To add Algolia search in our project we are going to install two modules: npm install algoliasearch react-instantsearch-dom Project Structure: It will look like the following. Step 3: Setting up Algolia. Algolia enables developers to build next-generation apps with APIs that deliver relevant content in milliseconds. So to use algolia first create a free account and get the API keys of that account. 1. To get the API keys Go to settings > API Keys 2. After that create an index and upload the data that you want to search. You can upload the data in json, csv format or by using their API. For this example, I am uploading the below data. Title, Tag, Day GFG1, python, Monday GFG2, java, Tuesday GFG3, css, Wednesday GFG4, html, Thursday GFG5, react, Friday GFG6, nextjs, Saturday Step 4: Now we will create a custom search bar for our app. For this, we will create a new file inside a new component folder with the below content. Javascript import { connectSearchBox } from 'react-instantsearch-dom'; function SearchBar({ currentRefinement, isSearchStalled, refine }) { return ( <form noValidate action="" role="search"> <input value={currentRefinement} onChange={event => refine(event.currentTarget.value)} placeholder="Search any term" style={{ height:'40px',width:'280px',borderRadius:"10px"}} title='Search bar' /> </form> )} export default connectSearchBox(SearchBar); Step 5: Now we can use the API to add the customized search in NextJs Project. After that to use our customized search bar we are going to add the below code in the index.js file. Javascript // Importing modulesimport algoliasearch from "algoliasearch/lite";import { InstantSearch, SearchBox, Hits } from "react-instantsearch-dom";import SearchBar from "../component/CustomSearch"; const searchClient = algoliasearch( APPLICATION_API_KEY, SEARCH_ONLY_API_KEY,); export default function CustomizedSearch() { return ( <> <InstantSearch searchClient={searchClient} indexName="gfg_dev"> {/* Adding Search Box */} <SearchBar/> {/* Adding Data */} <Hits /> </InstantSearch> </> );} You can also add styling using CSS in our custom search bar. Steps to run the application: Run the app using the below command in the terminal. npm run dev Next.js NodeJS-Questions JavaScript Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 26805, "s": 26777, "text": "\n22 Oct, 2021" }, { "code": null, "e": 27142, "s": 26805, "text": "In this article, we will learn How we can add a customized search bar in the NextJS project using Algolia. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally." }, { "code": null, "e": 27567, "s": 27142, "text": "Approach: To add our customized search bar first we are going to create an account in algolia that enables us to search content in milliseconds. After that, we will get the API keys that we will use later in our app. Then we will create a new index to upload our data. On the homepage of our app, we will fetch the data from algolia using the API keys and algoliasearch module. Then we will create our customized search bar." }, { "code": null, "e": 27636, "s": 27567, "text": "Step 1: You can create a new NextJs project using the below command:" }, { "code": null, "e": 27660, "s": 27636, "text": "npx create-next-app gfg" }, { "code": null, "e": 27742, "s": 27660, "text": "Step 2: To add Algolia search in our project we are going to install two modules:" }, { "code": null, "e": 27792, "s": 27742, "text": "npm install algoliasearch react-instantsearch-dom" }, { "code": null, "e": 27844, "s": 27792, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28070, "s": 27844, "text": "Step 3: Setting up Algolia. Algolia enables developers to build next-generation apps with APIs that deliver relevant content in milliseconds. So to use algolia first create a free account and get the API keys of that account." }, { "code": null, "e": 28119, "s": 28070, "text": "1. To get the API keys Go to settings > API Keys" }, { "code": null, "e": 28261, "s": 28119, "text": "2. After that create an index and upload the data that you want to search. You can upload the data in json, csv format or by using their API." }, { "code": null, "e": 28310, "s": 28261, "text": "For this example, I am uploading the below data." }, { "code": null, "e": 28452, "s": 28310, "text": "Title, Tag, Day\nGFG1, python, Monday\nGFG2, java, Tuesday\nGFG3, css, Wednesday\nGFG4, html, Thursday\nGFG5, react, Friday\nGFG6, nextjs, Saturday" }, { "code": null, "e": 28604, "s": 28452, "text": "Step 4: Now we will create a custom search bar for our app. For this, we will create a new file inside a new component folder with the below content. " }, { "code": null, "e": 28615, "s": 28604, "text": "Javascript" }, { "code": "import { connectSearchBox } from 'react-instantsearch-dom'; function SearchBar({ currentRefinement, isSearchStalled, refine }) { return ( <form noValidate action=\"\" role=\"search\"> <input value={currentRefinement} onChange={event => refine(event.currentTarget.value)} placeholder=\"Search any term\" style={{ height:'40px',width:'280px',borderRadius:\"10px\"}} title='Search bar' /> </form> )} export default connectSearchBox(SearchBar);", "e": 29136, "s": 28615, "text": null }, { "code": null, "e": 29317, "s": 29136, "text": "Step 5: Now we can use the API to add the customized search in NextJs Project. After that to use our customized search bar we are going to add the below code in the index.js file." }, { "code": null, "e": 29328, "s": 29317, "text": "Javascript" }, { "code": "// Importing modulesimport algoliasearch from \"algoliasearch/lite\";import { InstantSearch, SearchBox, Hits } from \"react-instantsearch-dom\";import SearchBar from \"../component/CustomSearch\"; const searchClient = algoliasearch( APPLICATION_API_KEY, SEARCH_ONLY_API_KEY,); export default function CustomizedSearch() { return ( <> <InstantSearch searchClient={searchClient} indexName=\"gfg_dev\"> {/* Adding Search Box */} <SearchBar/> {/* Adding Data */} <Hits /> </InstantSearch> </> );}", "e": 29887, "s": 29328, "text": null }, { "code": null, "e": 29948, "s": 29887, "text": "You can also add styling using CSS in our custom search bar." }, { "code": null, "e": 30031, "s": 29948, "text": "Steps to run the application: Run the app using the below command in the terminal." }, { "code": null, "e": 30043, "s": 30031, "text": "npm run dev" }, { "code": null, "e": 30051, "s": 30043, "text": "Next.js" }, { "code": null, "e": 30068, "s": 30051, "text": "NodeJS-Questions" }, { "code": null, "e": 30079, "s": 30068, "text": "JavaScript" }, { "code": null, "e": 30087, "s": 30079, "text": "Node.js" }, { "code": null, "e": 30185, "s": 30087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30225, "s": 30185, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30286, "s": 30225, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30327, "s": 30286, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30349, "s": 30327, "text": "JavaScript | Promises" }, { "code": null, "e": 30403, "s": 30349, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30436, "s": 30403, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30484, "s": 30436, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30517, "s": 30484, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 30547, "s": 30517, "text": "Node.js fs.writeFile() Method" } ]
Unicornscan - Penetration Testing Tool in Kali Linux - GeeksforGeeks
24 Jun, 2021 Unicornscan is a free and open-source Automated Penetration Testing tool available on GitHub which is very useful for security researchers for information gathering and testing of the security of websites and web servers.Unicornscan provides many integrated tools to perform penetration testing on the target system. This tool is also known as an active web application security reconnaissance tool. This tool was designed as it should be accurate, scalable, flexible for the users who are using it. This tool is released under GPL General Public License. This tool offers and performs scanning of TCP and UDP network protocols. This tool is very useful for finding network discovery patterns. This tool is used to find remote hosts. Unicornscan can also give you information about the target operating system. Unicornscan can detect asynchronous TCP banner. Unicornscan can tell you information about OS, application and system service detection on the host. Unicornscan tool has ability to use custom data sets to perform reconnaissance. Unicornscan tool supports SQL relational output from networks. Unicornscan can perform TCP asynchronous scan on hosts Unicornscan can perform asynchronous UDP scan on hosts. Step 1: Use the following command to install the tool on your kali linux machine. sudo apt install unicorn Step 2: The tool has been downloaded into your kali linux machine. Now to open the flags and help menu of the tool use the following command. unicorn -h Now you can see that the tool is finally installed into your machine as the tool is opening its help menu. Now lets see some examples of how to use the tool. Example 1: Use the unicorn tool to scan a ip address to get details of open and closed ports of a website called adaptercart. sudo unicornscan -r30 -mT adaptercart.com You can see that it showing all the open ports this is how you can also use unicorn scan tool for your ip address or on your target host. Example 2: Use the unicorn tool to scan an ip address to get details of open and closed ports of a website called geeksforgeeks. sudo unicornscan -r30 -mT geeksforgeeks.org Two ports are opened on the site geeksforgeeks.org. This is how you can also perform Example 3 : Use the unicorn tool to scan a ip address to get details of open and closed ports of a website called google.com sudo unicornscan -r30 -mT google.com You can refer to above example to perform scanning on your target. Example 4: Use the Unicornscan tool to perform a UDP scan on the whole network sudo unicornscan –mU –v –I 192.168.1.1/24 Example 5: Use the Unicornscan tool to perform a TCP SYN Scan on a whole network. unicornscan -msf -v 192.168.1.1/24 Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n24 Jun, 2021" }, { "code": null, "e": 26462, "s": 25651, "text": "Unicornscan is a free and open-source Automated Penetration Testing tool available on GitHub which is very useful for security researchers for information gathering and testing of the security of websites and web servers.Unicornscan provides many integrated tools to perform penetration testing on the target system. This tool is also known as an active web application security reconnaissance tool. This tool was designed as it should be accurate, scalable, flexible for the users who are using it. This tool is released under GPL General Public License. This tool offers and performs scanning of TCP and UDP network protocols. This tool is very useful for finding network discovery patterns. This tool is used to find remote hosts. Unicornscan can also give you information about the target operating system." }, { "code": null, "e": 26510, "s": 26462, "text": "Unicornscan can detect asynchronous TCP banner." }, { "code": null, "e": 26611, "s": 26510, "text": "Unicornscan can tell you information about OS, application and system service detection on the host." }, { "code": null, "e": 26691, "s": 26611, "text": "Unicornscan tool has ability to use custom data sets to perform reconnaissance." }, { "code": null, "e": 26755, "s": 26691, "text": "Unicornscan tool supports SQL relational output from networks." }, { "code": null, "e": 26810, "s": 26755, "text": "Unicornscan can perform TCP asynchronous scan on hosts" }, { "code": null, "e": 26866, "s": 26810, "text": "Unicornscan can perform asynchronous UDP scan on hosts." }, { "code": null, "e": 26948, "s": 26866, "text": "Step 1: Use the following command to install the tool on your kali linux machine." }, { "code": null, "e": 26973, "s": 26948, "text": "sudo apt install unicorn" }, { "code": null, "e": 27115, "s": 26973, "text": "Step 2: The tool has been downloaded into your kali linux machine. Now to open the flags and help menu of the tool use the following command." }, { "code": null, "e": 27126, "s": 27115, "text": "unicorn -h" }, { "code": null, "e": 27285, "s": 27126, "text": " Now you can see that the tool is finally installed into your machine as the tool is opening its help menu. Now lets see some examples of how to use the tool." }, { "code": null, "e": 27297, "s": 27285, "text": "Example 1: " }, { "code": null, "e": 27412, "s": 27297, "text": "Use the unicorn tool to scan a ip address to get details of open and closed ports of a website called adaptercart." }, { "code": null, "e": 27454, "s": 27412, "text": "sudo unicornscan -r30 -mT adaptercart.com" }, { "code": null, "e": 27592, "s": 27454, "text": "You can see that it showing all the open ports this is how you can also use unicorn scan tool for your ip address or on your target host." }, { "code": null, "e": 27603, "s": 27592, "text": "Example 2:" }, { "code": null, "e": 27722, "s": 27603, "text": " Use the unicorn tool to scan an ip address to get details of open and closed ports of a website called geeksforgeeks." }, { "code": null, "e": 27766, "s": 27722, "text": "sudo unicornscan -r30 -mT geeksforgeeks.org" }, { "code": null, "e": 27853, "s": 27766, "text": "Two ports are opened on the site geeksforgeeks.org. This is how you can also perform " }, { "code": null, "e": 27866, "s": 27853, "text": "Example 3 : " }, { "code": null, "e": 27979, "s": 27866, "text": "Use the unicorn tool to scan a ip address to get details of open and closed ports of a website called google.com" }, { "code": null, "e": 28016, "s": 27979, "text": "sudo unicornscan -r30 -mT google.com" }, { "code": null, "e": 28083, "s": 28016, "text": "You can refer to above example to perform scanning on your target." }, { "code": null, "e": 28094, "s": 28083, "text": "Example 4:" }, { "code": null, "e": 28163, "s": 28094, "text": " Use the Unicornscan tool to perform a UDP scan on the whole network" }, { "code": null, "e": 28205, "s": 28163, "text": "sudo unicornscan –mU –v –I 192.168.1.1/24" }, { "code": null, "e": 28217, "s": 28205, "text": "Example 5: " }, { "code": null, "e": 28288, "s": 28217, "text": "Use the Unicornscan tool to perform a TCP SYN Scan on a whole network." }, { "code": null, "e": 28324, "s": 28288, "text": " unicornscan -msf -v 192.168.1.1/24" }, { "code": null, "e": 28335, "s": 28324, "text": "Kali-Linux" }, { "code": null, "e": 28347, "s": 28335, "text": "Linux-Tools" }, { "code": null, "e": 28358, "s": 28347, "text": "Linux-Unix" }, { "code": null, "e": 28456, "s": 28358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28491, "s": 28456, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28525, "s": 28491, "text": "mv command in Linux with examples" }, { "code": null, "e": 28551, "s": 28525, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28580, "s": 28551, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28617, "s": 28580, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28654, "s": 28617, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28696, "s": 28654, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28722, "s": 28696, "text": "Thread functions in C/C++" }, { "code": null, "e": 28758, "s": 28722, "text": "uniq Command in LINUX with examples" } ]
How to Label Image in Android using Firebase ML Kit? - GeeksforGeeks
24 Feb, 2021 We have seen many apps in Android in which we will detect the object present in the image whether it may be any object. In this article, we will take a look at the implementation of image labeling in Android using Firebase ML Kit. We will be building a simple application in which we will be capturing an image of any object and from that, we will detect the objects present inside our image with the accuracy level. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Connect your app to Firebase After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option below screenshot. After clicking on this option on the next screen click on Connect to Firebase option to connect your app to Firebase. Step 3: Adding dependency for language translation to build.gradle file Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. // dependency for firebase core. implementation’com.google.firebase:firebase-core:15.0.2′ // Firebase ML dependency implementation ‘com.google.firebase:firebase-ml-vision:24.0.3’ implementation ‘com.google.firebase:firebase-ml-vision-image-label-model:20.0.1’ Step 4: Adding permissions to access the Internet and meta-data in your Android Apps AndroidManifest file Navigate to the app > AndroidManifest.xml file and add the below code to it. Comments are added in the code to get to know in more detail. XML <!-- below line is use to add camera feature in our app --><uses-feature android:name="android.hardware.camera" android:required="true" /> <!-- permission for internet --><uses-permission android:name="android.permission.INTERNET" /> Add the below line inside your application tag. XML <meta-data android:name="com.google.firebase.ml.vision.DEPENDENCIES" android:value="label" /> Below is the complete code for the AndroidManifest.xml file. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.labelimage"> <!-- below line is use to add camera feature in our app --> <uses-feature android:name="android.hardware.camera" android:required="true" /> <!-- permission for internet --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.LabelImage"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.firebase.ml.vision.DEPENDENCIES" android:value="label" /> </application> </manifest> Step 5: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--image view for displaying our image--> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="300dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:scaleType="centerCrop" /> <LinearLayout android:id="@+id/idLLButtons" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/image" android:orientation="horizontal"> <!--button for capturing our image--> <Button android:id="@+id/snapbtn" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_marginTop="30dp" android:layout_weight="1" android:text="SNAP" android:textSize="25dp" android:textStyle="bold" /> <!--button for detecting the objects--> <Button android:id="@+id/labelBtn" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_marginTop="30dp" android:layout_weight="1" android:text="Label" android:textSize="25dp" android:textStyle="bold" /> </LinearLayout> <!--recycler view for displaying the list of objects--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVResults" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idLLButtons" /> </RelativeLayout> Step 6: Creating a modal class for storing our data Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as DataModal and add the below code to it. Comments are added inside the code to understand the code in more detail. Java public class DataModal { // variables for our // string and confidence. private String result; private float confidence; // constructor public DataModal(String result, float confidence) { this.result = result; this.confidence = confidence; } // getter and setter methods public float getConfidence() { return confidence; } public void setConfidence(float confidence) { this.confidence = confidence; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } } Step 7: Creating a layout file for displaying our recycler view items Navigate to the app > res > layout > Right-click on it > New > layout resource file and name it as result_rv_item and add below code to it. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:elevation="8dp" app:cardCornerRadius="8dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp"> <!--text view for our result--> <TextView android:id="@+id/idTVResult" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="3dp" android:text="Result" android:textColor="@color/black" /> <!--text view for our confidence--> <TextView android:id="@+id/idTVConfidence" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVResult" android:padding="3dp" android:text="Confidence" android:textColor="@color/black" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 8: Creating an adapter class for our RecyclerView Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as resultRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class resultRVAdapter extends RecyclerView.Adapter<resultRVAdapter.ViewHolder> { // arraylist for storing our data and context private ArrayList<DataModal> dataModalArrayList; private Context context; // constructor for our variables public resultRVAdapter(ArrayList<DataModal> dataModalArrayList, Context context) { this.dataModalArrayList = dataModalArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inside on create view holder method we are inflating our layout file which we created. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.result_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // inside on bind view holder method we are setting // data to each item of recycler view. DataModal modal = dataModalArrayList.get(position); holder.resultTV.setText(modal.getResult()); holder.confidenceTV.setText("" + modal.getConfidence()); } @Override public int getItemCount() { // returning the size of array list. return dataModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text view. private TextView resultTV, confidenceTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our views with their ids. resultTV = itemView.findViewById(R.id.idTVResult); confidenceTV = itemView.findViewById(R.id.idTVConfidence); } }} Step 9: 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.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.ml.vision.FirebaseVision;import com.google.firebase.ml.vision.common.FirebaseVisionImage;import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel;import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // variables for our image view, image bitmap, // buttons, recycler view, adapter and array list. private ImageView img; private Button snap, labelBtn; private Bitmap imageBitmap; private RecyclerView resultRV; private resultRVAdapter resultRvAdapter; private ArrayList<DataModal> dataModalArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables for views img = (ImageView) findViewById(R.id.image); snap = (Button) findViewById(R.id.snapbtn); labelBtn = findViewById(R.id.labelBtn); resultRV = findViewById(R.id.idRVResults); // initializing our array list dataModalArrayList = new ArrayList<>(); // initializing our adapter class. resultRvAdapter = new resultRVAdapter(dataModalArrayList, MainActivity.this); // layout manager for our recycler view. LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this); // on below line we are setting layout manager // and adapter to our recycler view. resultRV.setLayoutManager(manager); resultRV.setAdapter(resultRvAdapter); // adding on click listener for our label button. labelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method // to label images. labelImage(); } }); // adding on click listener for our snap button. snap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method // to capture an image. dispatchTakePictureIntent(); } }); } static final int REQUEST_IMAGE_CAPTURE = 1; private void dispatchTakePictureIntent() { // inside this method we are calling an implicit intent to capture an image. Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // calling a start activity for result when image is captured. startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // inside on activity result method we are setting // our image to our image view from bitmap. if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); imageBitmap = (Bitmap) extras.get("data"); // on below line we are setting our // bitmap to our image view. img.setImageBitmap(imageBitmap); } } private void labelImage() { // inside the label image method we are calling a // firebase vision image and passing our image bitmap to it. FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(imageBitmap); // on below line we are creating a labeler for our image bitmap // and creating a variable for our firebase vision image labeler. FirebaseVisionImageLabeler labeler = FirebaseVision.getInstance().getOnDeviceImageLabeler(); // calling a method to process an image and adding on success listener method to it. labeler.processImage(image).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() { @Override public void onSuccess(List<FirebaseVisionImageLabel> firebaseVisionImageLabels) { // inside on success method we are running a loop to get the data from our list. for (FirebaseVisionImageLabel label : firebaseVisionImageLabels) { // on below line we are getting text from our list. String text = label.getText(); // on below line we are getting its entity id String entityId = label.getEntityId(); // on below line we are getting the // confidence level of our modal. float confidence = label.getConfidence(); // after getting all data we are passing it to our array list. dataModalArrayList.add(new DataModal(text, confidence)); // after adding a new data we are notifying // our adapter that data has been updated. resultRvAdapter.notifyDataSetChanged(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // error handling for on failure method Toast.makeText(MainActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show(); } }); }} Now run your app and see the output of the app. Note: If you are facing the following NDK at ~/Library/Android/sdk/ndk-bundle did not have a source.properties file error then please refer to this article. Technical Scripter 2020 Android Java Machine Learning Technical Scripter Java Android Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n24 Feb, 2021" }, { "code": null, "e": 26613, "s": 26381, "text": "We have seen many apps in Android in which we will detect the object present in the image whether it may be any object. In this article, we will take a look at the implementation of image labeling in Android using Firebase ML Kit. " }, { "code": null, "e": 26966, "s": 26613, "text": "We will be building a simple application in which we will be capturing an image of any object and from that, we will detect the objects present inside our image with the accuracy level. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 26995, "s": 26966, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27157, "s": 26995, "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": 27194, "s": 27157, "text": "Step 2: Connect your app to Firebase" }, { "code": null, "e": 27547, "s": 27194, "text": "After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option below screenshot. " }, { "code": null, "e": 27666, "s": 27547, "text": "After clicking on this option on the next screen click on Connect to Firebase option to connect your app to Firebase. " }, { "code": null, "e": 27738, "s": 27666, "text": "Step 3: Adding dependency for language translation to build.gradle file" }, { "code": null, "e": 27857, "s": 27738, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 27890, "s": 27857, "text": "// dependency for firebase core." }, { "code": null, "e": 27947, "s": 27890, "text": "implementation’com.google.firebase:firebase-core:15.0.2′" }, { "code": null, "e": 27973, "s": 27947, "text": "// Firebase ML dependency" }, { "code": null, "e": 28036, "s": 27973, "text": "implementation ‘com.google.firebase:firebase-ml-vision:24.0.3’" }, { "code": null, "e": 28117, "s": 28036, "text": "implementation ‘com.google.firebase:firebase-ml-vision-image-label-model:20.0.1’" }, { "code": null, "e": 28225, "s": 28117, "text": "Step 4: Adding permissions to access the Internet and meta-data in your Android Apps AndroidManifest file " }, { "code": null, "e": 28366, "s": 28225, "text": "Navigate to the app > AndroidManifest.xml file and add the below code to it. Comments are added in the code to get to know in more detail. " }, { "code": null, "e": 28370, "s": 28366, "text": "XML" }, { "code": "<!-- below line is use to add camera feature in our app --><uses-feature android:name=\"android.hardware.camera\" android:required=\"true\" /> <!-- permission for internet --><uses-permission android:name=\"android.permission.INTERNET\" />", "e": 28607, "s": 28370, "text": null }, { "code": null, "e": 28656, "s": 28607, "text": "Add the below line inside your application tag. " }, { "code": null, "e": 28660, "s": 28656, "text": "XML" }, { "code": "<meta-data android:name=\"com.google.firebase.ml.vision.DEPENDENCIES\" android:value=\"label\" />", "e": 28756, "s": 28660, "text": null }, { "code": null, "e": 28817, "s": 28756, "text": "Below is the complete code for the AndroidManifest.xml file." }, { "code": null, "e": 28821, "s": 28817, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.labelimage\"> <!-- below line is use to add camera feature in our app --> <uses-feature android:name=\"android.hardware.camera\" android:required=\"true\" /> <!-- permission for internet --> <uses-permission android:name=\"android.permission.INTERNET\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.LabelImage\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> <meta-data android:name=\"com.google.firebase.ml.vision.DEPENDENCIES\" android:value=\"label\" /> </application> </manifest>", "e": 29933, "s": 28821, "text": null }, { "code": null, "e": 29981, "s": 29933, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 30124, "s": 29981, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 30128, "s": 30124, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--image view for displaying our image--> <ImageView android:id=\"@+id/image\" android:layout_width=\"match_parent\" android:layout_height=\"300dp\" android:layout_alignParentTop=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"10dp\" android:scaleType=\"centerCrop\" /> <LinearLayout android:id=\"@+id/idLLButtons\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/image\" android:orientation=\"horizontal\"> <!--button for capturing our image--> <Button android:id=\"@+id/snapbtn\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:layout_marginTop=\"30dp\" android:layout_weight=\"1\" android:text=\"SNAP\" android:textSize=\"25dp\" android:textStyle=\"bold\" /> <!--button for detecting the objects--> <Button android:id=\"@+id/labelBtn\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:layout_marginTop=\"30dp\" android:layout_weight=\"1\" android:text=\"Label\" android:textSize=\"25dp\" android:textStyle=\"bold\" /> </LinearLayout> <!--recycler view for displaying the list of objects--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVResults\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idLLButtons\" /> </RelativeLayout>", "e": 32117, "s": 30128, "text": null }, { "code": null, "e": 32169, "s": 32117, "text": "Step 6: Creating a modal class for storing our data" }, { "code": null, "e": 32398, "s": 32169, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as DataModal and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 32403, "s": 32398, "text": "Java" }, { "code": "public class DataModal { // variables for our // string and confidence. private String result; private float confidence; // constructor public DataModal(String result, float confidence) { this.result = result; this.confidence = confidence; } // getter and setter methods public float getConfidence() { return confidence; } public void setConfidence(float confidence) { this.confidence = confidence; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }", "e": 33026, "s": 32403, "text": null }, { "code": null, "e": 33096, "s": 33026, "text": "Step 7: Creating a layout file for displaying our recycler view items" }, { "code": null, "e": 33237, "s": 33096, "text": "Navigate to the app > res > layout > Right-click on it > New > layout resource file and name it as result_rv_item and add below code to it. " }, { "code": null, "e": 33241, "s": 33237, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <RelativeLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"3dp\"> <!--text view for our result--> <TextView android:id=\"@+id/idTVResult\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"3dp\" android:text=\"Result\" android:textColor=\"@color/black\" /> <!--text view for our confidence--> <TextView android:id=\"@+id/idTVConfidence\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVResult\" android:padding=\"3dp\" android:text=\"Confidence\" android:textColor=\"@color/black\" /> </RelativeLayout> </androidx.cardview.widget.CardView>", "e": 34478, "s": 33241, "text": null }, { "code": null, "e": 34533, "s": 34478, "text": "Step 8: Creating an adapter class for our RecyclerView" }, { "code": null, "e": 34760, "s": 34533, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as resultRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 34765, "s": 34760, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class resultRVAdapter extends RecyclerView.Adapter<resultRVAdapter.ViewHolder> { // arraylist for storing our data and context private ArrayList<DataModal> dataModalArrayList; private Context context; // constructor for our variables public resultRVAdapter(ArrayList<DataModal> dataModalArrayList, Context context) { this.dataModalArrayList = dataModalArrayList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // inside on create view holder method we are inflating our layout file which we created. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.result_rv_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // inside on bind view holder method we are setting // data to each item of recycler view. DataModal modal = dataModalArrayList.get(position); holder.resultTV.setText(modal.getResult()); holder.confidenceTV.setText(\"\" + modal.getConfidence()); } @Override public int getItemCount() { // returning the size of array list. return dataModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text view. private TextView resultTV, confidenceTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our views with their ids. resultTV = itemView.findViewById(R.id.idTVResult); confidenceTV = itemView.findViewById(R.id.idTVConfidence); } }}", "e": 36778, "s": 34765, "text": null }, { "code": null, "e": 36826, "s": 36778, "text": "Step 9: Working with the MainActivity.java file" }, { "code": null, "e": 37016, "s": 36826, "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": 37021, "s": 37016, "text": "Java" }, { "code": "import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.ml.vision.FirebaseVision;import com.google.firebase.ml.vision.common.FirebaseVisionImage;import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel;import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { // variables for our image view, image bitmap, // buttons, recycler view, adapter and array list. private ImageView img; private Button snap, labelBtn; private Bitmap imageBitmap; private RecyclerView resultRV; private resultRVAdapter resultRvAdapter; private ArrayList<DataModal> dataModalArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables for views img = (ImageView) findViewById(R.id.image); snap = (Button) findViewById(R.id.snapbtn); labelBtn = findViewById(R.id.labelBtn); resultRV = findViewById(R.id.idRVResults); // initializing our array list dataModalArrayList = new ArrayList<>(); // initializing our adapter class. resultRvAdapter = new resultRVAdapter(dataModalArrayList, MainActivity.this); // layout manager for our recycler view. LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this); // on below line we are setting layout manager // and adapter to our recycler view. resultRV.setLayoutManager(manager); resultRV.setAdapter(resultRvAdapter); // adding on click listener for our label button. labelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method // to label images. labelImage(); } }); // adding on click listener for our snap button. snap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling a method // to capture an image. dispatchTakePictureIntent(); } }); } static final int REQUEST_IMAGE_CAPTURE = 1; private void dispatchTakePictureIntent() { // inside this method we are calling an implicit intent to capture an image. Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // calling a start activity for result when image is captured. startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // inside on activity result method we are setting // our image to our image view from bitmap. if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); imageBitmap = (Bitmap) extras.get(\"data\"); // on below line we are setting our // bitmap to our image view. img.setImageBitmap(imageBitmap); } } private void labelImage() { // inside the label image method we are calling a // firebase vision image and passing our image bitmap to it. FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(imageBitmap); // on below line we are creating a labeler for our image bitmap // and creating a variable for our firebase vision image labeler. FirebaseVisionImageLabeler labeler = FirebaseVision.getInstance().getOnDeviceImageLabeler(); // calling a method to process an image and adding on success listener method to it. labeler.processImage(image).addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() { @Override public void onSuccess(List<FirebaseVisionImageLabel> firebaseVisionImageLabels) { // inside on success method we are running a loop to get the data from our list. for (FirebaseVisionImageLabel label : firebaseVisionImageLabels) { // on below line we are getting text from our list. String text = label.getText(); // on below line we are getting its entity id String entityId = label.getEntityId(); // on below line we are getting the // confidence level of our modal. float confidence = label.getConfidence(); // after getting all data we are passing it to our array list. dataModalArrayList.add(new DataModal(text, confidence)); // after adding a new data we are notifying // our adapter that data has been updated. resultRvAdapter.notifyDataSetChanged(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // error handling for on failure method Toast.makeText(MainActivity.this, \"Fail to get data..\", Toast.LENGTH_SHORT).show(); } }); }}", "e": 43200, "s": 37021, "text": null }, { "code": null, "e": 43249, "s": 43200, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 43407, "s": 43249, "text": "Note: If you are facing the following NDK at ~/Library/Android/sdk/ndk-bundle did not have a source.properties file error then please refer to this article. " }, { "code": null, "e": 43431, "s": 43407, "text": "Technical Scripter 2020" }, { "code": null, "e": 43439, "s": 43431, "text": "Android" }, { "code": null, "e": 43444, "s": 43439, "text": "Java" }, { "code": null, "e": 43461, "s": 43444, "text": "Machine Learning" }, { "code": null, "e": 43480, "s": 43461, "text": "Technical Scripter" }, { "code": null, "e": 43485, "s": 43480, "text": "Java" }, { "code": null, "e": 43493, "s": 43485, "text": "Android" }, { "code": null, "e": 43510, "s": 43493, "text": "Machine Learning" }, { "code": null, "e": 43608, "s": 43510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43646, "s": 43608, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 43685, "s": 43646, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 43735, "s": 43685, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 43786, "s": 43735, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 43828, "s": 43786, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 43843, "s": 43828, "text": "Arrays in Java" }, { "code": null, "e": 43887, "s": 43843, "text": "Split() String method in Java with examples" }, { "code": null, "e": 43909, "s": 43887, "text": "For-each loop in Java" }, { "code": null, "e": 43960, "s": 43909, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to Execute C# Program on cmd (command-line)? - GeeksforGeeks
30 Jan, 2020 C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”. C# is among the languages for Common Language Infrastructure and the current version of C# is version 8.0. C# is a lot similar to Java syntactically and is easy for the users who know C, C++ or Java. Since the C# is a lot similar to other widely used languages syntactically, it is easier to code and learn in C#.Programs can be written in C# in any of the widely used text editors like Notepad++, gedit, etc. or on any of the compilers. After writing the program save the file with the extension .cs. There are various online IDEs such as GeeksforGeeks ide, CodeChef ide, etc. which can be used to run C# programs without installing. One can also use command-line options to run a C# program. Sample C# Program to execute on Command-Line: // C# program to print Hello World!using System; // namespace declarationnamespace HelloWorldApp { // Class declarationclass Geeks { // Main Method static void Main(string[] args) { // statement // printing Hello World! Console.WriteLine("Hello World!"); // To prevents the screen from // running and closing quickly Console.ReadKey(); }}} Step 1: Go to Control Panel -> System and Security -> System. Under Advanced System Setting option click on Environment Variables as shown below: Step 2: Now, we have to alter the “Path” variable under System variables so that it also contains the path to the .NET Framework environment. Select the “Path” variable and click on the Edit button as shown below: Step 3: We will see a list of different paths, click on the New button and then add the path where .NET Framework is installed. Step 4: Click on OK, Save the settings and it is done !! Now to check whether the environment setup is done correctly, open command prompt and type csc. Step 1: Open the text editor like Notepad or Notepad++, and write the code that you want to execute. Now save the file with .cs extension. Step 2: Compile your C# source code with the use of command: csc File_name.cs If your program has no error then it will create a filename.exe file in the same directory where you have saved your program. Suppose you saved the above program as Hello.cs. So you will write csc Hello.cs on cmd. This will create a Hello.exe file. Step 3: Now there are two ways to execute the Hello.exe. First, you have to simply type the filename i.e Hello on the cmd and it will give the output. Second, you can go to the directory where you saved your program and there you find filename.exe. You have to simply double-click that file and it will give the output. Using Command: Using .exe file: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method Introduction to .NET Framework C# | Arrays HashSet in C# with Examples
[ { "code": null, "e": 25147, "s": 25119, "text": "\n30 Jan, 2020" }, { "code": null, "e": 25445, "s": 25147, "text": "C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”. C# is among the languages for Common Language Infrastructure and the current version of C# is version 8.0. C# is a lot similar to Java syntactically and is easy for the users who know C, C++ or Java." }, { "code": null, "e": 25939, "s": 25445, "text": "Since the C# is a lot similar to other widely used languages syntactically, it is easier to code and learn in C#.Programs can be written in C# in any of the widely used text editors like Notepad++, gedit, etc. or on any of the compilers. After writing the program save the file with the extension .cs. There are various online IDEs such as GeeksforGeeks ide, CodeChef ide, etc. which can be used to run C# programs without installing. One can also use command-line options to run a C# program." }, { "code": null, "e": 25985, "s": 25939, "text": "Sample C# Program to execute on Command-Line:" }, { "code": "// C# program to print Hello World!using System; // namespace declarationnamespace HelloWorldApp { // Class declarationclass Geeks { // Main Method static void Main(string[] args) { // statement // printing Hello World! Console.WriteLine(\"Hello World!\"); // To prevents the screen from // running and closing quickly Console.ReadKey(); }}}", "e": 26387, "s": 25985, "text": null }, { "code": null, "e": 26533, "s": 26387, "text": "Step 1: Go to Control Panel -> System and Security -> System. Under Advanced System Setting option click on Environment Variables as shown below:" }, { "code": null, "e": 26749, "s": 26535, "text": "Step 2: Now, we have to alter the “Path” variable under System variables so that it also contains the path to the .NET Framework environment. Select the “Path” variable and click on the Edit button as shown below:" }, { "code": null, "e": 26879, "s": 26751, "text": "Step 3: We will see a list of different paths, click on the New button and then add the path where .NET Framework is installed." }, { "code": null, "e": 27034, "s": 26881, "text": "Step 4: Click on OK, Save the settings and it is done !! Now to check whether the environment setup is done correctly, open command prompt and type csc." }, { "code": null, "e": 27175, "s": 27036, "text": "Step 1: Open the text editor like Notepad or Notepad++, and write the code that you want to execute. Now save the file with .cs extension." }, { "code": null, "e": 27238, "s": 27177, "text": "Step 2: Compile your C# source code with the use of command:" }, { "code": null, "e": 27255, "s": 27238, "text": "csc File_name.cs" }, { "code": null, "e": 27504, "s": 27255, "text": "If your program has no error then it will create a filename.exe file in the same directory where you have saved your program. Suppose you saved the above program as Hello.cs. So you will write csc Hello.cs on cmd. This will create a Hello.exe file." }, { "code": null, "e": 27826, "s": 27506, "text": "Step 3: Now there are two ways to execute the Hello.exe. First, you have to simply type the filename i.e Hello on the cmd and it will give the output. Second, you can go to the directory where you saved your program and there you find filename.exe. You have to simply double-click that file and it will give the output." }, { "code": null, "e": 27841, "s": 27826, "text": "Using Command:" }, { "code": null, "e": 27858, "s": 27841, "text": "Using .exe file:" }, { "code": null, "e": 27861, "s": 27858, "text": "C#" }, { "code": null, "e": 27959, "s": 27861, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27987, "s": 27959, "text": "C# Dictionary with examples" }, { "code": null, "e": 28002, "s": 27987, "text": "C# | Delegates" }, { "code": null, "e": 28024, "s": 28002, "text": "C# | Abstract Classes" }, { "code": null, "e": 28070, "s": 28024, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28093, "s": 28070, "text": "Extension Method in C#" }, { "code": null, "e": 28133, "s": 28093, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28155, "s": 28133, "text": "C# | Replace() Method" }, { "code": null, "e": 28186, "s": 28155, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28198, "s": 28186, "text": "C# | Arrays" } ]
Solidity - Enums and Structs - GeeksforGeeks
11 May, 2022 Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of few predefined values, these values of the enumerated list are called as enums. Options of are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code. Syntax: enum <enumerator_name> { element 1, element 2,....,element n } Example: In the below example, the contract Types consist of an enumerator week_days, and functions are defined to set and get the value of a variable of type enumerator. Solidity // Solidity program to demonstrate// how to use 'enumerator'pragma solidity ^0.5.0; // Creating a contractcontract Types { // Creating an enumerator enum week_days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } // Declaring variables of // type enumerator week_days week; week_days choice; // Setting a default value week_days constant default_value = week_days.Sunday; // Defining a function to // set value of choice function set_value() public { choice = week_days.Thursday; } // Defining a function to // return value of choice function get_choice( ) public view returns (week_days) { return choice; } // Defining function to // return default value function getdefaultvalue( ) public pure returns(week_days) { return default_value; } } Output : Solidity allows user to create their own data type in the form of structure. The struct contains a group of elements with a different data type. Generally, it is used to represent a record. To define a structure struct keyword is used, which creates a new data type. Syntax: struct <structure_name> { <data type> variable_1; <data type> variable_2; } For accessing any element of the structure dot operator is used, which separates the struct variable and the element we wish to access. To define the variable of structure data type structure name is used. Example: In the below example, the contract Test consists of a structure Book, and functions are defined to set and get values of the elements of the structure. Solidity // Solidity program to demonstrate// how to use 'structures'pragma solidity ^0.5.0; // Creating a contractcontract test { // Declaring a structure struct Book { string name; string writter; uint id; bool available; } // Declaring a structure object Book book1; // Assigning values to the fields // for the structure object book2 Book book2 = Book("Building Ethereum DApps", "Roberto Infante ", 2, false); // Defining a function to set values // for the fields for structure book1 function set_book_detail() public { book1 = Book("Introducing Ethereum and Solidity", "Chris Dannen", 1, true); } // Defining function to print // book2 details function book_info( )public view returns ( string memory, string memory, uint, bool) { return(book2.name, book2.writter, book2.id, book2.available); } // Defining function to print // book1 details function get_details( ) public view returns (string memory, uint) { return (book1.name, book1.id); }} Output : simmytarika5 Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect ReactJS with MetaMask ? How to Become a Blockchain Developer? Solidity - Inheritance Mathematical Operations in Solidity How to Install Solidity in Windows? Solidity - Inheritance Mathematical Operations in Solidity How to Install Solidity in Windows? Introduction to Solidity Dynamic Arrays and its Operations in Solidity
[ { "code": null, "e": 25651, "s": 25623, "text": "\n11 May, 2022" }, { "code": null, "e": 26123, "s": 25651, "text": "Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading. Enums restrict the variable with one of few predefined values, these values of the enumerated list are called as enums. Options of are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code." }, { "code": null, "e": 26131, "s": 26123, "text": "Syntax:" }, { "code": null, "e": 26208, "s": 26131, "text": "enum <enumerator_name> { \n element 1, element 2,....,element n\n} " }, { "code": null, "e": 26379, "s": 26208, "text": "Example: In the below example, the contract Types consist of an enumerator week_days, and functions are defined to set and get the value of a variable of type enumerator." }, { "code": null, "e": 26388, "s": 26379, "text": "Solidity" }, { "code": "// Solidity program to demonstrate// how to use 'enumerator'pragma solidity ^0.5.0; // Creating a contractcontract Types { // Creating an enumerator enum week_days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } // Declaring variables of // type enumerator week_days week; week_days choice; // Setting a default value week_days constant default_value = week_days.Sunday; // Defining a function to // set value of choice function set_value() public { choice = week_days.Thursday; } // Defining a function to // return value of choice function get_choice( ) public view returns (week_days) { return choice; } // Defining function to // return default value function getdefaultvalue( ) public pure returns(week_days) { return default_value; } }", "e": 27309, "s": 26388, "text": null }, { "code": null, "e": 27319, "s": 27309, "text": "Output : " }, { "code": null, "e": 27587, "s": 27319, "text": "Solidity allows user to create their own data type in the form of structure. The struct contains a group of elements with a different data type. Generally, it is used to represent a record. To define a structure struct keyword is used, which creates a new data type. " }, { "code": null, "e": 27595, "s": 27587, "text": "Syntax:" }, { "code": null, "e": 27682, "s": 27595, "text": "struct <structure_name> { \n <data type> variable_1; \n <data type> variable_2; \n}" }, { "code": null, "e": 27888, "s": 27682, "text": "For accessing any element of the structure dot operator is used, which separates the struct variable and the element we wish to access. To define the variable of structure data type structure name is used." }, { "code": null, "e": 28049, "s": 27888, "text": "Example: In the below example, the contract Test consists of a structure Book, and functions are defined to set and get values of the elements of the structure." }, { "code": null, "e": 28058, "s": 28049, "text": "Solidity" }, { "code": "// Solidity program to demonstrate// how to use 'structures'pragma solidity ^0.5.0; // Creating a contractcontract test { // Declaring a structure struct Book { string name; string writter; uint id; bool available; } // Declaring a structure object Book book1; // Assigning values to the fields // for the structure object book2 Book book2 = Book(\"Building Ethereum DApps\", \"Roberto Infante \", 2, false); // Defining a function to set values // for the fields for structure book1 function set_book_detail() public { book1 = Book(\"Introducing Ethereum and Solidity\", \"Chris Dannen\", 1, true); } // Defining function to print // book2 details function book_info( )public view returns ( string memory, string memory, uint, bool) { return(book2.name, book2.writter, book2.id, book2.available); } // Defining function to print // book1 details function get_details( ) public view returns (string memory, uint) { return (book1.name, book1.id); }}", "e": 29186, "s": 28058, "text": null }, { "code": null, "e": 29197, "s": 29186, "text": "Output : " }, { "code": null, "e": 29210, "s": 29197, "text": "simmytarika5" }, { "code": null, "e": 29221, "s": 29210, "text": "Blockchain" }, { "code": null, "e": 29230, "s": 29221, "text": "Solidity" }, { "code": null, "e": 29328, "s": 29230, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29367, "s": 29328, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 29405, "s": 29367, "text": "How to Become a Blockchain Developer?" }, { "code": null, "e": 29428, "s": 29405, "text": "Solidity - Inheritance" }, { "code": null, "e": 29464, "s": 29428, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 29500, "s": 29464, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 29523, "s": 29500, "text": "Solidity - Inheritance" }, { "code": null, "e": 29559, "s": 29523, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 29595, "s": 29559, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 29620, "s": 29595, "text": "Introduction to Solidity" } ]
Java Program to Separate the Individual Characters from a String - GeeksforGeeks
27 Jan, 2021 The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it’s content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided as the input. Therefore, to separate each character from the string, the individual characters are accessed through its index. Examples : Input : string = "GeeksforGeeks" Output: Individual characters from given string : G e e k s f o r G e e k s Input : string = "Characters" Output: Individual characters from given string : C h a r a c t e r s Approach 1: First, define a string.Next, create a for-loop where the loop variable will start from index 0 and end at the length of the given string.Print the character present at every index in order to separate each individual character.For better visualization, separate each individual character by space. First, define a string. Next, create a for-loop where the loop variable will start from index 0 and end at the length of the given string. Print the character present at every index in order to separate each individual character. For better visualization, separate each individual character by space. Below is the implementation of the above approach : Java // Java Program to Separate the// Individual Characters from a String import java.io.*; public class GFG { public static void main(String[] args) { String string = "GeeksforGeeks"; // Displays individual characters from given string System.out.println( "Individual characters from given string: "); // Iterate through the given string to // display the individual characters for (int i = 0; i < string.length(); i++) { System.out.print(string.charAt(i) + " "); } }} Individual characters from given string: G e e k s f o r G e e k s Time Complexity: O(n), where n is the length of the string. Approach 2: Define a String.Use the toCharArray method and store the array of Characters returned in a char array.Print separated characters using for-each loop. Define a String. Use the toCharArray method and store the array of Characters returned in a char array. Print separated characters using for-each loop. Below is the implementation of the above approach : Java // Java Implementation of the above approach import java.io.*; class GFG{ public static void main(String[] args) { // Initialising String String str = "GeeksForGeeks"; // Converts the string into // char array char[] arr = str.toCharArray(); System.out.println( "Displaying individual characters" + "from given string:"); // Printing the characters using for-each loop for (char e : arr) System.out.print(e + " "); }} Displaying individual charactersfrom given string: G e e k s F o r G e e k s Time Complexity: O(N)Space Complexity: O(N) sudhanshublaze Java-String-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 26332, "s": 26304, "text": "\n27 Jan, 2021" }, { "code": null, "e": 26760, "s": 26332, "text": "The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it’s content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided as the input. Therefore, to separate each character from the string, the individual characters are accessed through its index." }, { "code": null, "e": 26771, "s": 26760, "text": "Examples :" }, { "code": null, "e": 26998, "s": 26771, "text": "Input : string = \"GeeksforGeeks\"\nOutput: Individual characters from given string :\n G e e k s f o r G e e k s\nInput : string = \"Characters\"\nOutput: Individual characters from given string :\n C h a r a c t e r s" }, { "code": null, "e": 27010, "s": 26998, "text": "Approach 1:" }, { "code": null, "e": 27308, "s": 27010, "text": "First, define a string.Next, create a for-loop where the loop variable will start from index 0 and end at the length of the given string.Print the character present at every index in order to separate each individual character.For better visualization, separate each individual character by space." }, { "code": null, "e": 27332, "s": 27308, "text": "First, define a string." }, { "code": null, "e": 27447, "s": 27332, "text": "Next, create a for-loop where the loop variable will start from index 0 and end at the length of the given string." }, { "code": null, "e": 27538, "s": 27447, "text": "Print the character present at every index in order to separate each individual character." }, { "code": null, "e": 27609, "s": 27538, "text": "For better visualization, separate each individual character by space." }, { "code": null, "e": 27661, "s": 27609, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 27666, "s": 27661, "text": "Java" }, { "code": "// Java Program to Separate the// Individual Characters from a String import java.io.*; public class GFG { public static void main(String[] args) { String string = \"GeeksforGeeks\"; // Displays individual characters from given string System.out.println( \"Individual characters from given string: \"); // Iterate through the given string to // display the individual characters for (int i = 0; i < string.length(); i++) { System.out.print(string.charAt(i) + \" \"); } }}", "e": 28215, "s": 27666, "text": null }, { "code": null, "e": 28287, "s": 28218, "text": "Individual characters from given string: \nG e e k s f o r G e e k s " }, { "code": null, "e": 28348, "s": 28287, "text": "Time Complexity: O(n), where n is the length of the string. " }, { "code": null, "e": 28360, "s": 28348, "text": "Approach 2:" }, { "code": null, "e": 28510, "s": 28360, "text": "Define a String.Use the toCharArray method and store the array of Characters returned in a char array.Print separated characters using for-each loop." }, { "code": null, "e": 28527, "s": 28510, "text": "Define a String." }, { "code": null, "e": 28614, "s": 28527, "text": "Use the toCharArray method and store the array of Characters returned in a char array." }, { "code": null, "e": 28662, "s": 28614, "text": "Print separated characters using for-each loop." }, { "code": null, "e": 28714, "s": 28662, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 28719, "s": 28714, "text": "Java" }, { "code": "// Java Implementation of the above approach import java.io.*; class GFG{ public static void main(String[] args) { // Initialising String String str = \"GeeksForGeeks\"; // Converts the string into // char array char[] arr = str.toCharArray(); System.out.println( \"Displaying individual characters\" + \"from given string:\"); // Printing the characters using for-each loop for (char e : arr) System.out.print(e + \" \"); }}", "e": 29247, "s": 28719, "text": null }, { "code": null, "e": 29325, "s": 29247, "text": "Displaying individual charactersfrom given string:\nG e e k s F o r G e e k s " }, { "code": null, "e": 29369, "s": 29325, "text": "Time Complexity: O(N)Space Complexity: O(N)" }, { "code": null, "e": 29384, "s": 29369, "text": "sudhanshublaze" }, { "code": null, "e": 29405, "s": 29384, "text": "Java-String-Programs" }, { "code": null, "e": 29412, "s": 29405, "text": "Picked" }, { "code": null, "e": 29417, "s": 29412, "text": "Java" }, { "code": null, "e": 29431, "s": 29417, "text": "Java Programs" }, { "code": null, "e": 29436, "s": 29431, "text": "Java" }, { "code": null, "e": 29534, "s": 29436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29585, "s": 29534, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29615, "s": 29585, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29630, "s": 29615, "text": "Stream In Java" }, { "code": null, "e": 29649, "s": 29630, "text": "Interfaces in Java" }, { "code": null, "e": 29680, "s": 29649, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29708, "s": 29680, "text": "Initializing a List in Java" }, { "code": null, "e": 29752, "s": 29708, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 29778, "s": 29752, "text": "Java Programming Examples" }, { "code": null, "e": 29812, "s": 29778, "text": "Convert Double to Integer in Java" } ]
RustScan - Faster Nmap Scanning with Rust - GeeksforGeeks
23 Sep, 2021 Port Scanning is the process of detection of active ports on the Web Server. In some cases, if there is an unfamiliar port running on the server, this can lead to breaches. We can perform use various automated tools like Nmap, Masscan, etc for port detection. RustScan is the tool that assures the fastest result retrieving tool as compares to Nmap. RustScan is a tool that turns a 17 minutes Nmap scan into 19 seconds. RustScan tool is developed in the Rust language and valid on the GitHub platform. RustScan tool is an open-source and free-to-use tool. RustScan tool can scan 65k ports in almost 7-8 seconds which is much faster than other tools. RustScan tool has support to IPv6 Version IP. Step 1: Download the .deb file from the below links to your Kali Linux operating system. https://github.com/RustScan/RustScan/releases/download/2.0.1/rustscan_2.0.1_amd64.deb Step 2: Run the command dpkg -i on the file to install the tool. sudp dpkg -i rustscan_2.0.1_amd64.deb Step 3: Now use the following command to run the tool and check the help section. rustscan -h Example 1: Host Scanning rustscan -a www.geeksforgeeks.org In this example, we will be performing a simple port scan on the geeksforgeeks.org domain. Example 2: Individual Port Scanning rustscan -a www.geeksforgeeks.org -p 443 In this example, we will be performing specific single port detection rather than scanning all the ports. Example 3: Multiple selected port scanning rustscan -a www.geeksforgeeks.org -p 443,80,121,65535 In this example, we will be performing multiple port scans or specific lists of ports rather than scanning all the ports. Example 4: Ranges of ports rustscan -a www.geeksforgeeks.org --range 1-1000 In this example, we will be performing detection of ports from the range of 1-1000 on the geeksforgeeks.org domain. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n23 Sep, 2021" }, { "code": null, "e": 26347, "s": 25651, "text": "Port Scanning is the process of detection of active ports on the Web Server. In some cases, if there is an unfamiliar port running on the server, this can lead to breaches. We can perform use various automated tools like Nmap, Masscan, etc for port detection. RustScan is the tool that assures the fastest result retrieving tool as compares to Nmap. RustScan is a tool that turns a 17 minutes Nmap scan into 19 seconds. RustScan tool is developed in the Rust language and valid on the GitHub platform. RustScan tool is an open-source and free-to-use tool. RustScan tool can scan 65k ports in almost 7-8 seconds which is much faster than other tools. RustScan tool has support to IPv6 Version IP." }, { "code": null, "e": 26436, "s": 26347, "text": "Step 1: Download the .deb file from the below links to your Kali Linux operating system." }, { "code": null, "e": 26522, "s": 26436, "text": "https://github.com/RustScan/RustScan/releases/download/2.0.1/rustscan_2.0.1_amd64.deb" }, { "code": null, "e": 26587, "s": 26522, "text": "Step 2: Run the command dpkg -i on the file to install the tool." }, { "code": null, "e": 26625, "s": 26587, "text": "sudp dpkg -i rustscan_2.0.1_amd64.deb" }, { "code": null, "e": 26707, "s": 26625, "text": "Step 3: Now use the following command to run the tool and check the help section." }, { "code": null, "e": 26719, "s": 26707, "text": "rustscan -h" }, { "code": null, "e": 26744, "s": 26719, "text": "Example 1: Host Scanning" }, { "code": null, "e": 26778, "s": 26744, "text": "rustscan -a www.geeksforgeeks.org" }, { "code": null, "e": 26869, "s": 26778, "text": "In this example, we will be performing a simple port scan on the geeksforgeeks.org domain." }, { "code": null, "e": 26905, "s": 26869, "text": "Example 2: Individual Port Scanning" }, { "code": null, "e": 26946, "s": 26905, "text": "rustscan -a www.geeksforgeeks.org -p 443" }, { "code": null, "e": 27052, "s": 26946, "text": "In this example, we will be performing specific single port detection rather than scanning all the ports." }, { "code": null, "e": 27095, "s": 27052, "text": "Example 3: Multiple selected port scanning" }, { "code": null, "e": 27149, "s": 27095, "text": "rustscan -a www.geeksforgeeks.org -p 443,80,121,65535" }, { "code": null, "e": 27271, "s": 27149, "text": "In this example, we will be performing multiple port scans or specific lists of ports rather than scanning all the ports." }, { "code": null, "e": 27298, "s": 27271, "text": "Example 4: Ranges of ports" }, { "code": null, "e": 27347, "s": 27298, "text": "rustscan -a www.geeksforgeeks.org --range 1-1000" }, { "code": null, "e": 27463, "s": 27347, "text": "In this example, we will be performing detection of ports from the range of 1-1000 on the geeksforgeeks.org domain." }, { "code": null, "e": 27474, "s": 27463, "text": "Kali-Linux" }, { "code": null, "e": 27486, "s": 27474, "text": "Linux-Tools" }, { "code": null, "e": 27497, "s": 27486, "text": "Linux-Unix" }, { "code": null, "e": 27595, "s": 27497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27630, "s": 27595, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27656, "s": 27630, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27690, "s": 27656, "text": "mv command in Linux with examples" }, { "code": null, "e": 27719, "s": 27690, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27756, "s": 27719, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27793, "s": 27756, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27835, "s": 27793, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27861, "s": 27835, "text": "Thread functions in C/C++" }, { "code": null, "e": 27897, "s": 27861, "text": "uniq Command in LINUX with examples" } ]
Mathematics | Introduction to Propositional Logic | Set 2 - GeeksforGeeks
30 Sep, 2021 Prerequisite : Introduction to Propositional Logic – Set 1 De Morgan’s Law : In propositional logic and boolean algebra, De Morgan’s laws are a pair of transformation rules that are both valid rules of inference. They are named after Augustus De Morgan, a 19th-century British mathematician. The rules allow the expression of conjunctions and disjunctions purely in terms of each other via negation.In formal language, the rules are written as – Proof by Truth Table – Special Conditional Statements : As we know that we can form new propositions using existing propositions and logical connectives. New conditional statements can be formed starting with a conditional statement .In particular, there are three related conditional statements that occur so often that they have special names. Implication : Converse : The converse of the proposition is Contrapositive : The contrapositive of the proposition is Inverse : The inverse of the proposition is To summarise, Note : It is interesting to note that the truth value of the conditional statement is the same as it’s contrapositive, and the truth value of the Converse of is the same as the truth value of its Inverse.When two compound propositions always have the same truth value, they are said to be equivalent. Therefore, Example : Implication : If today is Friday, then it is raining. The given proposition is of the form , where is “Today is Friday” and is “It is raining today”.Contrapositive, Converse, and Inverse of the given proposition respectively are- Converse : If it is raining, then today is Friday Contrapositive :If it is not raining, then today is not Friday Inverse : If today is not Friday, then it is not raining Implicit use of Biconditionals : The last article, part one of this topic, ended with a discussion of bi-conditionals, what it is and its truth table. In Natural Language bi-conditionals are not always explicit. In particular, the iff construction (if and only if) is rarely used in common language. Instead, bi-conditionals are often expressed using “if, then” or an “only if” construction. The other part of the “if and only if” is implicit, i.e. the converse is implied but not stated.For example consider the following statement,“If you complete your homework, then you can go out and play”. What is really meant is “You can go out and play if and only if you complete your homework”. This statement is logically equivalent to two statements, “If you complete your homework, then you can go out and play” and “You can go out and play only if you complete your homework”.Because of this imprecision in Natural Language, an assumption needs to be made whether a conditional statement in natural language includes its converse or not. Precedence order of Logical Connectives : Logical connectives are used to construct compound propositions by joining existing propositions. Although parenthesis can be used to specify the order in which the logical operators in the compound proposition need to be applied, there exists a precedence order in Logical Operators.The precedence Order is- Here, higher the number lower the precedence. Translating English Sentences : As mentioned above in this article, Natural Languages such as English are ambiguous i.e. a statement may have multiple interpretations. Therefore it is important to convert these sentences into mathematical expressions involving propositional variables and logical connectives.The above process of conversion may take certain reasonable assumptions about the intended meaning of the sentence. Once the sentences are translated into logical expressions they can be analyzed further to determine their truth values. Rules of Inference can then further be used to reason about the expressions. Example : “You can access the Internet from campus only if you are a computer science major or you are not a freshman.”The above statement could be considered as a single proposition but it would be more useful to break it down into simpler propositions. That would make it easier to analyze its meaning and to reason with it. The above sentence could be broken down into three propositions, - "You can access the Internet from campus." - "You are a computer science major." - "You are a freshman." Using logical connectives we can join the above-mentioned propositions to get a logical expression of the given statement.“only if” is one way to express a conditional statement, (as discussed in Part-1 of this topic in previous Article),Therefore the logical expression would be – GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. 1. GATE CS 2009, Question 242. GATE CS 2014 Set-1, Question 633. GATE CS 2006, Question 284. GATE CS 2002, Question 85. GATE CS 2000, Question 306. GATE CS 2015 Set-1, Question 24 References – Propositional Logic – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sagartomar9927 Discrete Mathematics Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Activation Functions Arrow Symbols in LaTeX Newton's Divided Difference Interpolation Formula Set Notations in LaTeX Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 31277, "s": 31249, "text": "\n30 Sep, 2021" }, { "code": null, "e": 31336, "s": 31277, "text": "Prerequisite : Introduction to Propositional Logic – Set 1" }, { "code": null, "e": 31354, "s": 31336, "text": "De Morgan’s Law :" }, { "code": null, "e": 31723, "s": 31354, "text": "In propositional logic and boolean algebra, De Morgan’s laws are a pair of transformation rules that are both valid rules of inference. They are named after Augustus De Morgan, a 19th-century British mathematician. The rules allow the expression of conjunctions and disjunctions purely in terms of each other via negation.In formal language, the rules are written as –" }, { "code": null, "e": 31746, "s": 31723, "text": "Proof by Truth Table –" }, { "code": null, "e": 31781, "s": 31748, "text": "Special Conditional Statements :" }, { "code": null, "e": 32071, "s": 31781, "text": "As we know that we can form new propositions using existing propositions and logical connectives. New conditional statements can be formed starting with a conditional statement .In particular, there are three related conditional statements that occur so often that they have special names." }, { "code": null, "e": 32086, "s": 32071, "text": "Implication : " }, { "code": null, "e": 32134, "s": 32086, "text": "Converse : The converse of the proposition is " }, { "code": null, "e": 32194, "s": 32134, "text": "Contrapositive : The contrapositive of the proposition is " }, { "code": null, "e": 32240, "s": 32194, "text": "Inverse : The inverse of the proposition is " }, { "code": null, "e": 32254, "s": 32240, "text": "To summarise," }, { "code": null, "e": 32559, "s": 32256, "text": "Note : It is interesting to note that the truth value of the conditional statement is the same as it’s contrapositive, and the truth value of the Converse of is the same as the truth value of its Inverse.When two compound propositions always have the same truth value, they are said to be equivalent." }, { "code": null, "e": 32570, "s": 32559, "text": "Therefore," }, { "code": null, "e": 32582, "s": 32572, "text": "Example :" }, { "code": null, "e": 32636, "s": 32582, "text": "Implication : If today is Friday, then it is raining." }, { "code": null, "e": 32814, "s": 32636, "text": "The given proposition is of the form , where is “Today is Friday” and is “It is raining today”.Contrapositive, Converse, and Inverse of the given proposition respectively are-" }, { "code": null, "e": 32864, "s": 32814, "text": "Converse : If it is raining, then today is Friday" }, { "code": null, "e": 32927, "s": 32864, "text": "Contrapositive :If it is not raining, then today is not Friday" }, { "code": null, "e": 32984, "s": 32927, "text": "Inverse : If today is not Friday, then it is not raining" }, { "code": null, "e": 33017, "s": 32984, "text": "Implicit use of Biconditionals :" }, { "code": null, "e": 34020, "s": 33017, "text": "The last article, part one of this topic, ended with a discussion of bi-conditionals, what it is and its truth table. In Natural Language bi-conditionals are not always explicit. In particular, the iff construction (if and only if) is rarely used in common language. Instead, bi-conditionals are often expressed using “if, then” or an “only if” construction. The other part of the “if and only if” is implicit, i.e. the converse is implied but not stated.For example consider the following statement,“If you complete your homework, then you can go out and play”. What is really meant is “You can go out and play if and only if you complete your homework”. This statement is logically equivalent to two statements, “If you complete your homework, then you can go out and play” and “You can go out and play only if you complete your homework”.Because of this imprecision in Natural Language, an assumption needs to be made whether a conditional statement in natural language includes its converse or not." }, { "code": null, "e": 34062, "s": 34020, "text": "Precedence order of Logical Connectives :" }, { "code": null, "e": 34371, "s": 34062, "text": "Logical connectives are used to construct compound propositions by joining existing propositions. Although parenthesis can be used to specify the order in which the logical operators in the compound proposition need to be applied, there exists a precedence order in Logical Operators.The precedence Order is-" }, { "code": null, "e": 34419, "s": 34373, "text": "Here, higher the number lower the precedence." }, { "code": null, "e": 34451, "s": 34419, "text": "Translating English Sentences :" }, { "code": null, "e": 35042, "s": 34451, "text": "As mentioned above in this article, Natural Languages such as English are ambiguous i.e. a statement may have multiple interpretations. Therefore it is important to convert these sentences into mathematical expressions involving propositional variables and logical connectives.The above process of conversion may take certain reasonable assumptions about the intended meaning of the sentence. Once the sentences are translated into logical expressions they can be analyzed further to determine their truth values. Rules of Inference can then further be used to reason about the expressions." }, { "code": null, "e": 35052, "s": 35042, "text": "Example :" }, { "code": null, "e": 35369, "s": 35052, "text": "“You can access the Internet from campus only if you are a computer science major or you are not a freshman.”The above statement could be considered as a single proposition but it would be more useful to break it down into simpler propositions. That would make it easier to analyze its meaning and to reason with it." }, { "code": null, "e": 35434, "s": 35369, "text": "The above sentence could be broken down into three propositions," }, { "code": null, "e": 35545, "s": 35434, "text": " - \"You can access the Internet from campus.\"\n - \"You are a computer science major.\"\n - \"You are a freshman.\"\n" }, { "code": null, "e": 35827, "s": 35545, "text": "Using logical connectives we can join the above-mentioned propositions to get a logical expression of the given statement.“only if” is one way to express a conditional statement, (as discussed in Part-1 of this topic in previous Article),Therefore the logical expression would be –" }, { "code": null, "e": 35854, "s": 35829, "text": "GATE CS Corner Questions" }, { "code": null, "e": 36052, "s": 35854, "text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 36232, "s": 36052, "text": "1. GATE CS 2009, Question 242. GATE CS 2014 Set-1, Question 633. GATE CS 2006, Question 284. GATE CS 2002, Question 85. GATE CS 2000, Question 306. GATE CS 2015 Set-1, Question 24" }, { "code": null, "e": 36245, "s": 36232, "text": "References –" }, { "code": null, "e": 36338, "s": 36245, "text": "Propositional Logic – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen" }, { "code": null, "e": 36640, "s": 36338, "text": "This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 36765, "s": 36640, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36780, "s": 36765, "text": "sagartomar9927" }, { "code": null, "e": 36801, "s": 36780, "text": "Discrete Mathematics" }, { "code": null, "e": 36825, "s": 36801, "text": "Engineering Mathematics" }, { "code": null, "e": 36833, "s": 36825, "text": "GATE CS" }, { "code": null, "e": 36931, "s": 36833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36953, "s": 36931, "text": "Inequalities in LaTeX" }, { "code": null, "e": 36974, "s": 36953, "text": "Activation Functions" }, { "code": null, "e": 36997, "s": 36974, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 37047, "s": 36997, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 37070, "s": 37047, "text": "Set Notations in LaTeX" }, { "code": null, "e": 37090, "s": 37070, "text": "Layers of OSI Model" }, { "code": null, "e": 37114, "s": 37090, "text": "ACID Properties in DBMS" }, { "code": null, "e": 37127, "s": 37114, "text": "TCP/IP Model" }, { "code": null, "e": 37154, "s": 37127, "text": "Types of Operating Systems" } ]
How to get the floor, ceiling and truncated values of the elements of a numpy array? - GeeksforGeeks
29 Aug, 2020 In this article, let’s discuss how to get the floor, ceiling, and truncated values of the elements of a Numpy array. First, we need to import the NumPy library to use all the functions available in it. This can be done with this import statement: import numpy as np The greatest integer that is less than or equal to x where x is the array element is known as floor value. It can found using the function numpy.floor() Syntax: numpy.floor(x[, out]) = ufunc ‘floor’) Example 1: Python # Import the numpy libraryimport numpy as np # Initialize numpy arraya = np.array([1.2]) # Get floor valuea = np.floor(a)print(a) Output: [1.] Example 2: Python import numpy as np a = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0]) a = np.floor(a)print(a) OutPut: [-2., -2., -1., 0., 1., 1., 3.] The least integer that is greater than or equal to x where x is the array element is known as ceil value. It can be found using the numpy.ceil() method. Syntax: numpy.ceil(x[, out]) = ufunc ‘ceil’) Example 1: Python # Import the numpy libraryimport numpy as np # Initialize numpy arraya = np.array([1.2]) # Get ceil valuea = np.ceil(a)print(a) Output: [2.] Example 2: Python import numpy as np a = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0]) a = np.ceil(a)print(a) Output: [-1., -1., -0., 1., 2., 2., 3.] The trunc of the scalar x is the nearest integer i which, closer to zero than x. This simply means that, the fractional part of the signed number x is discarded by this function. It can be found using the numpy.trunc() method. Syntax: numpy.trunc(x[, out]) = ufunc ‘trunc’) Example 1: Python # Import the numpy libraryimport numpy as np # Initialize numpy arraya = np.array([1.2]) # Get truncate valuea = np.trunc(a)print(a) Output: [1.] Example 2: Python import numpy as np a = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0]) a = np.trunc(a)print(a) Output: [-1., -1., -0., 0., 1., 1., 3.] Example to get floor, ceil, trunc values of the elements of a numpy array Python import numpy as np input_arr = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0])print(input_arr) floor_values = np.floor(input_arr)print("\nFloor values : \n", floor_values) ceil_values = np.ceil(input_arr)print("\nCeil values : \n", ceil_values) trunc_values = np.trunc(input_arr)print("\nTruncated values : \n", trunc_values) Output: [-1.8 -1.6 -0.5 0.5 1.6 1.8 3. ] Floor values : [-2. -2. -1. 0. 1. 1. 3.] Ceil values : [-1. -1. -0. 1. 2. 2. 3.] Truncated values : [-1. -1. -0. 0. 1. 1. 3.] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Aug, 2020" }, { "code": null, "e": 25784, "s": 25537, "text": "In this article, let’s discuss how to get the floor, ceiling, and truncated values of the elements of a Numpy array. First, we need to import the NumPy library to use all the functions available in it. This can be done with this import statement:" }, { "code": null, "e": 25804, "s": 25784, "text": "import numpy as np\n" }, { "code": null, "e": 25957, "s": 25804, "text": "The greatest integer that is less than or equal to x where x is the array element is known as floor value. It can found using the function numpy.floor()" }, { "code": null, "e": 25965, "s": 25957, "text": "Syntax:" }, { "code": null, "e": 26006, "s": 25965, "text": "numpy.floor(x[, out]) = ufunc ‘floor’) \n" }, { "code": null, "e": 26018, "s": 26006, "text": "Example 1: " }, { "code": null, "e": 26025, "s": 26018, "text": "Python" }, { "code": "# Import the numpy libraryimport numpy as np # Initialize numpy arraya = np.array([1.2]) # Get floor valuea = np.floor(a)print(a)", "e": 26159, "s": 26025, "text": null }, { "code": null, "e": 26168, "s": 26159, "text": "Output: " }, { "code": null, "e": 26174, "s": 26168, "text": "[1.]\n" }, { "code": null, "e": 26185, "s": 26174, "text": "Example 2:" }, { "code": null, "e": 26192, "s": 26185, "text": "Python" }, { "code": "import numpy as np a = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0]) a = np.floor(a)print(a)", "e": 26305, "s": 26192, "text": null }, { "code": null, "e": 26314, "s": 26305, "text": "OutPut: " }, { "code": null, "e": 26347, "s": 26314, "text": "[-2., -2., -1., 0., 1., 1., 3.]\n" }, { "code": null, "e": 26500, "s": 26347, "text": "The least integer that is greater than or equal to x where x is the array element is known as ceil value. It can be found using the numpy.ceil() method." }, { "code": null, "e": 26508, "s": 26500, "text": "Syntax:" }, { "code": null, "e": 26547, "s": 26508, "text": "numpy.ceil(x[, out]) = ufunc ‘ceil’) \n" }, { "code": null, "e": 26558, "s": 26547, "text": "Example 1:" }, { "code": null, "e": 26565, "s": 26558, "text": "Python" }, { "code": "# Import the numpy libraryimport numpy as np # Initialize numpy arraya = np.array([1.2]) # Get ceil valuea = np.ceil(a)print(a)", "e": 26697, "s": 26565, "text": null }, { "code": null, "e": 26706, "s": 26697, "text": "Output: " }, { "code": null, "e": 26712, "s": 26706, "text": "[2.]\n" }, { "code": null, "e": 26723, "s": 26712, "text": "Example 2:" }, { "code": null, "e": 26730, "s": 26723, "text": "Python" }, { "code": "import numpy as np a = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0]) a = np.ceil(a)print(a)", "e": 26842, "s": 26730, "text": null }, { "code": null, "e": 26850, "s": 26842, "text": "Output:" }, { "code": null, "e": 26883, "s": 26850, "text": "[-1., -1., -0., 1., 2., 2., 3.]\n" }, { "code": null, "e": 27110, "s": 26883, "text": "The trunc of the scalar x is the nearest integer i which, closer to zero than x. This simply means that, the fractional part of the signed number x is discarded by this function. It can be found using the numpy.trunc() method." }, { "code": null, "e": 27118, "s": 27110, "text": "Syntax:" }, { "code": null, "e": 27158, "s": 27118, "text": "numpy.trunc(x[, out]) = ufunc ‘trunc’)\n" }, { "code": null, "e": 27169, "s": 27158, "text": "Example 1:" }, { "code": null, "e": 27176, "s": 27169, "text": "Python" }, { "code": "# Import the numpy libraryimport numpy as np # Initialize numpy arraya = np.array([1.2]) # Get truncate valuea = np.trunc(a)print(a)", "e": 27313, "s": 27176, "text": null }, { "code": null, "e": 27321, "s": 27313, "text": "Output:" }, { "code": null, "e": 27327, "s": 27321, "text": "[1.]\n" }, { "code": null, "e": 27338, "s": 27327, "text": "Example 2:" }, { "code": null, "e": 27345, "s": 27338, "text": "Python" }, { "code": "import numpy as np a = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0]) a = np.trunc(a)print(a)", "e": 27458, "s": 27345, "text": null }, { "code": null, "e": 27466, "s": 27458, "text": "Output:" }, { "code": null, "e": 27499, "s": 27466, "text": "[-1., -1., -0., 0., 1., 1., 3.]\n" }, { "code": null, "e": 27573, "s": 27499, "text": "Example to get floor, ceil, trunc values of the elements of a numpy array" }, { "code": null, "e": 27580, "s": 27573, "text": "Python" }, { "code": "import numpy as np input_arr = np.array([-1.8, -1.6, -0.5, 0.5, 1.6, 1.8, 3.0])print(input_arr) floor_values = np.floor(input_arr)print(\"\\nFloor values : \\n\", floor_values) ceil_values = np.ceil(input_arr)print(\"\\nCeil values : \\n\", ceil_values) trunc_values = np.trunc(input_arr)print(\"\\nTruncated values : \\n\", trunc_values)", "e": 27935, "s": 27580, "text": null }, { "code": null, "e": 27943, "s": 27935, "text": "Output:" }, { "code": null, "e": 28128, "s": 27943, "text": "[-1.8 -1.6 -0.5 0.5 1.6 1.8 3. ]\n\nFloor values : \n [-2. -2. -1. 0. 1. 1. 3.]\n\nCeil values : \n [-1. -1. -0. 1. 2. 2. 3.]\n\nTruncated values : \n [-1. -1. -0. 0. 1. 1. 3.]\n" }, { "code": null, "e": 28163, "s": 28128, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 28176, "s": 28163, "text": "Python-numpy" }, { "code": null, "e": 28183, "s": 28176, "text": "Python" }, { "code": null, "e": 28281, "s": 28183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28313, "s": 28281, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28355, "s": 28313, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28397, "s": 28355, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28424, "s": 28397, "text": "Python Classes and Objects" }, { "code": null, "e": 28480, "s": 28424, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28502, "s": 28480, "text": "Defaultdict in Python" }, { "code": null, "e": 28541, "s": 28502, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28572, "s": 28541, "text": "Python | os.path.join() method" }, { "code": null, "e": 28601, "s": 28572, "text": "Create a directory in Python" } ]
Output of C programs | Set 47 (Decision and Control Statements) - GeeksforGeeks
30 Aug, 2017 Decision and Loops & Control Statements QUE.1 What is the output of this program ? #include <stdio.h>#include <stdio.h> void main(){ while (printf("geeks")) { }} OPTIONa) geeksb) infinite time geeksc) Compile time errord) No Output Answer: b Explanation: printf returns the number of characters of “geeks”. It returns 5 and loop runs infinite times because 5>0 and it is neither increasing nor decreasing. So it will print “geeks” infinite times QUE.2 What is the output of this program? #include <stdio.h> int main(){ while (printf("geeks")) return 0;} OPTIONa) geeksb) infinite time geeksc) compile time errord) no output Answer: a Explanation: printf returns the number of characters “geeks”. It will return 5 but when it enters int, the body of loop it will get “return 0” and terminates the program so it will print “geeks” only one time. QUE. 3 What is the output of this program ? #include <stdio.h> int main(){ if (printf("geeks")) switch (printf("for")) while (printf("geeks")) return 0;} OPTIONa) geeksb) forc) geeksford) geeksforgeeks Answer: c Explanation: if, switch and while are condition checkers in his () and print anything written in his (). In this program, first run if() and printf return “geeks” 5 and come to 2 switch. Now switch print “for” and printf return 3 and now switch find case 3 and case 3 is not in the program and it terminates the program and print only “geeksfor”. QUE.4 What is the output? #include <stdio.h> int main(){ if (printf("geeks") != 5) { } else printf("geeksforgeeks"); return 0;} OPTIONa) geeksb) geeksforgeeksc) geeksgeeksforgeeksd) Compile Errors Answer: c Explanation: First time, the if block is checked after printing geeks. Then check condition if(printf(“geeks”)!=5). Here condition is false then go to else part and print “geeksforgeeks” also. Then, go to the else part and print then output is geeksgeeksforgeeks. QUE.5 What is output of this program? #include <stdio.h>#define int n = printf("geeks")int main(){ int n = 10; printf("%d", n); return 0;} OPTIONa) geeksb) 10c) geeks 10d) Compile Errors Answer: d Explanation:Error: Invalid InitializationYou cannot define a printf as a int n=printf(). The data definition has no type or storage class. Related Article : Quiz on Loop and Control structures This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of C++ programs | Set 34 (File Handling) Result of sizeof operator Program to reverse columns in given 2D Array (Matrix) Output of C++ Program | Set 1 Output of Java program | Set 26 Output of C++ programs | Set 22 unsigned specifier (%u) in C with Examples Output of C Programs | Set 7 Output of C Programs | Set 6 Output of C programs | Set 8
[ { "code": null, "e": 25811, "s": 25783, "text": "\n30 Aug, 2017" }, { "code": null, "e": 25851, "s": 25811, "text": "Decision and Loops & Control Statements" }, { "code": null, "e": 25894, "s": 25851, "text": "QUE.1 What is the output of this program ?" }, { "code": "#include <stdio.h>#include <stdio.h> void main(){ while (printf(\"geeks\")) { }}", "e": 25980, "s": 25894, "text": null }, { "code": null, "e": 26050, "s": 25980, "text": "OPTIONa) geeksb) infinite time geeksc) Compile time errord) No Output" }, { "code": null, "e": 26060, "s": 26050, "text": "Answer: b" }, { "code": null, "e": 26264, "s": 26060, "text": "Explanation: printf returns the number of characters of “geeks”. It returns 5 and loop runs infinite times because 5>0 and it is neither increasing nor decreasing. So it will print “geeks” infinite times" }, { "code": null, "e": 26306, "s": 26264, "text": "QUE.2 What is the output of this program?" }, { "code": "#include <stdio.h> int main(){ while (printf(\"geeks\")) return 0;}", "e": 26383, "s": 26306, "text": null }, { "code": null, "e": 26453, "s": 26383, "text": "OPTIONa) geeksb) infinite time geeksc) compile time errord) no output" }, { "code": null, "e": 26464, "s": 26453, "text": "Answer: a" }, { "code": null, "e": 26674, "s": 26464, "text": "Explanation: printf returns the number of characters “geeks”. It will return 5 but when it enters int, the body of loop it will get “return 0” and terminates the program so it will print “geeks” only one time." }, { "code": null, "e": 26718, "s": 26674, "text": "QUE. 3 What is the output of this program ?" }, { "code": "#include <stdio.h> int main(){ if (printf(\"geeks\")) switch (printf(\"for\")) while (printf(\"geeks\")) return 0;}", "e": 26865, "s": 26718, "text": null }, { "code": null, "e": 26913, "s": 26865, "text": "OPTIONa) geeksb) forc) geeksford) geeksforgeeks" }, { "code": null, "e": 26923, "s": 26913, "text": "Answer: c" }, { "code": null, "e": 27270, "s": 26923, "text": "Explanation: if, switch and while are condition checkers in his () and print anything written in his (). In this program, first run if() and printf return “geeks” 5 and come to 2 switch. Now switch print “for” and printf return 3 and now switch find case 3 and case 3 is not in the program and it terminates the program and print only “geeksfor”." }, { "code": null, "e": 27296, "s": 27270, "text": "QUE.4 What is the output?" }, { "code": "#include <stdio.h> int main(){ if (printf(\"geeks\") != 5) { } else printf(\"geeksforgeeks\"); return 0;}", "e": 27417, "s": 27296, "text": null }, { "code": null, "e": 27486, "s": 27417, "text": "OPTIONa) geeksb) geeksforgeeksc) geeksgeeksforgeeksd) Compile Errors" }, { "code": null, "e": 27496, "s": 27486, "text": "Answer: c" }, { "code": null, "e": 27760, "s": 27496, "text": "Explanation: First time, the if block is checked after printing geeks. Then check condition if(printf(“geeks”)!=5). Here condition is false then go to else part and print “geeksforgeeks” also. Then, go to the else part and print then output is geeksgeeksforgeeks." }, { "code": null, "e": 27798, "s": 27760, "text": "QUE.5 What is output of this program?" }, { "code": "#include <stdio.h>#define int n = printf(\"geeks\")int main(){ int n = 10; printf(\"%d\", n); return 0;}", "e": 27908, "s": 27798, "text": null }, { "code": null, "e": 27956, "s": 27908, "text": "OPTIONa) geeksb) 10c) geeks 10d) Compile Errors" }, { "code": null, "e": 27966, "s": 27956, "text": "Answer: d" }, { "code": null, "e": 28105, "s": 27966, "text": "Explanation:Error: Invalid InitializationYou cannot define a printf as a int n=printf(). The data definition has no type or storage class." }, { "code": null, "e": 28159, "s": 28105, "text": "Related Article : Quiz on Loop and Control structures" }, { "code": null, "e": 28456, "s": 28159, "text": "This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28581, "s": 28456, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28590, "s": 28581, "text": "C-Output" }, { "code": null, "e": 28605, "s": 28590, "text": "Program Output" }, { "code": null, "e": 28703, "s": 28605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28751, "s": 28703, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 28777, "s": 28751, "text": "Result of sizeof operator" }, { "code": null, "e": 28831, "s": 28777, "text": "Program to reverse columns in given 2D Array (Matrix)" }, { "code": null, "e": 28861, "s": 28831, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 28893, "s": 28861, "text": "Output of Java program | Set 26" }, { "code": null, "e": 28925, "s": 28893, "text": "Output of C++ programs | Set 22" }, { "code": null, "e": 28968, "s": 28925, "text": "unsigned specifier (%u) in C with Examples" }, { "code": null, "e": 28997, "s": 28968, "text": "Output of C Programs | Set 7" }, { "code": null, "e": 29026, "s": 28997, "text": "Output of C Programs | Set 6" } ]
Get UTC timestamp in Python - GeeksforGeeks
17 Mar, 2021 Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. Note: For more information, refer to Python datetime module with examples Example: # Python program to demonstrate# datetime module import datetime dt = datetime.date(2020, 1, 26)# prints the date as date# objectprint(dt) # prints the current dateprint(datetime.date.today()) # prints the date and timedt = datetime.datetime(1999, 12, 12, 12, 12, 12, 342380) print(dt) # prints the current date # and timeprint(datetime.datetime.now()) Output: 2020-01-26 2020-02-04 1999-12-12 12:12:12.342380 2020-02-04 07:46:29.315237 Use the datetime.datetime.now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp. Example: from datetime import timezoneimport datetime # Getting the current date# and timedt = datetime.datetime.now(timezone.utc) utc_time = dt.replace(tzinfo=timezone.utc)utc_timestamp = utc_time.timestamp() print(utc_timestamp) Output: 1615975803.787904 Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26075, "s": 26047, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26366, "s": 26075, "text": "Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps." }, { "code": null, "e": 26440, "s": 26366, "text": "Note: For more information, refer to Python datetime module with examples" }, { "code": null, "e": 26449, "s": 26440, "text": "Example:" }, { "code": "# Python program to demonstrate# datetime module import datetime dt = datetime.date(2020, 1, 26)# prints the date as date# objectprint(dt) # prints the current dateprint(datetime.date.today()) # prints the date and timedt = datetime.datetime(1999, 12, 12, 12, 12, 12, 342380) print(dt) # prints the current date # and timeprint(datetime.datetime.now())", "e": 26811, "s": 26449, "text": null }, { "code": null, "e": 26819, "s": 26811, "text": "Output:" }, { "code": null, "e": 26896, "s": 26819, "text": "2020-01-26\n2020-02-04\n1999-12-12 12:12:12.342380\n2020-02-04 07:46:29.315237\n" }, { "code": null, "e": 27110, "s": 26896, "text": "Use the datetime.datetime.now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp." }, { "code": null, "e": 27119, "s": 27110, "text": "Example:" }, { "code": "from datetime import timezoneimport datetime # Getting the current date# and timedt = datetime.datetime.now(timezone.utc) utc_time = dt.replace(tzinfo=timezone.utc)utc_timestamp = utc_time.timestamp() print(utc_timestamp)", "e": 27346, "s": 27119, "text": null }, { "code": null, "e": 27354, "s": 27346, "text": "Output:" }, { "code": null, "e": 27373, "s": 27354, "text": "1615975803.787904\n" }, { "code": null, "e": 27389, "s": 27373, "text": "Python-datetime" }, { "code": null, "e": 27396, "s": 27389, "text": "Python" }, { "code": null, "e": 27494, "s": 27396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27512, "s": 27494, "text": "Python Dictionary" }, { "code": null, "e": 27547, "s": 27512, "text": "Read a file line by line in Python" }, { "code": null, "e": 27579, "s": 27547, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27601, "s": 27579, "text": "Enumerate() in Python" }, { "code": null, "e": 27643, "s": 27601, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27673, "s": 27643, "text": "Iterate over a list in Python" }, { "code": null, "e": 27702, "s": 27673, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27746, "s": 27702, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27783, "s": 27746, "text": "Create a Pandas DataFrame from Lists" } ]
Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG ) - GeeksforGeeks
14 Sep, 2021 Given a 2D array Edges[][], representing a directed edge between the pair of nodes in a Directed Acyclic Connected Graph consisting of N nodes valued from [1, N] and an array arr[] representing weights of each node, the task is to find the maximum absolute difference between the weights of any node and any of its ancestors. Examples: Input: N = 5, M = 4, Edges[][2] = {{1, 2}, {2, 3}, {4, 5}, {1, 3}}, arr[] = {13, 8, 3, 15, 18}Output: 10Explanation: From the above graph, it can be observed that the maximum difference between the value of any node and any of its ancestors is 18 (Node 5) – 8 (Node 2) = 10. Input: N = 4, M = 3, Edges[][2] = {{1, 2}, {2, 4}, {1, 3}}, arr[] = {2, 3, 1, 5}Output: 3 Approach: The idea to solve the given problem is to perform DFS Traversal on the Graph and populate the maximum and minimum values from each node to its child node and find the maximum absolute difference.Follow the steps below to solve the given problem: Initialize a variable, say ans as INT_MIN to store the required maximum difference. Perform DFS traversal on the given graph to find the maximum absolute difference between the weights of a node and any of its ancestors by performing the following operations:For each source node, say src, update the value of ans to store the maximum of the absolute difference between the weight of src and currentMin and currentMax respectively.Update the value of currentMin as the minimum of currentMin and the value of the source node src.Update the value of currentMax as the maximum of currentMax and the value of the source node src.Now, recursively traverse the child nodes of src and update values of currentMax and currentMin as DFS(child, Adj, ans, currentMin, currentMax). For each source node, say src, update the value of ans to store the maximum of the absolute difference between the weight of src and currentMin and currentMax respectively. Update the value of currentMin as the minimum of currentMin and the value of the source node src. Update the value of currentMax as the maximum of currentMax and the value of the source node src. Now, recursively traverse the child nodes of src and update values of currentMax and currentMin as DFS(child, Adj, ans, currentMin, currentMax). After completing the above steps, print the value of ans as the resultant maximum difference. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to perform DFS// Traversal on the given graphvoid DFS(int src, vector<int> Adj[], int& ans, int arr[], int currentMin, int currentMax){ // Update the value of ans ans = max( ans, max(abs( currentMax - arr[src - 1]), abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = min(currentMin, arr[src - 1]); currentMax = min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src for (auto& child : Adj[src]) { // Recursively call // for the child node DFS(child, Adj, ans, arr, currentMin, currentMax); }} // Function to calculate maximum absolute// difference between a node and its ancestorvoid getMaximumDifference(int Edges[][2], int arr[], int N, int M){ // Stores the adjacency list of graph vector<int> Adj[N + 1]; // Create Adjacency list for (int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; // Add a directed edge Adj[u].push_back(v); } int ans = 0; // Perform DFS Traversal DFS(1, Adj, ans, arr, arr[0], arr[0]); // Print the maximum // absolute difference cout << ans;} // Driver Codeint main(){ int N = 5, M = 4; int Edges[][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 } }; int arr[] = { 13, 8, 3, 15, 18 }; getMaximumDifference(Edges, arr, N, M); return 0;} // Java program for the above approachimport java.util.*; class GFG{ static int ans; // Function to perform DFS// Traversal on the given graphstatic void DFS(int src, ArrayList<ArrayList<Integer> > Adj, int arr[], int currentMin, int currentMax){ // Update the value of ans ans = Math.max(ans, Math.max(Math.abs(currentMax - arr[src - 1]), Math.abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = Math.min(currentMin, arr[src - 1]); currentMax = Math.min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src for(Integer child : Adj.get(src)) { // Recursively call // for the child node DFS(child, Adj, arr, currentMin, currentMax); }} // Function to calculate maximum absolute// difference between a node and its ancestorstatic void getMaximumDifference(int Edges[][], int arr[], int N, int M){ ans = 0; // Stores the adjacency list of graph ArrayList<ArrayList<Integer>> Adj = new ArrayList<>(); for(int i = 0; i < N + 1; i++) Adj.add(new ArrayList<>()); // Create Adjacency list for(int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; // Add a directed edge Adj.get(u).add(v); } // Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]); // Print the maximum // absolute difference System.out.println(ans);} // Driver codepublic static void main(String[] args){ int N = 5, M = 4; int Edges[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 } }; int arr[] = { 13, 8, 3, 15, 18 }; getMaximumDifference(Edges, arr, N, M);}} // This code is contributed by offbeat # Python3 program for the above approachans = 0 # Function to perform DFS# Traversal on the given graphdef DFS(src, Adj, arr, currentMin, currentMax): # Update the value of ans global ans ans = max(ans, max(abs(currentMax - arr[src - 1]), abs(currentMin - arr[src - 1]))) # Update the currentMin and currentMax currentMin = min(currentMin, arr[src - 1]) currentMax = min(currentMax, arr[src - 1]) # Traverse the adjacency # list of the node src for child in Adj[src]: # Recursively call # for the child node DFS(child, Adj, arr, currentMin, currentMax) # Function to calculate maximum absolute# difference between a node and its ancestordef getMaximumDifference(Edges, arr, N, M): global ans # Stores the adjacency list of graph Adj = [[] for i in range(N + 1)] # Create Adjacency list for i in range(M): u = Edges[i][0] v = Edges[i][1] # Add a directed edge Adj[u].append(v) # Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]) # Print the maximum # absolute difference print(ans) # Driver Codeif __name__ == '__main__': N = 5 M = 4 Edges = [[1, 2], [2, 3], [4, 5], [1, 3]] arr = [13, 8, 3, 15, 18] getMaximumDifference(Edges, arr, N, M) # This code is contributed by ipg2016107 // C# program for the above approachusing System;using System.Collections.Generic;class GFG { static int ans; // Function to perform DFS // Traversal on the given graph static void DFS(int src, List<List<int>> Adj, int[] arr, int currentMin, int currentMax) { // Update the value of ans ans = Math.Max(ans, Math.Max(Math.Abs(currentMax - arr[src - 1]), Math.Abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = Math.Min(currentMin, arr[src - 1]); currentMax = Math.Min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src foreach(int child in Adj[src]) { // Recursively call // for the child node DFS(child, Adj, arr, currentMin, currentMax); } } // Function to calculate maximum absolute // difference between a node and its ancestor static void getMaximumDifference(int[,] Edges, int[] arr, int N, int M) { ans = 0; // Stores the adjacency list of graph List<List<int>> Adj = new List<List<int>>(); for(int i = 0; i < N + 1; i++) Adj.Add(new List<int>()); // Create Adjacency list for(int i = 0; i < M; i++) { int u = Edges[i,0]; int v = Edges[i,1]; // Add a directed edge Adj[u].Add(v); } // Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]); // Print the maximum // absolute difference Console.WriteLine(ans); } static void Main() { int N = 5, M = 4; int[,] Edges = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 } }; int[] arr = { 13, 8, 3, 15, 18 }; getMaximumDifference(Edges, arr, N, M); }} // This code is contributed by rameshtravel07. <script> // Javascript program for the above approach var ans = 0; // Function to perform DFS// Traversal on the given graphfunction DFS(src, Adj, arr, currentMin, currentMax){ // Update the value of ans ans = Math.max( ans, Math.max(Math.abs( currentMax - arr[src - 1]), Math.abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = Math.min(currentMin, arr[src - 1]); currentMax = Math.min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src Adj[src].forEach(child => { // Recursively call // for the child node DFS(child, Adj,arr, currentMin, currentMax); });} // Function to calculate maximum absolute// difference between a node and its ancestorfunction getMaximumDifference(Edges, arr, N, M){ // Stores the adjacency list of graph var Adj = Array.from(Array(N+1), ()=> Array()); // Create Adjacency list for (var i = 0; i < M; i++) { var u = Edges[i][0]; var v = Edges[i][1]; // Add a directed edge Adj[u].push(v); } // Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]); // Print the maximum // absolute difference document.write( ans);} // Driver Codevar N = 5, M = 4;var Edges = [ [ 1, 2 ], [ 2, 3 ], [ 4, 5 ], [ 1, 3 ] ];var arr = [13, 8, 3, 15, 18];getMaximumDifference(Edges, arr, N, M); </script> 10 Time Complexity: O(N + M)Auxiliary Space: O(N) ipg2016107 offbeat rrrtnx rameshtravel07 DFS Data Structures Graph Recursion Searching Technical Scripter Data Structures Searching Recursion DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Linked List | Question 5 Data Structures | Tree Traversals | Question 4 Data Structures | Linked List | Question 6 Difference between Singly linked list and Doubly linked list Advantages and Disadvantages of Linked List Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 26939, "s": 26911, "text": "\n14 Sep, 2021" }, { "code": null, "e": 27265, "s": 26939, "text": "Given a 2D array Edges[][], representing a directed edge between the pair of nodes in a Directed Acyclic Connected Graph consisting of N nodes valued from [1, N] and an array arr[] representing weights of each node, the task is to find the maximum absolute difference between the weights of any node and any of its ancestors." }, { "code": null, "e": 27275, "s": 27265, "text": "Examples:" }, { "code": null, "e": 27392, "s": 27275, "text": "Input: N = 5, M = 4, Edges[][2] = {{1, 2}, {2, 3}, {4, 5}, {1, 3}}, arr[] = {13, 8, 3, 15, 18}Output: 10Explanation:" }, { "code": null, "e": 27550, "s": 27392, "text": "From the above graph, it can be observed that the maximum difference between the value of any node and any of its ancestors is 18 (Node 5) – 8 (Node 2) = 10." }, { "code": null, "e": 27640, "s": 27550, "text": "Input: N = 4, M = 3, Edges[][2] = {{1, 2}, {2, 4}, {1, 3}}, arr[] = {2, 3, 1, 5}Output: 3" }, { "code": null, "e": 27896, "s": 27640, "text": "Approach: The idea to solve the given problem is to perform DFS Traversal on the Graph and populate the maximum and minimum values from each node to its child node and find the maximum absolute difference.Follow the steps below to solve the given problem:" }, { "code": null, "e": 27980, "s": 27896, "text": "Initialize a variable, say ans as INT_MIN to store the required maximum difference." }, { "code": null, "e": 28666, "s": 27980, "text": "Perform DFS traversal on the given graph to find the maximum absolute difference between the weights of a node and any of its ancestors by performing the following operations:For each source node, say src, update the value of ans to store the maximum of the absolute difference between the weight of src and currentMin and currentMax respectively.Update the value of currentMin as the minimum of currentMin and the value of the source node src.Update the value of currentMax as the maximum of currentMax and the value of the source node src.Now, recursively traverse the child nodes of src and update values of currentMax and currentMin as DFS(child, Adj, ans, currentMin, currentMax)." }, { "code": null, "e": 28839, "s": 28666, "text": "For each source node, say src, update the value of ans to store the maximum of the absolute difference between the weight of src and currentMin and currentMax respectively." }, { "code": null, "e": 28937, "s": 28839, "text": "Update the value of currentMin as the minimum of currentMin and the value of the source node src." }, { "code": null, "e": 29035, "s": 28937, "text": "Update the value of currentMax as the maximum of currentMax and the value of the source node src." }, { "code": null, "e": 29180, "s": 29035, "text": "Now, recursively traverse the child nodes of src and update values of currentMax and currentMin as DFS(child, Adj, ans, currentMin, currentMax)." }, { "code": null, "e": 29274, "s": 29180, "text": "After completing the above steps, print the value of ans as the resultant maximum difference." }, { "code": null, "e": 29325, "s": 29274, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29329, "s": 29325, "text": "C++" }, { "code": null, "e": 29334, "s": 29329, "text": "Java" }, { "code": null, "e": 29342, "s": 29334, "text": "Python3" }, { "code": null, "e": 29345, "s": 29342, "text": "C#" }, { "code": null, "e": 29356, "s": 29345, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to perform DFS// Traversal on the given graphvoid DFS(int src, vector<int> Adj[], int& ans, int arr[], int currentMin, int currentMax){ // Update the value of ans ans = max( ans, max(abs( currentMax - arr[src - 1]), abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = min(currentMin, arr[src - 1]); currentMax = min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src for (auto& child : Adj[src]) { // Recursively call // for the child node DFS(child, Adj, ans, arr, currentMin, currentMax); }} // Function to calculate maximum absolute// difference between a node and its ancestorvoid getMaximumDifference(int Edges[][2], int arr[], int N, int M){ // Stores the adjacency list of graph vector<int> Adj[N + 1]; // Create Adjacency list for (int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; // Add a directed edge Adj[u].push_back(v); } int ans = 0; // Perform DFS Traversal DFS(1, Adj, ans, arr, arr[0], arr[0]); // Print the maximum // absolute difference cout << ans;} // Driver Codeint main(){ int N = 5, M = 4; int Edges[][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 } }; int arr[] = { 13, 8, 3, 15, 18 }; getMaximumDifference(Edges, arr, N, M); return 0;}", "e": 31011, "s": 29356, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ static int ans; // Function to perform DFS// Traversal on the given graphstatic void DFS(int src, ArrayList<ArrayList<Integer> > Adj, int arr[], int currentMin, int currentMax){ // Update the value of ans ans = Math.max(ans, Math.max(Math.abs(currentMax - arr[src - 1]), Math.abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = Math.min(currentMin, arr[src - 1]); currentMax = Math.min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src for(Integer child : Adj.get(src)) { // Recursively call // for the child node DFS(child, Adj, arr, currentMin, currentMax); }} // Function to calculate maximum absolute// difference between a node and its ancestorstatic void getMaximumDifference(int Edges[][], int arr[], int N, int M){ ans = 0; // Stores the adjacency list of graph ArrayList<ArrayList<Integer>> Adj = new ArrayList<>(); for(int i = 0; i < N + 1; i++) Adj.add(new ArrayList<>()); // Create Adjacency list for(int i = 0; i < M; i++) { int u = Edges[i][0]; int v = Edges[i][1]; // Add a directed edge Adj.get(u).add(v); } // Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]); // Print the maximum // absolute difference System.out.println(ans);} // Driver codepublic static void main(String[] args){ int N = 5, M = 4; int Edges[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 } }; int arr[] = { 13, 8, 3, 15, 18 }; getMaximumDifference(Edges, arr, N, M);}} // This code is contributed by offbeat", "e": 32868, "s": 31011, "text": null }, { "code": "# Python3 program for the above approachans = 0 # Function to perform DFS# Traversal on the given graphdef DFS(src, Adj, arr, currentMin, currentMax): # Update the value of ans global ans ans = max(ans, max(abs(currentMax - arr[src - 1]), abs(currentMin - arr[src - 1]))) # Update the currentMin and currentMax currentMin = min(currentMin, arr[src - 1]) currentMax = min(currentMax, arr[src - 1]) # Traverse the adjacency # list of the node src for child in Adj[src]: # Recursively call # for the child node DFS(child, Adj, arr, currentMin, currentMax) # Function to calculate maximum absolute# difference between a node and its ancestordef getMaximumDifference(Edges, arr, N, M): global ans # Stores the adjacency list of graph Adj = [[] for i in range(N + 1)] # Create Adjacency list for i in range(M): u = Edges[i][0] v = Edges[i][1] # Add a directed edge Adj[u].append(v) # Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]) # Print the maximum # absolute difference print(ans) # Driver Codeif __name__ == '__main__': N = 5 M = 4 Edges = [[1, 2], [2, 3], [4, 5], [1, 3]] arr = [13, 8, 3, 15, 18] getMaximumDifference(Edges, arr, N, M) # This code is contributed by ipg2016107", "e": 34237, "s": 32868, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { static int ans; // Function to perform DFS // Traversal on the given graph static void DFS(int src, List<List<int>> Adj, int[] arr, int currentMin, int currentMax) { // Update the value of ans ans = Math.Max(ans, Math.Max(Math.Abs(currentMax - arr[src - 1]), Math.Abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = Math.Min(currentMin, arr[src - 1]); currentMax = Math.Min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src foreach(int child in Adj[src]) { // Recursively call // for the child node DFS(child, Adj, arr, currentMin, currentMax); } } // Function to calculate maximum absolute // difference between a node and its ancestor static void getMaximumDifference(int[,] Edges, int[] arr, int N, int M) { ans = 0; // Stores the adjacency list of graph List<List<int>> Adj = new List<List<int>>(); for(int i = 0; i < N + 1; i++) Adj.Add(new List<int>()); // Create Adjacency list for(int i = 0; i < M; i++) { int u = Edges[i,0]; int v = Edges[i,1]; // Add a directed edge Adj[u].Add(v); } // Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]); // Print the maximum // absolute difference Console.WriteLine(ans); } static void Main() { int N = 5, M = 4; int[,] Edges = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 } }; int[] arr = { 13, 8, 3, 15, 18 }; getMaximumDifference(Edges, arr, N, M); }} // This code is contributed by rameshtravel07.", "e": 36247, "s": 34237, "text": null }, { "code": "<script> // Javascript program for the above approach var ans = 0; // Function to perform DFS// Traversal on the given graphfunction DFS(src, Adj, arr, currentMin, currentMax){ // Update the value of ans ans = Math.max( ans, Math.max(Math.abs( currentMax - arr[src - 1]), Math.abs(currentMin - arr[src - 1]))); // Update the currentMin and currentMax currentMin = Math.min(currentMin, arr[src - 1]); currentMax = Math.min(currentMax, arr[src - 1]); // Traverse the adjacency // list of the node src Adj[src].forEach(child => { // Recursively call // for the child node DFS(child, Adj,arr, currentMin, currentMax); });} // Function to calculate maximum absolute// difference between a node and its ancestorfunction getMaximumDifference(Edges, arr, N, M){ // Stores the adjacency list of graph var Adj = Array.from(Array(N+1), ()=> Array()); // Create Adjacency list for (var i = 0; i < M; i++) { var u = Edges[i][0]; var v = Edges[i][1]; // Add a directed edge Adj[u].push(v); } // Perform DFS Traversal DFS(1, Adj, arr, arr[0], arr[0]); // Print the maximum // absolute difference document.write( ans);} // Driver Codevar N = 5, M = 4;var Edges = [ [ 1, 2 ], [ 2, 3 ], [ 4, 5 ], [ 1, 3 ] ];var arr = [13, 8, 3, 15, 18];getMaximumDifference(Edges, arr, N, M); </script>", "e": 37749, "s": 36247, "text": null }, { "code": null, "e": 37752, "s": 37749, "text": "10" }, { "code": null, "e": 37801, "s": 37754, "text": "Time Complexity: O(N + M)Auxiliary Space: O(N)" }, { "code": null, "e": 37814, "s": 37803, "text": "ipg2016107" }, { "code": null, "e": 37822, "s": 37814, "text": "offbeat" }, { "code": null, "e": 37829, "s": 37822, "text": "rrrtnx" }, { "code": null, "e": 37844, "s": 37829, "text": "rameshtravel07" }, { "code": null, "e": 37848, "s": 37844, "text": "DFS" }, { "code": null, "e": 37864, "s": 37848, "text": "Data Structures" }, { "code": null, "e": 37870, "s": 37864, "text": "Graph" }, { "code": null, "e": 37880, "s": 37870, "text": "Recursion" }, { "code": null, "e": 37890, "s": 37880, "text": "Searching" }, { "code": null, "e": 37909, "s": 37890, "text": "Technical Scripter" }, { "code": null, "e": 37925, "s": 37909, "text": "Data Structures" }, { "code": null, "e": 37935, "s": 37925, "text": "Searching" }, { "code": null, "e": 37945, "s": 37935, "text": "Recursion" }, { "code": null, "e": 37949, "s": 37945, "text": "DFS" }, { "code": null, "e": 37955, "s": 37949, "text": "Graph" }, { "code": null, "e": 38053, "s": 37955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38096, "s": 38053, "text": "Data Structures | Linked List | Question 5" }, { "code": null, "e": 38143, "s": 38096, "text": "Data Structures | Tree Traversals | Question 4" }, { "code": null, "e": 38186, "s": 38143, "text": "Data Structures | Linked List | Question 6" }, { "code": null, "e": 38247, "s": 38186, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 38291, "s": 38247, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 38331, "s": 38291, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 38369, "s": 38331, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 38420, "s": 38369, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 38478, "s": 38420, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Multiply two integers without using multiplication, division and bitwise operators, and no loops
08 Jul, 2022 By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times. Base case: When the numbers of times x has to be added becomes 0. Recursive call: If the base case is not met, then add x to the current resultant value and pass it to the next iteration. C++ C Java Python3 C# PHP Javascript // C++ program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops#include<iostream> using namespace std;class GFG{ /* function to multiply two numbers x and y*/public : int multiply(int x, int y){ /* 0 multiplied with anything gives 0 */ if(y == 0) return 0; /* Add x one by one */ if(y > 0 ) return (x + multiply(x, y-1)); /* the case where y is negative */ if(y < 0 ) return -multiply(x, -y);}}; // Driver codeint main(){ GFG g; cout << endl << g.multiply(5, -11); getchar(); return 0;} // This code is contributed by SoM15242 #include<stdio.h>/* function to multiply two numbers x and y*/int multiply(int x, int y){ /* 0 multiplied with anything gives 0 */ if(y == 0) return 0; /* Add x one by one */ if(y > 0 ) return (x + multiply(x, y-1)); /* the case where y is negative */ if(y < 0 ) return -multiply(x, -y);} int main(){ printf("\n %d", multiply(5, -11)); getchar(); return 0;} class GFG { /* function to multiply two numbers x and y*/ static int multiply(int x, int y) { /* 0 multiplied with anything gives 0 */ if (y == 0) return 0; /* Add x one by one */ if (y > 0) return (x + multiply(x, y - 1)); /* the case where y is negative */ if (y < 0) return -multiply(x, -y); return -1; } // Driver code public static void main(String[] args) { System.out.print("\n" + multiply(5, -11)); }} // This code is contributed by Anant Agarwal. # Function to multiply two numbers# x and ydef multiply(x,y): # 0 multiplied with anything # gives 0 if(y == 0): return 0 # Add x one by one if(y > 0 ): return (x + multiply(x, y - 1)) # The case where y is negative if(y < 0 ): return -multiply(x, -y) # Driver codeprint(multiply(5, -11)) # This code is contributed by Anant Agarwal. // Multiply two integers without// using multiplication, division// and bitwise operators, and no// loopsusing System; class GFG { // function to multiply two numbers // x and y static int multiply(int x, int y) { // 0 multiplied with anything gives 0 if (y == 0) return 0; // Add x one by one if (y > 0) return (x + multiply(x, y - 1)); // the case where y is negative if (y < 0) return -multiply(x, -y); return -1; } // Driver code public static void Main() { Console.WriteLine(multiply(5, -11)); }} // This code is contributed by vt_m. <?php// function to multiply// two numbers x and yfunction multiply($x, $y){/* 0 multiplied withanything gives 0 */if($y == 0) return 0; /* Add x one by one */if($y > 0 ) return ($x + multiply($x, $y - 1)); /* the case wherey is negative */if($y < 0 ) return -multiply($x, -$y);} // Driver Codeecho multiply(5, -11); // This code is contributed by mits.?> <script> // javascript program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops /* function to multiply two numbers x and y*/function multiply( x, y){ /* 0 multiplied with anything gives 0 */ if(y == 0) return 0; /* Add x one by one */ if(y > 0 ) return (x + multiply(x, y-1)); /* the case where y is negative */ if(y < 0 ) return -multiply(x, -y);} // Driver code document.write( multiply(5, -11)); // This code is contributed by todaysgaurav </script> -55 Time Complexity: O(y) where y is the second argument to function multiply(). Auxiliary Space: O(y) for the recursion stack Another approach: The problem can also be solved using basic math property (a+b)2 = a2 + b2 + 2a*b ⇒ a*b = ((a+b)2 – a2 – b2) / 2 For computing the square of numbers, we can use the power function in C++ and for dividing by 2 in the above expression we can write a recursive function. Below is the implementation of the above approach: C++ Python3 Javascript // C++ program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops#include<bits/stdc++.h>using namespace std; // divide a number by 2 recursivelyint divideby2(int num){ if(num<2) return 0; return 1 + divideby2(num-2);} int multiply(int a,int b){ int whole_square=pow(a+b,2); int a_square=pow(a,2); int b_square=pow(b,2); int val= whole_square- a_square - b_square; int product; // for positive value of variable val if(val>=0) product = divideby2(val); // for negative value of variable val // we first compute the division by 2 for // positive val and by subtracting from // 0 we can make it negative else product = 0 - divideby2(abs(val)); return product;} // Driver codeint main(){ int a=5; int b=-11; cout << multiply(a,b); return 0;} // This code is contributed by Pushpesh raj. # Python3 program to Multiply two integers without# using multiplication, division and bitwise# operators, and no loops # divide a number by 2 recursivelydef divideby2(num): if(num < 2): return 0 return 1 + divideby2(num-2) def multiply(a, b): whole_square = (a + b) ** 2 a_square = pow(a, 2) b_square = pow(b, 2) val = whole_square - a_square - b_square # for positive value of variable val if(val >= 0): product = divideby2(val) # for negative value of variable val # we first compute the division by 2 for # positive val and by subtracting from # 0 we can make it negative else: product = 0 - divideby2(abs(val)) return product # Driver codea = 5b = -11print(multiply(a, b)) # This code is contributed by phasing17 // JavaScript program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops // divide a number by 2 recursivelyfunction divideby2(num){ if(num<2) return 0; return 1 + divideby2(num-2);} function multiply(a, b){ let whole_square = Math.pow(a+b,2); let a_square = Math.pow(a,2); let b_square = Math.pow(b,2); let val = whole_square- a_square - b_square; let product; // for positive value of variable val if(val>=0) product = divideby2(val); // for negative value of variable val // we first compute the division by 2 for // positive val and by subtracting from // 0 we can make it negative else product = 0 - divideby2(Math.abs(val)); return product;} // Driver codelet a = 5;let b = -11;console.log(multiply(a,b)); // This code is contributed by phasing17 -55 Russian Peasant (Multiply two numbers using bitwise operators)Please write comments if you find any of the above code/algorithm incorrect, or find better ways to solve the same problem. Mithun Kumar SoumikMondal todaysgaurav subhammahato348 Code_r pushpeshrajdx01 phasing17 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Sieve of Eratosthenes Prime Numbers Minimum number of jumps to reach end Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 187, "s": 52, "text": "By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. " }, { "code": null, "e": 197, "s": 187, "text": "Approach:" }, { "code": null, "e": 332, "s": 197, "text": "Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times." }, { "code": null, "e": 400, "s": 332, "text": "Base case: When the numbers of times x has to be added becomes 0. " }, { "code": null, "e": 522, "s": 400, "text": "Recursive call: If the base case is not met, then add x to the current resultant value and pass it to the next iteration." }, { "code": null, "e": 526, "s": 522, "text": "C++" }, { "code": null, "e": 528, "s": 526, "text": "C" }, { "code": null, "e": 533, "s": 528, "text": "Java" }, { "code": null, "e": 541, "s": 533, "text": "Python3" }, { "code": null, "e": 544, "s": 541, "text": "C#" }, { "code": null, "e": 548, "s": 544, "text": "PHP" }, { "code": null, "e": 559, "s": 548, "text": "Javascript" }, { "code": "// C++ program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops#include<iostream> using namespace std;class GFG{ /* function to multiply two numbers x and y*/public : int multiply(int x, int y){ /* 0 multiplied with anything gives 0 */ if(y == 0) return 0; /* Add x one by one */ if(y > 0 ) return (x + multiply(x, y-1)); /* the case where y is negative */ if(y < 0 ) return -multiply(x, -y);}}; // Driver codeint main(){ GFG g; cout << endl << g.multiply(5, -11); getchar(); return 0;} // This code is contributed by SoM15242", "e": 1187, "s": 559, "text": null }, { "code": "#include<stdio.h>/* function to multiply two numbers x and y*/int multiply(int x, int y){ /* 0 multiplied with anything gives 0 */ if(y == 0) return 0; /* Add x one by one */ if(y > 0 ) return (x + multiply(x, y-1)); /* the case where y is negative */ if(y < 0 ) return -multiply(x, -y);} int main(){ printf(\"\\n %d\", multiply(5, -11)); getchar(); return 0;}", "e": 1575, "s": 1187, "text": null }, { "code": "class GFG { /* function to multiply two numbers x and y*/ static int multiply(int x, int y) { /* 0 multiplied with anything gives 0 */ if (y == 0) return 0; /* Add x one by one */ if (y > 0) return (x + multiply(x, y - 1)); /* the case where y is negative */ if (y < 0) return -multiply(x, -y); return -1; } // Driver code public static void main(String[] args) { System.out.print(\"\\n\" + multiply(5, -11)); }} // This code is contributed by Anant Agarwal.", "e": 2189, "s": 1575, "text": null }, { "code": "# Function to multiply two numbers# x and ydef multiply(x,y): # 0 multiplied with anything # gives 0 if(y == 0): return 0 # Add x one by one if(y > 0 ): return (x + multiply(x, y - 1)) # The case where y is negative if(y < 0 ): return -multiply(x, -y) # Driver codeprint(multiply(5, -11)) # This code is contributed by Anant Agarwal.", "e": 2572, "s": 2189, "text": null }, { "code": "// Multiply two integers without// using multiplication, division// and bitwise operators, and no// loopsusing System; class GFG { // function to multiply two numbers // x and y static int multiply(int x, int y) { // 0 multiplied with anything gives 0 if (y == 0) return 0; // Add x one by one if (y > 0) return (x + multiply(x, y - 1)); // the case where y is negative if (y < 0) return -multiply(x, -y); return -1; } // Driver code public static void Main() { Console.WriteLine(multiply(5, -11)); }} // This code is contributed by vt_m.", "e": 3272, "s": 2572, "text": null }, { "code": "<?php// function to multiply// two numbers x and yfunction multiply($x, $y){/* 0 multiplied withanything gives 0 */if($y == 0) return 0; /* Add x one by one */if($y > 0 ) return ($x + multiply($x, $y - 1)); /* the case wherey is negative */if($y < 0 ) return -multiply($x, -$y);} // Driver Codeecho multiply(5, -11); // This code is contributed by mits.?>", "e": 3662, "s": 3272, "text": null }, { "code": "<script> // javascript program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops /* function to multiply two numbers x and y*/function multiply( x, y){ /* 0 multiplied with anything gives 0 */ if(y == 0) return 0; /* Add x one by one */ if(y > 0 ) return (x + multiply(x, y-1)); /* the case where y is negative */ if(y < 0 ) return -multiply(x, -y);} // Driver code document.write( multiply(5, -11)); // This code is contributed by todaysgaurav </script>", "e": 4208, "s": 3662, "text": null }, { "code": null, "e": 4212, "s": 4208, "text": "-55" }, { "code": null, "e": 4289, "s": 4212, "text": "Time Complexity: O(y) where y is the second argument to function multiply()." }, { "code": null, "e": 4335, "s": 4289, "text": "Auxiliary Space: O(y) for the recursion stack" }, { "code": null, "e": 4410, "s": 4335, "text": "Another approach: The problem can also be solved using basic math property" }, { "code": null, "e": 4434, "s": 4410, "text": "(a+b)2 = a2 + b2 + 2a*b" }, { "code": null, "e": 4466, "s": 4434, "text": "⇒ a*b = ((a+b)2 – a2 – b2) / 2" }, { "code": null, "e": 4621, "s": 4466, "text": "For computing the square of numbers, we can use the power function in C++ and for dividing by 2 in the above expression we can write a recursive function." }, { "code": null, "e": 4673, "s": 4621, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 4677, "s": 4673, "text": "C++" }, { "code": null, "e": 4685, "s": 4677, "text": "Python3" }, { "code": null, "e": 4696, "s": 4685, "text": "Javascript" }, { "code": "// C++ program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops#include<bits/stdc++.h>using namespace std; // divide a number by 2 recursivelyint divideby2(int num){ if(num<2) return 0; return 1 + divideby2(num-2);} int multiply(int a,int b){ int whole_square=pow(a+b,2); int a_square=pow(a,2); int b_square=pow(b,2); int val= whole_square- a_square - b_square; int product; // for positive value of variable val if(val>=0) product = divideby2(val); // for negative value of variable val // we first compute the division by 2 for // positive val and by subtracting from // 0 we can make it negative else product = 0 - divideby2(abs(val)); return product;} // Driver codeint main(){ int a=5; int b=-11; cout << multiply(a,b); return 0;} // This code is contributed by Pushpesh raj.", "e": 5616, "s": 4696, "text": null }, { "code": "# Python3 program to Multiply two integers without# using multiplication, division and bitwise# operators, and no loops # divide a number by 2 recursivelydef divideby2(num): if(num < 2): return 0 return 1 + divideby2(num-2) def multiply(a, b): whole_square = (a + b) ** 2 a_square = pow(a, 2) b_square = pow(b, 2) val = whole_square - a_square - b_square # for positive value of variable val if(val >= 0): product = divideby2(val) # for negative value of variable val # we first compute the division by 2 for # positive val and by subtracting from # 0 we can make it negative else: product = 0 - divideby2(abs(val)) return product # Driver codea = 5b = -11print(multiply(a, b)) # This code is contributed by phasing17", "e": 6410, "s": 5616, "text": null }, { "code": "// JavaScript program to Multiply two integers without// using multiplication, division and bitwise// operators, and no loops // divide a number by 2 recursivelyfunction divideby2(num){ if(num<2) return 0; return 1 + divideby2(num-2);} function multiply(a, b){ let whole_square = Math.pow(a+b,2); let a_square = Math.pow(a,2); let b_square = Math.pow(b,2); let val = whole_square- a_square - b_square; let product; // for positive value of variable val if(val>=0) product = divideby2(val); // for negative value of variable val // we first compute the division by 2 for // positive val and by subtracting from // 0 we can make it negative else product = 0 - divideby2(Math.abs(val)); return product;} // Driver codelet a = 5;let b = -11;console.log(multiply(a,b)); // This code is contributed by phasing17", "e": 7284, "s": 6410, "text": null }, { "code": null, "e": 7288, "s": 7284, "text": "-55" }, { "code": null, "e": 7475, "s": 7288, "text": "Russian Peasant (Multiply two numbers using bitwise operators)Please write comments if you find any of the above code/algorithm incorrect, or find better ways to solve the same problem. " }, { "code": null, "e": 7488, "s": 7475, "text": "Mithun Kumar" }, { "code": null, "e": 7501, "s": 7488, "text": "SoumikMondal" }, { "code": null, "e": 7514, "s": 7501, "text": "todaysgaurav" }, { "code": null, "e": 7530, "s": 7514, "text": "subhammahato348" }, { "code": null, "e": 7537, "s": 7530, "text": "Code_r" }, { "code": null, "e": 7553, "s": 7537, "text": "pushpeshrajdx01" }, { "code": null, "e": 7563, "s": 7553, "text": "phasing17" }, { "code": null, "e": 7576, "s": 7563, "text": "Mathematical" }, { "code": null, "e": 7589, "s": 7576, "text": "Mathematical" }, { "code": null, "e": 7687, "s": 7589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7711, "s": 7687, "text": "Merge two sorted arrays" }, { "code": null, "e": 7733, "s": 7711, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 7747, "s": 7733, "text": "Prime Numbers" }, { "code": null, "e": 7784, "s": 7747, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7826, "s": 7784, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 7879, "s": 7826, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7922, "s": 7879, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7954, "s": 7922, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7995, "s": 7954, "text": "Program for Decimal to Binary Conversion" } ]
locate command in Linux with Examples
23 May, 2019 locate command in Linux is used to find the files by name. There is two most widely used file searching utilities accessible to users are called find and locate. The locate utility works better and faster than find command counterpart because instead of searching the file system when a file search is initiated, it would look through a database. This database contains bits and parts of files and their corresponding paths on your system. By default, locate command does not check whether the files found in the database still exist and it never reports files created after the most recent update of the relevant database. Syntax: locate [OPTION]... PATTERN... Exit Status: This command will exit with status 0 if any specified match found. If no match founds or a fatal error encountered, then it will exit with status 1. Options: -b, –basename : Match only the base name against the specified patterns, which is the opposite of –wholename. -c, –count : Instead of writing file names on standard output, write the number of matching entries only. -d, –database DBPATH : Replace the default database with DBPATH. DBPATH is a : (colon) separated list of database file names. If more than one –database option is specified, the resulting path is a concatenation of the separate paths. An empty database file name is replaced by the default database. A database file name – refers to the standard input. Note that a database can be read from the standard input only once. -e, –existing : Print only entries that refer to files existing at the time locate is run. -L, –follow : When checking whether files exist (if the –existing option is specified), follow trailing symbolic links. This causes bro ken symbolic links to be omitted from the output. This option is the default behavior. The opposite can be specified using –nofollow. -h, –help : Write a summary of the available options to standard output and exit successfully. -i, –ignore-case : Ignore case distinctions when matching patterns. -l, –limit, -n LIMIT : Exit successfully after finding LIMIT entries. If the –count option is specified, the resulting count is also limited to LIMIT. -m, –mmap : Ignored, but included for compatibility with BSD and GNU locate. -P, –nofollow, -H : When checking whether files exist (if the –existing option is specified), do not follow trailing symbolic links. This causes broken symbolic links to be reported like other files.This option is the opposite of –follow. This option is the opposite of –follow. -0, –null : Separate the entries on output using the ASCII NUL character instead of writing each entry on a separate line. This option is designed for interoperability with the –null option of GNU xargs. -S, –statistics : Write statistics about each read database to standard output instead of searching for files and exit successfully. -q, –quiet : Write no messages about errors encountered while reading and processing databases. -r, –regexp REGEXP : Search for a basic regexp REGEXP. No PATTERNs are allowed if this option is used, but this option can be specified multiple times. –regex : Interpret all PATTERNs as extended regexps. -s, –stdio : Ignored, for compatibility with BSD and GNU locate. -V, –version : Write information about the version and license of locate on standard output and exit successfully. -w, –wholename : Match only the whole path name against the specified patterns. This option is the default behavior. The opposite can be specified using –basename. Example 1: Search a file with specific name. $ locate sample.txt It will search for sample.txt in particular directory. Output: Example 2: Limit Search Queries to a Specific Number. $ locate "*.html" -n 20 It will show 20 results for the searching of file ending with .html. Output: Example 3. Display The Number of Matching Entries. $ locate -c [.txt]* It will count files ending with .txt. Output: Example 4: Ignore Case Sensitive Locate Outputs. This command is configured to process queries in a case sensitive manner. It means SAMPLE.TXT will show a different result than sample.txt. $ locate -i *SAMPLE.txt* Output: Example 5: Separate Output Entries Without New Line. $ locate -i -0 *sample.txt* Default separator for locate command is the newline (\\n) character. But if someone want to use a different separator like the ASCII NUL, the he/she can do so using the -0 command line option. Output: linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 May, 2019" }, { "code": null, "e": 677, "s": 53, "text": "locate command in Linux is used to find the files by name. There is two most widely used file searching utilities accessible to users are called find and locate. The locate utility works better and faster than find command counterpart because instead of searching the file system when a file search is initiated, it would look through a database. This database contains bits and parts of files and their corresponding paths on your system. By default, locate command does not check whether the files found in the database still exist and it never reports files created after the most recent update of the relevant database." }, { "code": null, "e": 685, "s": 677, "text": "Syntax:" }, { "code": null, "e": 715, "s": 685, "text": "locate [OPTION]... PATTERN..." }, { "code": null, "e": 877, "s": 715, "text": "Exit Status: This command will exit with status 0 if any specified match found. If no match founds or a fatal error encountered, then it will exit with status 1." }, { "code": null, "e": 886, "s": 877, "text": "Options:" }, { "code": null, "e": 996, "s": 886, "text": "-b, –basename : Match only the base name against the specified patterns, which is the opposite of –wholename." }, { "code": null, "e": 1102, "s": 996, "text": "-c, –count : Instead of writing file names on standard output, write the number of matching entries only." }, { "code": null, "e": 1523, "s": 1102, "text": "-d, –database DBPATH : Replace the default database with DBPATH. DBPATH is a : (colon) separated list of database file names. If more than one –database option is specified, the resulting path is a concatenation of the separate paths. An empty database file name is replaced by the default database. A database file name – refers to the standard input. Note that a database can be read from the standard input only once." }, { "code": null, "e": 1614, "s": 1523, "text": "-e, –existing : Print only entries that refer to files existing at the time locate is run." }, { "code": null, "e": 1884, "s": 1614, "text": "-L, –follow : When checking whether files exist (if the –existing option is specified), follow trailing symbolic links. This causes bro ken symbolic links to be omitted from the output. This option is the default behavior. The opposite can be specified using –nofollow." }, { "code": null, "e": 1979, "s": 1884, "text": "-h, –help : Write a summary of the available options to standard output and exit successfully." }, { "code": null, "e": 2047, "s": 1979, "text": "-i, –ignore-case : Ignore case distinctions when matching patterns." }, { "code": null, "e": 2198, "s": 2047, "text": "-l, –limit, -n LIMIT : Exit successfully after finding LIMIT entries. If the –count option is specified, the resulting count is also limited to LIMIT." }, { "code": null, "e": 2275, "s": 2198, "text": "-m, –mmap : Ignored, but included for compatibility with BSD and GNU locate." }, { "code": null, "e": 2514, "s": 2275, "text": "-P, –nofollow, -H : When checking whether files exist (if the –existing option is specified), do not follow trailing symbolic links. This causes broken symbolic links to be reported like other files.This option is the opposite of –follow." }, { "code": null, "e": 2554, "s": 2514, "text": "This option is the opposite of –follow." }, { "code": null, "e": 2758, "s": 2554, "text": "-0, –null : Separate the entries on output using the ASCII NUL character instead of writing each entry on a separate line. This option is designed for interoperability with the –null option of GNU xargs." }, { "code": null, "e": 2891, "s": 2758, "text": "-S, –statistics : Write statistics about each read database to standard output instead of searching for files and exit successfully." }, { "code": null, "e": 2987, "s": 2891, "text": "-q, –quiet : Write no messages about errors encountered while reading and processing databases." }, { "code": null, "e": 3139, "s": 2987, "text": "-r, –regexp REGEXP : Search for a basic regexp REGEXP. No PATTERNs are allowed if this option is used, but this option can be specified multiple times." }, { "code": null, "e": 3192, "s": 3139, "text": "–regex : Interpret all PATTERNs as extended regexps." }, { "code": null, "e": 3257, "s": 3192, "text": "-s, –stdio : Ignored, for compatibility with BSD and GNU locate." }, { "code": null, "e": 3372, "s": 3257, "text": "-V, –version : Write information about the version and license of locate on standard output and exit successfully." }, { "code": null, "e": 3536, "s": 3372, "text": "-w, –wholename : Match only the whole path name against the specified patterns. This option is the default behavior. The opposite can be specified using –basename." }, { "code": null, "e": 3581, "s": 3536, "text": "Example 1: Search a file with specific name." }, { "code": null, "e": 3602, "s": 3581, "text": "$ locate sample.txt " }, { "code": null, "e": 3657, "s": 3602, "text": "It will search for sample.txt in particular directory." }, { "code": null, "e": 3665, "s": 3657, "text": "Output:" }, { "code": null, "e": 3719, "s": 3665, "text": "Example 2: Limit Search Queries to a Specific Number." }, { "code": null, "e": 3743, "s": 3719, "text": "$ locate \"*.html\" -n 20" }, { "code": null, "e": 3812, "s": 3743, "text": "It will show 20 results for the searching of file ending with .html." }, { "code": null, "e": 3820, "s": 3812, "text": "Output:" }, { "code": null, "e": 3871, "s": 3820, "text": "Example 3. Display The Number of Matching Entries." }, { "code": null, "e": 3891, "s": 3871, "text": "$ locate -c [.txt]*" }, { "code": null, "e": 3929, "s": 3891, "text": "It will count files ending with .txt." }, { "code": null, "e": 3937, "s": 3929, "text": "Output:" }, { "code": null, "e": 4126, "s": 3937, "text": "Example 4: Ignore Case Sensitive Locate Outputs. This command is configured to process queries in a case sensitive manner. It means SAMPLE.TXT will show a different result than sample.txt." }, { "code": null, "e": 4151, "s": 4126, "text": "$ locate -i *SAMPLE.txt*" }, { "code": null, "e": 4159, "s": 4151, "text": "Output:" }, { "code": null, "e": 4212, "s": 4159, "text": "Example 5: Separate Output Entries Without New Line." }, { "code": null, "e": 4240, "s": 4212, "text": "$ locate -i -0 *sample.txt*" }, { "code": null, "e": 4433, "s": 4240, "text": "Default separator for locate command is the newline (\\\\n) character. But if someone want to use a different separator like the ASCII NUL, the he/she can do so using the -0 command line option." }, { "code": null, "e": 4441, "s": 4433, "text": "Output:" }, { "code": null, "e": 4455, "s": 4441, "text": "linux-command" }, { "code": null, "e": 4475, "s": 4455, "text": "Linux-misc-commands" }, { "code": null, "e": 4482, "s": 4475, "text": "Picked" }, { "code": null, "e": 4493, "s": 4482, "text": "Linux-Unix" } ]
Matplotlib.pyplot.subplot() function in Python
20 May, 2022 Prerequisites: matplotlib subplot() function adds subplot to a current figure at the specified grid position. It is similar to the subplots() function however unlike subplots() it adds one subplot at a time. So to create multiple plots you will need several lines of code with the subplot() function. Another drawback of the subplot function is that it deletes the preexisting plot on your figure. Refer to example 1. It is a wrapper of Figure.add_subplot. Syntax: subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(ax) Parameters : args: Either a 3-digit integer or three separate integers describing the position of the subplot. pos is a three-digit integer where the first, second, and third integer are nrows,ncols, index. projection : [{None, ’aitoff’, ’hammer’, ’lambert’, ’mollweide’, ’polar’, ’rectilinear’, str}, optional]. The projection-type of the subplot (Axes). The default None results in a ’rectilinear’ projection. label : [str] A label for the returned axes. **kwargs: This method also takes the keyword arguments for the returned axes base class;except for the figure argument, for e.g facecolor. Returns : An axes.SubplotBase subclass of Axes or a subclass of Axes. The returned axes base class depends on the projection used. Implementation of the function is given below: Example 1: subplot() will delete the pre-existing plot. Python3 # importing the moduleimport matplotlib.pyplot as plt # Data to display on plotx = [1, 2, 3, 4, 5]y = [1, 2, 1, 2, 1] # plot() will create new figure and will add axes object (plot) of above dataplt.plot(x, y, marker="x", color="green") # subplot() will add plot to current figure deleting existing plotplt.subplot(121) Output: We can see that the first plot got set aside by the subplot() function. subplot_gfg If you want to see the first plot comment out plt.subplot() line and you will see the following plot plot_gfg Example 2: Python3 import matplotlib.pyplot as plt# data to display on plots x = [3, 1, 3]y = [3, 2, 1]z = [1, 3, 1] # Creating figure objectplt.figure() # adding first subplotplt.subplot(121)plt.plot(x, y, color="orange", marker="*") # adding second subplotplt.subplot(122)plt.plot(z, y, color="yellow", marker="*") Output : multiple_subplots sumitgumber28 surinderdawra388 Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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 | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n20 May, 2022" }, { "code": null, "e": 80, "s": 54, "text": "Prerequisites: matplotlib" }, { "code": null, "e": 473, "s": 80, "text": "subplot() function adds subplot to a current figure at the specified grid position. It is similar to the subplots() function however unlike subplots() it adds one subplot at a time. So to create multiple plots you will need several lines of code with the subplot() function. Another drawback of the subplot function is that it deletes the preexisting plot on your figure. Refer to example 1." }, { "code": null, "e": 512, "s": 473, "text": "It is a wrapper of Figure.add_subplot." }, { "code": null, "e": 520, "s": 512, "text": "Syntax:" }, { "code": null, "e": 559, "s": 520, "text": "subplot(nrows, ncols, index, **kwargs)" }, { "code": null, "e": 583, "s": 559, "text": "subplot(pos, **kwargs) " }, { "code": null, "e": 595, "s": 583, "text": "subplot(ax)" }, { "code": null, "e": 609, "s": 595, "text": "Parameters : " }, { "code": null, "e": 708, "s": 609, "text": "args: Either a 3-digit integer or three separate integers describing the position of the subplot." }, { "code": null, "e": 804, "s": 708, "text": "pos is a three-digit integer where the first, second, and third integer are nrows,ncols, index." }, { "code": null, "e": 1009, "s": 804, "text": "projection : [{None, ’aitoff’, ’hammer’, ’lambert’, ’mollweide’, ’polar’, ’rectilinear’, str}, optional]. The projection-type of the subplot (Axes). The default None results in a ’rectilinear’ projection." }, { "code": null, "e": 1054, "s": 1009, "text": "label : [str] A label for the returned axes." }, { "code": null, "e": 1193, "s": 1054, "text": "**kwargs: This method also takes the keyword arguments for the returned axes base class;except for the figure argument, for e.g facecolor." }, { "code": null, "e": 1325, "s": 1193, "text": "Returns : An axes.SubplotBase subclass of Axes or a subclass of Axes. The returned axes base class depends on the projection used." }, { "code": null, "e": 1372, "s": 1325, "text": "Implementation of the function is given below:" }, { "code": null, "e": 1428, "s": 1372, "text": "Example 1: subplot() will delete the pre-existing plot." }, { "code": null, "e": 1436, "s": 1428, "text": "Python3" }, { "code": "# importing the moduleimport matplotlib.pyplot as plt # Data to display on plotx = [1, 2, 3, 4, 5]y = [1, 2, 1, 2, 1] # plot() will create new figure and will add axes object (plot) of above dataplt.plot(x, y, marker=\"x\", color=\"green\") # subplot() will add plot to current figure deleting existing plotplt.subplot(121)", "e": 1756, "s": 1436, "text": null }, { "code": null, "e": 1837, "s": 1756, "text": "Output: We can see that the first plot got set aside by the subplot() function. " }, { "code": null, "e": 1849, "s": 1837, "text": "subplot_gfg" }, { "code": null, "e": 1950, "s": 1849, "text": "If you want to see the first plot comment out plt.subplot() line and you will see the following plot" }, { "code": null, "e": 1959, "s": 1950, "text": "plot_gfg" }, { "code": null, "e": 1970, "s": 1959, "text": "Example 2:" }, { "code": null, "e": 1978, "s": 1970, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt# data to display on plots x = [3, 1, 3]y = [3, 2, 1]z = [1, 3, 1] # Creating figure objectplt.figure() # adding first subplotplt.subplot(121)plt.plot(x, y, color=\"orange\", marker=\"*\") # adding second subplotplt.subplot(122)plt.plot(z, y, color=\"yellow\", marker=\"*\")", "e": 2276, "s": 1978, "text": null }, { "code": null, "e": 2285, "s": 2276, "text": "Output :" }, { "code": null, "e": 2303, "s": 2285, "text": "multiple_subplots" }, { "code": null, "e": 2317, "s": 2303, "text": "sumitgumber28" }, { "code": null, "e": 2334, "s": 2317, "text": "surinderdawra388" }, { "code": null, "e": 2358, "s": 2334, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 2376, "s": 2358, "text": "Python-matplotlib" }, { "code": null, "e": 2383, "s": 2376, "text": "Python" }, { "code": null, "e": 2481, "s": 2383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2513, "s": 2481, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2540, "s": 2513, "text": "Python Classes and Objects" }, { "code": null, "e": 2561, "s": 2540, "text": "Python OOPs Concepts" }, { "code": null, "e": 2584, "s": 2561, "text": "Introduction To PYTHON" }, { "code": null, "e": 2615, "s": 2584, "text": "Python | os.path.join() method" }, { "code": null, "e": 2671, "s": 2615, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2713, "s": 2671, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2755, "s": 2713, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2794, "s": 2755, "text": "Python | Get unique values from a list" } ]
How to use Scrapy to parse PDF pages online?
18 Jul, 2021 Prerequisite: Scrapy, PyPDF2, URLLIB In this article, we will be using Scrapy to parse any online PDF without downloading it onto the system. To do that we have to use the PDF parser or editor library of Python know as PyPDF2. PyPDF2 is a pdf parsing library of python, which provides various methods like reader methods, writer methods, and many more which are used to modify, edit and parse the pdfs either online or offline. All the constructors of PyPDF2 classes require a stream of the PDF file. Now, since we can only achieve the URL of the pdf file, so to convert that URL to a file stream or simply open that URL we will require the use of urllib module of Python which can be used to call an urlopen() method on the request object returned by spider. Example 1: We will be using some basic operations like extracting the page numbers and checking whether the file is encrypted or not. For this, we will parse with URL and find get the response then we will check the file pages and encrypted using numPages and isEncrypted. Scrapy spider crawls the web page to find the pdf file online which is to be scrapped, then the URL of that pdf file is obtained from another variable URL, then the urllib is used to open the URL file and create a reader object of PyPDF2 lib by passing the stream link of the URL to the parameter of the Object’s constructor. Python3 import ioimport PyPDF2import urllib.requestimport scrapyfrom scrapy.item import Item class ParserspiderSpider(scrapy.Spider): name = 'parserspider' # URL of the pdf file . This is operating system # book solution of author Albert Silberschatz start_urls = ['https://codex.cs.yale.edu/avi/\ os-book/OS9/practice-exer-dir/index.html'] # default parse method def parse(self, response): # getting the list of URL of the pdf pdfs = response.xpath('//tr[3]/td[2]/a/@href') # Extracting the URL URL = response.urljoin(pdfs[0].extract()) # calling urllib to create a reader of the pdf url File = urllib.request.urlopen(URL) reader = PyPDF2.pdf.PdfFileReader(io.BytesIO(File.read())) # accessing some descriptions of the pdf file. print("This is the number of pages"+str(reader.numPages)) print("Is file Encrypted?"+str(reader.isEncrypted)) Output: First output the pages of pdf and whether it is encrypted or not Example 2: In this example, we will be extracting the data of the pdf file (parsing), then the PyPDF2 object is used to make the required changes to the pdf file through the various methods mentioned above. We will print the extracted data to the terminal. Python3 import ioimport PyPDF2import urllib.requestimport scrapyfrom scrapy.item import Item class ParserspiderSpider(scrapy.Spider): name = 'parserspider' # URL of the pdf file. start_urls = ['https://codex.cs.yale.edu/avi\ /os-book/OS9/practice-exer-dir/index.html'] # default parse method def parse(self, response): # getting the list of URL of the pdf pdfs = response.xpath('//tr[3]/td[2]/a/@href') # Extracting the URL URL = response.urljoin(pdfs[0].extract()) # calling urllib to create a reader of the pdf url File = urllib.request.urlopen(URL) reader = PyPDF2.pdf.PdfFileReader(io.BytesIO(File.read())) # creating data data="" for datas in reader.pages: data += datas.extractText() print(data) Output: Parsed Pdf Picked Python-Scrapy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 65, "s": 28, "text": "Prerequisite: Scrapy, PyPDF2, URLLIB" }, { "code": null, "e": 256, "s": 65, "text": "In this article, we will be using Scrapy to parse any online PDF without downloading it onto the system. To do that we have to use the PDF parser or editor library of Python know as PyPDF2. " }, { "code": null, "e": 457, "s": 256, "text": "PyPDF2 is a pdf parsing library of python, which provides various methods like reader methods, writer methods, and many more which are used to modify, edit and parse the pdfs either online or offline." }, { "code": null, "e": 789, "s": 457, "text": "All the constructors of PyPDF2 classes require a stream of the PDF file. Now, since we can only achieve the URL of the pdf file, so to convert that URL to a file stream or simply open that URL we will require the use of urllib module of Python which can be used to call an urlopen() method on the request object returned by spider." }, { "code": null, "e": 1062, "s": 789, "text": "Example 1: We will be using some basic operations like extracting the page numbers and checking whether the file is encrypted or not. For this, we will parse with URL and find get the response then we will check the file pages and encrypted using numPages and isEncrypted." }, { "code": null, "e": 1388, "s": 1062, "text": "Scrapy spider crawls the web page to find the pdf file online which is to be scrapped, then the URL of that pdf file is obtained from another variable URL, then the urllib is used to open the URL file and create a reader object of PyPDF2 lib by passing the stream link of the URL to the parameter of the Object’s constructor." }, { "code": null, "e": 1396, "s": 1388, "text": "Python3" }, { "code": "import ioimport PyPDF2import urllib.requestimport scrapyfrom scrapy.item import Item class ParserspiderSpider(scrapy.Spider): name = 'parserspider' # URL of the pdf file . This is operating system # book solution of author Albert Silberschatz start_urls = ['https://codex.cs.yale.edu/avi/\\ os-book/OS9/practice-exer-dir/index.html'] # default parse method def parse(self, response): # getting the list of URL of the pdf pdfs = response.xpath('//tr[3]/td[2]/a/@href') # Extracting the URL URL = response.urljoin(pdfs[0].extract()) # calling urllib to create a reader of the pdf url File = urllib.request.urlopen(URL) reader = PyPDF2.pdf.PdfFileReader(io.BytesIO(File.read())) # accessing some descriptions of the pdf file. print(\"This is the number of pages\"+str(reader.numPages)) print(\"Is file Encrypted?\"+str(reader.isEncrypted))", "e": 2384, "s": 1396, "text": null }, { "code": null, "e": 2392, "s": 2384, "text": "Output:" }, { "code": null, "e": 2457, "s": 2392, "text": "First output the pages of pdf and whether it is encrypted or not" }, { "code": null, "e": 2714, "s": 2457, "text": "Example 2: In this example, we will be extracting the data of the pdf file (parsing), then the PyPDF2 object is used to make the required changes to the pdf file through the various methods mentioned above. We will print the extracted data to the terminal." }, { "code": null, "e": 2722, "s": 2714, "text": "Python3" }, { "code": "import ioimport PyPDF2import urllib.requestimport scrapyfrom scrapy.item import Item class ParserspiderSpider(scrapy.Spider): name = 'parserspider' # URL of the pdf file. start_urls = ['https://codex.cs.yale.edu/avi\\ /os-book/OS9/practice-exer-dir/index.html'] # default parse method def parse(self, response): # getting the list of URL of the pdf pdfs = response.xpath('//tr[3]/td[2]/a/@href') # Extracting the URL URL = response.urljoin(pdfs[0].extract()) # calling urllib to create a reader of the pdf url File = urllib.request.urlopen(URL) reader = PyPDF2.pdf.PdfFileReader(io.BytesIO(File.read())) # creating data data=\"\" for datas in reader.pages: data += datas.extractText() print(data)", "e": 3551, "s": 2722, "text": null }, { "code": null, "e": 3559, "s": 3551, "text": "Output:" }, { "code": null, "e": 3570, "s": 3559, "text": "Parsed Pdf" }, { "code": null, "e": 3577, "s": 3570, "text": "Picked" }, { "code": null, "e": 3591, "s": 3577, "text": "Python-Scrapy" }, { "code": null, "e": 3598, "s": 3591, "text": "Python" } ]
How to get the duration of audio in Python?
24 Feb, 2021 It is possible to find the duration of the audio files using Python language which is rich in the use of its libraries. The use of some libraries like mutagen, wave, audioread, etc. is not only limited to extract the length/duration of the audio files but comes with much more functionality. Source Audio File: Now let us see, how we can get the duration of any audio file using python: Mutagen is a Python module to handle audio metadata. It supports various formats of audio files like wavpack, mp3, Ogg, etc. Below are the steps to use it for computing the duration of the audio files: Step 1: Install Mutagen Since Mutagen is an external python library, hence first it needs to be installed using the pip command as follows: pip install mutagen Step 2: Import Mutagen Once installed, its need to be imported into our script using the following command, import mutagen In our program, we are going to use some inbuilt functions of the Mutagen library, Let’s explore them a bit to get a better understanding of the Source Code: 1) WAVE() Syntax: WAVE(file thing/filename) Use: It simply creates a WAVE object of the filename being provided as a parameter. Example: voice = WAVE(“sample.wav”) 2) info Syntax: variable.info Use: It fetches the metadata of the audio file whose WAVE object has been created. Example: voice_info = voice.info 3) length Syntax: variable.length Use: It returns audio length in seconds. The value returned is in float(by default). Example: voice_length = voice_info.length Below is the actual Python Script that records the duration/length of any audio file: Python3 import mutagenfrom mutagen.wave import WAVE # function to convert the information into # some readable formatdef audio_duration(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # returns the duration # Create a WAVE object# Specify the directory address of your wavpack file# "alarm.wav" is the name of the audiofileaudio = WAVE("alarm.wav") # contains all the metadata about the wavpack fileaudio_info = audio.infolength = int(audio_info.length)hours, mins, seconds = audio_duration(length)print('Total Duration: {}:{}:{}'.format(hours, mins, seconds)) Output: Total Duration: 0:0:2 Audioread is cross-library audio decoding for Python. It decodes audio files using whichever backend is available. Below are the steps to use it for computing the duration of the audio files: Step 1: Install audioread Since audioread is an external python library, hence first it needs to be installed using the pip command as follows: pip install audioread Step 2: Import audioread Once installed, its need to be imported into our script using the following command, import audioread In our program, we are going to use some inbuilt functions of audioread library, Let’s explore them a bit to get a better understanding of the Source Code: 1) audio_open() Syntax: audioread.audio_open(filename) Use: It simply opens an audio file using a library available on the system Example: with audioread.audio_open(‘example.wav’) as ex: #statement 1...statement n 2) duration Syntax: fileobject.duration Use: It returns the length of the audio in seconds (a float by default). Example: variable= fptr.duration Below is the actual Python Script that records the duration/length of any audio file: Python3 # METHOD 2import audioread # function to convert the information into # some readable formatdef duration_detector(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # alarm.wav is the name of the audio file# f is the fileobject being createdwith audioread.audio_open('alarm.wav') as f: # totalsec contains the length in float totalsec = f.duration hours, mins, seconds = duration_detector(int(totalsec)) print('Total Duration: {}:{}:{}'.format(hours, mins, seconds)) Output: Total Duration: 0:0:2 SciPy has many modules, classes, and functions available to read data from and write data to a variety of file formats like Wav sound files, MATLAB files, etc. Below are the steps to use it for computing the duration of the audio files: Step 1: Install Scipy Since Scipy is an external python library, hence first it needs to be installed using the pip command as follows: pip install scipy Step 2: Import Scipy Once installed, its need to be imported into our script using the following command, import scipy from scipy.io import wavfile In our program, we are going to use some inbuilt functions of the Scipy library, Let’s explore them a bit to get a better understanding of the Source Code: 1) scipy.io.wavfile.read() Syntax: scipy.io.wavfile.read(filename) Use: It returns the sample rate (in samples/sec) and data from a WAV file. The file can be an open file or a filename. The returned sample rate is a Python integer. The data is returned as a NumPy array with a data-type determined from the file. Example: variable1,variable2 = scipy.io.wavfile.read(‘example.wav’) Below is the actual Python Script that records the duration/length of any audio file: Python3 # Method 3import scipyfrom scipy.io import wavfile # function to convert the information into # some readable formatdef output_duration(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # sample_rate holds the sample rate of the wav file# in (sample/sec) format# data is the numpy array that consists# of actual data read from the wav filesample_rate, data = wavfile.read('alarm.wav') len_data = len(data) # holds length of the numpy array t = len_data / sample_rate # returns duration but in floats hours, mins, seconds = output_duration(int(t))print('Total Duration: {}:{}:{}'.format(hours, mins, seconds)) Output: Total Duration: 0:0:2 Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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 | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 320, "s": 28, "text": "It is possible to find the duration of the audio files using Python language which is rich in the use of its libraries. The use of some libraries like mutagen, wave, audioread, etc. is not only limited to extract the length/duration of the audio files but comes with much more functionality." }, { "code": null, "e": 340, "s": 320, "text": "Source Audio File: " }, { "code": null, "e": 416, "s": 340, "text": "Now let us see, how we can get the duration of any audio file using python:" }, { "code": null, "e": 618, "s": 416, "text": "Mutagen is a Python module to handle audio metadata. It supports various formats of audio files like wavpack, mp3, Ogg, etc. Below are the steps to use it for computing the duration of the audio files:" }, { "code": null, "e": 643, "s": 618, "text": "Step 1: Install Mutagen " }, { "code": null, "e": 759, "s": 643, "text": "Since Mutagen is an external python library, hence first it needs to be installed using the pip command as follows:" }, { "code": null, "e": 779, "s": 759, "text": "pip install mutagen" }, { "code": null, "e": 802, "s": 779, "text": "Step 2: Import Mutagen" }, { "code": null, "e": 887, "s": 802, "text": "Once installed, its need to be imported into our script using the following command," }, { "code": null, "e": 902, "s": 887, "text": "import mutagen" }, { "code": null, "e": 1060, "s": 902, "text": "In our program, we are going to use some inbuilt functions of the Mutagen library, Let’s explore them a bit to get a better understanding of the Source Code:" }, { "code": null, "e": 1070, "s": 1060, "text": "1) WAVE()" }, { "code": null, "e": 1104, "s": 1070, "text": "Syntax: WAVE(file thing/filename)" }, { "code": null, "e": 1188, "s": 1104, "text": "Use: It simply creates a WAVE object of the filename being provided as a parameter." }, { "code": null, "e": 1224, "s": 1188, "text": "Example: voice = WAVE(“sample.wav”)" }, { "code": null, "e": 1232, "s": 1224, "text": "2) info" }, { "code": null, "e": 1254, "s": 1232, "text": "Syntax: variable.info" }, { "code": null, "e": 1337, "s": 1254, "text": "Use: It fetches the metadata of the audio file whose WAVE object has been created." }, { "code": null, "e": 1370, "s": 1337, "text": "Example: voice_info = voice.info" }, { "code": null, "e": 1380, "s": 1370, "text": "3) length" }, { "code": null, "e": 1404, "s": 1380, "text": "Syntax: variable.length" }, { "code": null, "e": 1489, "s": 1404, "text": "Use: It returns audio length in seconds. The value returned is in float(by default)." }, { "code": null, "e": 1531, "s": 1489, "text": "Example: voice_length = voice_info.length" }, { "code": null, "e": 1617, "s": 1531, "text": "Below is the actual Python Script that records the duration/length of any audio file:" }, { "code": null, "e": 1625, "s": 1617, "text": "Python3" }, { "code": "import mutagenfrom mutagen.wave import WAVE # function to convert the information into # some readable formatdef audio_duration(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # returns the duration # Create a WAVE object# Specify the directory address of your wavpack file# \"alarm.wav\" is the name of the audiofileaudio = WAVE(\"alarm.wav\") # contains all the metadata about the wavpack fileaudio_info = audio.infolength = int(audio_info.length)hours, mins, seconds = audio_duration(length)print('Total Duration: {}:{}:{}'.format(hours, mins, seconds))", "e": 2349, "s": 1625, "text": null }, { "code": null, "e": 2358, "s": 2349, "text": "Output: " }, { "code": null, "e": 2380, "s": 2358, "text": "Total Duration: 0:0:2" }, { "code": null, "e": 2573, "s": 2380, "text": "Audioread is cross-library audio decoding for Python. It decodes audio files using whichever backend is available. Below are the steps to use it for computing the duration of the audio files: " }, { "code": null, "e": 2599, "s": 2573, "text": "Step 1: Install audioread" }, { "code": null, "e": 2717, "s": 2599, "text": "Since audioread is an external python library, hence first it needs to be installed using the pip command as follows:" }, { "code": null, "e": 2739, "s": 2717, "text": "pip install audioread" }, { "code": null, "e": 2764, "s": 2739, "text": "Step 2: Import audioread" }, { "code": null, "e": 2849, "s": 2764, "text": "Once installed, its need to be imported into our script using the following command," }, { "code": null, "e": 2866, "s": 2849, "text": "import audioread" }, { "code": null, "e": 3022, "s": 2866, "text": "In our program, we are going to use some inbuilt functions of audioread library, Let’s explore them a bit to get a better understanding of the Source Code:" }, { "code": null, "e": 3038, "s": 3022, "text": "1) audio_open()" }, { "code": null, "e": 3077, "s": 3038, "text": "Syntax: audioread.audio_open(filename)" }, { "code": null, "e": 3152, "s": 3077, "text": "Use: It simply opens an audio file using a library available on the system" }, { "code": null, "e": 3210, "s": 3152, "text": "Example: with audioread.audio_open(‘example.wav’) as ex: " }, { "code": null, "e": 3266, "s": 3210, "text": " #statement 1...statement n" }, { "code": null, "e": 3278, "s": 3266, "text": "2) duration" }, { "code": null, "e": 3306, "s": 3278, "text": "Syntax: fileobject.duration" }, { "code": null, "e": 3379, "s": 3306, "text": "Use: It returns the length of the audio in seconds (a float by default)." }, { "code": null, "e": 3412, "s": 3379, "text": "Example: variable= fptr.duration" }, { "code": null, "e": 3498, "s": 3412, "text": "Below is the actual Python Script that records the duration/length of any audio file:" }, { "code": null, "e": 3506, "s": 3498, "text": "Python3" }, { "code": "# METHOD 2import audioread # function to convert the information into # some readable formatdef duration_detector(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # alarm.wav is the name of the audio file# f is the fileobject being createdwith audioread.audio_open('alarm.wav') as f: # totalsec contains the length in float totalsec = f.duration hours, mins, seconds = duration_detector(int(totalsec)) print('Total Duration: {}:{}:{}'.format(hours, mins, seconds))", "e": 4157, "s": 3506, "text": null }, { "code": null, "e": 4166, "s": 4157, "text": "Output: " }, { "code": null, "e": 4188, "s": 4166, "text": "Total Duration: 0:0:2" }, { "code": null, "e": 4425, "s": 4188, "text": "SciPy has many modules, classes, and functions available to read data from and write data to a variety of file formats like Wav sound files, MATLAB files, etc. Below are the steps to use it for computing the duration of the audio files:" }, { "code": null, "e": 4447, "s": 4425, "text": "Step 1: Install Scipy" }, { "code": null, "e": 4561, "s": 4447, "text": "Since Scipy is an external python library, hence first it needs to be installed using the pip command as follows:" }, { "code": null, "e": 4579, "s": 4561, "text": "pip install scipy" }, { "code": null, "e": 4600, "s": 4579, "text": "Step 2: Import Scipy" }, { "code": null, "e": 4685, "s": 4600, "text": "Once installed, its need to be imported into our script using the following command," }, { "code": null, "e": 4727, "s": 4685, "text": "import scipy\nfrom scipy.io import wavfile" }, { "code": null, "e": 4883, "s": 4727, "text": "In our program, we are going to use some inbuilt functions of the Scipy library, Let’s explore them a bit to get a better understanding of the Source Code:" }, { "code": null, "e": 4910, "s": 4883, "text": "1) scipy.io.wavfile.read()" }, { "code": null, "e": 4950, "s": 4910, "text": "Syntax: scipy.io.wavfile.read(filename)" }, { "code": null, "e": 5196, "s": 4950, "text": "Use: It returns the sample rate (in samples/sec) and data from a WAV file. The file can be an open file or a filename. The returned sample rate is a Python integer. The data is returned as a NumPy array with a data-type determined from the file." }, { "code": null, "e": 5264, "s": 5196, "text": "Example: variable1,variable2 = scipy.io.wavfile.read(‘example.wav’)" }, { "code": null, "e": 5350, "s": 5264, "text": "Below is the actual Python Script that records the duration/length of any audio file:" }, { "code": null, "e": 5358, "s": 5350, "text": "Python3" }, { "code": "# Method 3import scipyfrom scipy.io import wavfile # function to convert the information into # some readable formatdef output_duration(length): hours = length // 3600 # calculate in hours length %= 3600 mins = length // 60 # calculate in minutes length %= 60 seconds = length # calculate in seconds return hours, mins, seconds # sample_rate holds the sample rate of the wav file# in (sample/sec) format# data is the numpy array that consists# of actual data read from the wav filesample_rate, data = wavfile.read('alarm.wav') len_data = len(data) # holds length of the numpy array t = len_data / sample_rate # returns duration but in floats hours, mins, seconds = output_duration(int(t))print('Total Duration: {}:{}:{}'.format(hours, mins, seconds))", "e": 6139, "s": 5358, "text": null }, { "code": null, "e": 6147, "s": 6139, "text": "Output:" }, { "code": null, "e": 6169, "s": 6147, "text": "Total Duration: 0:0:2" }, { "code": null, "e": 6176, "s": 6169, "text": "Picked" }, { "code": null, "e": 6191, "s": 6176, "text": "python-utility" }, { "code": null, "e": 6198, "s": 6191, "text": "Python" }, { "code": null, "e": 6296, "s": 6198, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6328, "s": 6296, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6355, "s": 6328, "text": "Python Classes and Objects" }, { "code": null, "e": 6376, "s": 6355, "text": "Python OOPs Concepts" }, { "code": null, "e": 6399, "s": 6376, "text": "Introduction To PYTHON" }, { "code": null, "e": 6430, "s": 6399, "text": "Python | os.path.join() method" }, { "code": null, "e": 6486, "s": 6430, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6528, "s": 6486, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6570, "s": 6528, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6609, "s": 6570, "text": "Python | Get unique values from a list" } ]
SQRT() Function in SQL Server
30 Dec, 2020 SQRT() function :This function in SQL Server is used to return the square root of a specified positive number. For example, if the specified number is 81, this function will return 9. Features : This function is used to find the square root of a given number. This function accepts only positive numbers. This function also accepts fraction numbers. This function always returns positive number. This function use the formula ”(a)1/2 = Returned value“, where a is the specified number. Syntax : SQRT(number) Parameter :This method accepts a parameter as given below : number : Specified positive number whose square root is going to be returned. Returns :It returns the square root of a specified positive number. Example-1 :Getting the square root of the specified number 4. SELECT SQRT(4); Output : 2.0 Example-2 :Getting the square root of the specified number 0. SELECT SQRT(0); Output : 0.0 Example-3 :Using SQRT() function with a variable and getting the square root of the specified number 1. DECLARE @Parameter_Value INT; SET @Parameter_Value = 1; SELECT SQRT(@Parameter_Value); Output : 1.0 Example-4 :Getting the square root of 16 which is the result of “64/4”. SELECT SQRT(64/4); Output : 4.0 Example-5 :Using SQRT() function with a variable and getting the square root of float value “4.7”. DECLARE @Parameter_Value FLOAT; SET @Parameter_Value = 4.7; SELECT SQRT(@Parameter_Value); Output : 2.16794833886788 Application :This function is used to return the square root of a specified positive number. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS Window functions in SQL SQL Correlated Subqueries
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2020" }, { "code": null, "e": 212, "s": 28, "text": "SQRT() function :This function in SQL Server is used to return the square root of a specified positive number. For example, if the specified number is 81, this function will return 9." }, { "code": null, "e": 223, "s": 212, "text": "Features :" }, { "code": null, "e": 288, "s": 223, "text": "This function is used to find the square root of a given number." }, { "code": null, "e": 333, "s": 288, "text": "This function accepts only positive numbers." }, { "code": null, "e": 378, "s": 333, "text": "This function also accepts fraction numbers." }, { "code": null, "e": 424, "s": 378, "text": "This function always returns positive number." }, { "code": null, "e": 514, "s": 424, "text": "This function use the formula ”(a)1/2 = Returned value“, where a is the specified number." }, { "code": null, "e": 523, "s": 514, "text": "Syntax :" }, { "code": null, "e": 536, "s": 523, "text": "SQRT(number)" }, { "code": null, "e": 596, "s": 536, "text": "Parameter :This method accepts a parameter as given below :" }, { "code": null, "e": 674, "s": 596, "text": "number : Specified positive number whose square root is going to be returned." }, { "code": null, "e": 742, "s": 674, "text": "Returns :It returns the square root of a specified positive number." }, { "code": null, "e": 804, "s": 742, "text": "Example-1 :Getting the square root of the specified number 4." }, { "code": null, "e": 820, "s": 804, "text": "SELECT SQRT(4);" }, { "code": null, "e": 829, "s": 820, "text": "Output :" }, { "code": null, "e": 833, "s": 829, "text": "2.0" }, { "code": null, "e": 895, "s": 833, "text": "Example-2 :Getting the square root of the specified number 0." }, { "code": null, "e": 911, "s": 895, "text": "SELECT SQRT(0);" }, { "code": null, "e": 920, "s": 911, "text": "Output :" }, { "code": null, "e": 924, "s": 920, "text": "0.0" }, { "code": null, "e": 1028, "s": 924, "text": "Example-3 :Using SQRT() function with a variable and getting the square root of the specified number 1." }, { "code": null, "e": 1115, "s": 1028, "text": "DECLARE @Parameter_Value INT;\nSET @Parameter_Value = 1;\nSELECT SQRT(@Parameter_Value);" }, { "code": null, "e": 1124, "s": 1115, "text": "Output :" }, { "code": null, "e": 1128, "s": 1124, "text": "1.0" }, { "code": null, "e": 1200, "s": 1128, "text": "Example-4 :Getting the square root of 16 which is the result of “64/4”." }, { "code": null, "e": 1219, "s": 1200, "text": "SELECT SQRT(64/4);" }, { "code": null, "e": 1228, "s": 1219, "text": "Output :" }, { "code": null, "e": 1232, "s": 1228, "text": "4.0" }, { "code": null, "e": 1331, "s": 1232, "text": "Example-5 :Using SQRT() function with a variable and getting the square root of float value “4.7”." }, { "code": null, "e": 1423, "s": 1331, "text": "DECLARE @Parameter_Value FLOAT;\nSET @Parameter_Value = 4.7;\nSELECT SQRT(@Parameter_Value);\n" }, { "code": null, "e": 1432, "s": 1423, "text": "Output :" }, { "code": null, "e": 1449, "s": 1432, "text": "2.16794833886788" }, { "code": null, "e": 1542, "s": 1449, "text": "Application :This function is used to return the square root of a specified positive number." }, { "code": null, "e": 1551, "s": 1542, "text": "DBMS-SQL" }, { "code": null, "e": 1562, "s": 1551, "text": "SQL-Server" }, { "code": null, "e": 1566, "s": 1562, "text": "SQL" }, { "code": null, "e": 1570, "s": 1566, "text": "SQL" }, { "code": null, "e": 1668, "s": 1570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1679, "s": 1668, "text": "CTE in SQL" }, { "code": null, "e": 1745, "s": 1679, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1769, "s": 1745, "text": "SQL Interview Questions" }, { "code": null, "e": 1781, "s": 1769, "text": "SQL | Views" }, { "code": null, "e": 1826, "s": 1781, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1859, "s": 1826, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1891, "s": 1859, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1930, "s": 1891, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 1954, "s": 1930, "text": "Window functions in SQL" } ]
Java Program to Crop Image Using BufferedImage Class
30 Jul, 2021 In the Java programming language, we need some classes to crop an image. So these classes are as follows: 1. To read and write an image file we have to import the File class. This class represents file and directory path names in general. import java.io.File 2. To handle errors we use the IOException class. import java.io.IOException 3. To hold the image we create the BufferedImage object for that we use BufferedImage class. This object is used to store an image in RAM. import java.awt.image.BufferedImage 4. To perform the image read-write operation we will import the ImageIO class. This class has static methods to read and write an image. import javax.imageio.ImageIO Approach: Change dimensions of the imageUsing some in-built methods of BufferedImage class and Color c Change dimensions of the image Using some in-built methods of BufferedImage class and Color c Example: Java // Java Program to Crop Image Using BufferedImage Class // Importing required packagesimport java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Reading original image from local path by // creating an object of BufferedImage class BufferedImage originalImg = ImageIO.read( new File("D:/test/Image.jpeg")); // Fetching and printing alongside the // dimensions of original image using getWidth() // and getHeight() methods System.out.println("Original Image Dimension: " + originalImg.getWidth() + "x" + originalImg.getHeight()); // Creating a subimage of given dimensions BufferedImage SubImg = originalImg.getSubimage(50, 50, 50, 50); // Printing Dimensions of new image created System.out.println("Cropped Image Dimension: " + SubImg.getWidth() + "x" + SubImg.getHeight()); // Creating new file for cropped image by // creating an object of File class File outputfile = new File("D:/test/ImageCropped.jpeg"); // Writing image in new file created ImageIO.write(SubImg, "jpg", outputfile); // Display message on console representing // proper execution of program System.out.println( "Cropped Image created successfully"); } // Catch block to handle the exceptions catch (IOException e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } }} Output: Cropped Image created successfully Also, after executing the program console will show an executed message and a new cropped image will be created at the path entered which is shown below: gabaa406 gulshankumarar231 Image-Processing 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": "\n30 Jul, 2021" }, { "code": null, "e": 134, "s": 28, "text": "In the Java programming language, we need some classes to crop an image. So these classes are as follows:" }, { "code": null, "e": 267, "s": 134, "text": "1. To read and write an image file we have to import the File class. This class represents file and directory path names in general." }, { "code": null, "e": 287, "s": 267, "text": "import java.io.File" }, { "code": null, "e": 337, "s": 287, "text": "2. To handle errors we use the IOException class." }, { "code": null, "e": 364, "s": 337, "text": "import java.io.IOException" }, { "code": null, "e": 503, "s": 364, "text": "3. To hold the image we create the BufferedImage object for that we use BufferedImage class. This object is used to store an image in RAM." }, { "code": null, "e": 539, "s": 503, "text": "import java.awt.image.BufferedImage" }, { "code": null, "e": 676, "s": 539, "text": "4. To perform the image read-write operation we will import the ImageIO class. This class has static methods to read and write an image." }, { "code": null, "e": 705, "s": 676, "text": "import javax.imageio.ImageIO" }, { "code": null, "e": 715, "s": 705, "text": "Approach:" }, { "code": null, "e": 808, "s": 715, "text": "Change dimensions of the imageUsing some in-built methods of BufferedImage class and Color c" }, { "code": null, "e": 839, "s": 808, "text": "Change dimensions of the image" }, { "code": null, "e": 902, "s": 839, "text": "Using some in-built methods of BufferedImage class and Color c" }, { "code": null, "e": 911, "s": 902, "text": "Example:" }, { "code": null, "e": 916, "s": 911, "text": "Java" }, { "code": "// Java Program to Crop Image Using BufferedImage Class // Importing required packagesimport java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Reading original image from local path by // creating an object of BufferedImage class BufferedImage originalImg = ImageIO.read( new File(\"D:/test/Image.jpeg\")); // Fetching and printing alongside the // dimensions of original image using getWidth() // and getHeight() methods System.out.println(\"Original Image Dimension: \" + originalImg.getWidth() + \"x\" + originalImg.getHeight()); // Creating a subimage of given dimensions BufferedImage SubImg = originalImg.getSubimage(50, 50, 50, 50); // Printing Dimensions of new image created System.out.println(\"Cropped Image Dimension: \" + SubImg.getWidth() + \"x\" + SubImg.getHeight()); // Creating new file for cropped image by // creating an object of File class File outputfile = new File(\"D:/test/ImageCropped.jpeg\"); // Writing image in new file created ImageIO.write(SubImg, \"jpg\", outputfile); // Display message on console representing // proper execution of program System.out.println( \"Cropped Image created successfully\"); } // Catch block to handle the exceptions catch (IOException e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } }}", "e": 2922, "s": 916, "text": null }, { "code": null, "e": 2931, "s": 2922, "text": "Output: " }, { "code": null, "e": 2966, "s": 2931, "text": "Cropped Image created successfully" }, { "code": null, "e": 3121, "s": 2966, "text": "Also, after executing the program console will show an executed message and a new cropped image will be created at the path entered which is shown below: " }, { "code": null, "e": 3132, "s": 3123, "text": "gabaa406" }, { "code": null, "e": 3150, "s": 3132, "text": "gulshankumarar231" }, { "code": null, "e": 3167, "s": 3150, "text": "Image-Processing" }, { "code": null, "e": 3172, "s": 3167, "text": "Java" }, { "code": null, "e": 3186, "s": 3172, "text": "Java Programs" }, { "code": null, "e": 3191, "s": 3186, "text": "Java" } ]
What does “dereferencing” a pointer mean in C/C++?
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers. int main() { int a = 7, b ; int *p; // Un-initialized Pointer p = &a; // Stores address of a in ptr b = *p; // Put Value at ptr in b } Here, address in p is basically address of a variable.
[ { "code": null, "e": 1457, "s": 1187, "text": "Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers." }, { "code": null, "e": 1604, "s": 1457, "text": "int main() {\n int a = 7, b ;\n int *p; // Un-initialized Pointer\n p = &a; // Stores address of a in ptr\n b = *p; // Put Value at ptr in b\n}" }, { "code": null, "e": 1659, "s": 1604, "text": "Here, address in p is basically address of a variable." } ]
Merge Two Balanced Binary Search Trees
17 Jun, 2022 You are given two balanced binary search trees e.g., AVL or Red-Black Tree. Write a function that merges the two given balanced BSTs into a balanced binary search tree. Let there be m elements in the first tree and n elements in the other tree. Your merge function should take O(m+n) time.In the following solutions, it is assumed that the sizes of trees are also given as input. If the size is not given, then we can get the size by traversing the tree (See this). Method 1 (Insert elements of the first tree to second): Take all elements of first BST one by one, and insert them into the second BST. Inserting an element to a self balancing BST takes Logn time (See this) where n is size of the BST. So time complexity of this method is Log(n) + Log(n+1) ... Log(m+n-1). The value of this expression will be between mLogn and mLog(m+n-1). As an optimization, we can pick the smaller tree as first tree. Method 2 (Merge Inorder Traversals): Do inorder traversal of first tree and store the traversal in one temp array arr1[]. This step takes O(m) time. Do inorder traversal of second tree and store the traversal in another temp array arr2[]. This step takes O(n) time. The arrays created in step 1 and 2 are sorted arrays. Merge the two sorted arrays into one array of size m + n. This step takes O(m+n) time. Construct a balanced tree from the merged array using the technique discussed in this post. This step takes O(m+n) time. Do inorder traversal of first tree and store the traversal in one temp array arr1[]. This step takes O(m) time. Do inorder traversal of second tree and store the traversal in another temp array arr2[]. This step takes O(n) time. The arrays created in step 1 and 2 are sorted arrays. Merge the two sorted arrays into one array of size m + n. This step takes O(m+n) time. Construct a balanced tree from the merged array using the technique discussed in this post. This step takes O(m+n) time. Time complexity of this method is O(m+n) which is better than method 1. This method takes O(m+n) time even if the input BSTs are not balanced. Following is implementation of this method. C++ C Java Python3 C# Javascript // C++ program to Merge Two Balanced Binary Search Trees#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; // A utility function to merge two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n); // A helper function that stores inorder// traversal of a tree in inorder arrayvoid storeInorder(node* node, int inorder[], int *index_ptr); /* A function that constructs BalancedBinary Search Tree from a sorted arraySee https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */node* sortedArrayToBST(int arr[], int start, int end); /* This function merges two balancedBSTs with roots as root1 and root2.m and n are the sizes of the trees respectively */node* mergeTrees(node *root1, node *root2, int m, int n){ // Store inorder traversal of // first tree in an array arr1[] int *arr1 = new int[m]; int i = 0; storeInorder(root1, arr1, &i); // Store inorder traversal of second // tree in another array arr2[] int *arr2 = new int[n]; int j = 0; storeInorder(root2, arr2, &j); // Merge the two sorted array into one int *mergedArr = merge(arr1, arr2, m, n); // Construct a tree from the merged // array and return root of the tree return sortedArrayToBST (mergedArr, 0, m + n - 1);} /* Helper function that allocatesa new node with the given data andNULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} // A utility function to print inorder// traversal of a given binary treevoid printInorder(node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); cout << node->data << " "; /* now recur on right child */ printInorder(node->right);} // A utility function to merge// two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n){ // mergedArr[] is going to contain result int *mergedArr = new int[m + n]; int i = 0, j = 0, k = 0; // Traverse through both arrays while (i < m && j < n) { // Pick the smaller element and put it in mergedArr if (arr1[i] < arr2[j]) { mergedArr[k] = arr1[i]; i++; } else { mergedArr[k] = arr2[j]; j++; } k++; } // If there are more elements in first array while (i < m) { mergedArr[k] = arr1[i]; i++; k++; } // If there are more elements in second array while (j < n) { mergedArr[k] = arr2[j]; j++; k++; } return mergedArr;} // A helper function that stores inorder// traversal of a tree rooted with nodevoid storeInorder(node* node, int inorder[], int *index_ptr){ if (node == NULL) return; /* first recur on left child */ storeInorder(node->left, inorder, index_ptr); inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* now recur on right child */ storeInorder(node->right, inorder, index_ptr);} /* A function that constructs Balanced// Binary Search Tree from a sorted arraySee https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */node* sortedArrayToBST(int arr[], int start, int end){ /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; node *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid+1, end); return root;} /* Driver code*/int main(){ /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ node *root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ node *root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); node *mergedTree = mergeTrees(root1, root2, 5, 3); cout << "Following is Inorder traversal of the merged tree \n"; printInorder(mergedTree); return 0;} // This code is contributed by rathbhupendra // C program to Merge Two Balanced Binary Search Trees#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; // A utility function to merge two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n); // A helper function that stores inorder traversal of a tree in inorder arrayvoid storeInorder(struct node* node, int inorder[], int *index_ptr); /* A function that constructs Balanced Binary Search Tree from a sorted array See https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */struct node* sortedArrayToBST(int arr[], int start, int end); /* This function merges two balanced BSTs with roots as root1 and root2. m and n are the sizes of the trees respectively */struct node* mergeTrees(struct node *root1, struct node *root2, int m, int n){ // Store inorder traversal of first tree in an array arr1[] int *arr1 = new int[m]; int i = 0; storeInorder(root1, arr1, &i); // Store inorder traversal of second tree in another array arr2[] int *arr2 = new int[n]; int j = 0; storeInorder(root2, arr2, &j); // Merge the two sorted array into one int *mergedArr = merge(arr1, arr2, m, n); // Construct a tree from the merged array and return root of the tree return sortedArrayToBST (mergedArr, 0, m+n-1);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // A utility function to print inorder traversal of a given binary treevoid printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); printf("%d ", node->data); /* now recur on right child */ printInorder(node->right);} // A utility function to merge two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n){ // mergedArr[] is going to contain result int *mergedArr = new int[m + n]; int i = 0, j = 0, k = 0; // Traverse through both arrays while (i < m && j < n) { // Pick the smaller element and put it in mergedArr if (arr1[i] < arr2[j]) { mergedArr[k] = arr1[i]; i++; } else { mergedArr[k] = arr2[j]; j++; } k++; } // If there are more elements in first array while (i < m) { mergedArr[k] = arr1[i]; i++; k++; } // If there are more elements in second array while (j < n) { mergedArr[k] = arr2[j]; j++; k++; } return mergedArr;} // A helper function that stores inorder traversal of a tree rooted with nodevoid storeInorder(struct node* node, int inorder[], int *index_ptr){ if (node == NULL) return; /* first recur on left child */ storeInorder(node->left, inorder, index_ptr); inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* now recur on right child */ storeInorder(node->right, inorder, index_ptr);} /* A function that constructs Balanced Binary Search Tree from a sorted array See https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */struct node* sortedArrayToBST(int arr[], int start, int end){ /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; struct node *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid+1, end); return root;} /* Driver program to test above functions*/int main(){ /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ struct node *root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ struct node *root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); struct node *mergedTree = mergeTrees(root1, root2, 5, 3); printf ("Following is Inorder traversal of the merged tree \n"); printInorder(mergedTree); getchar(); return 0;} // Java program to Merge Two Balanced Binary Search Treesimport java.io.*;import java.util.ArrayList; // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree{ // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the treevoid inorderUtil(Node node){ if(node==null) return; inorderUtil(node.left); System.out.print(node.data + " "); inorderUtil(node.right);} // A Utility Method that stores inorder traversal of a tree public ArrayList<Integer> storeInorderUtil(Node node, ArrayList<Integer> list) { if(node == null) return list; //recur on the left child storeInorderUtil(node.left, list); // Adds data to the list list.add(node.data); //recur on the right child storeInorderUtil(node.right, list); return list; } // Method that stores inorder traversal of a tree ArrayList<Integer> storeInorder(Node node) { ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2 = storeInorderUtil(node,list1); return list2; } // Method that merges two ArrayLists into one. ArrayList<Integer> merge(ArrayList<Integer>list1, ArrayList<Integer>list2, int m, int n) { // list3 will contain the merge of list1 and list2 ArrayList<Integer> list3 = new ArrayList<>(); int i=0; int j=0; //Traversing through both ArrayLists while( i<m && j<n) { // Smaller one goes into list3 if(list1.get(i)<list2.get(j)) { list3.add(list1.get(i)); i++; } else { list3.add(list2.get(j)); j++; } } // Adds the remaining elements of list1 into list3 while(i<m) { list3.add(list1.get(i)); i++; } // Adds the remaining elements of list2 into list3 while(j<n) { list3.add(list2.get(j)); j++; } return list3; } // Method that converts an ArrayList to a BST Node ALtoBST(ArrayList<Integer>list, int start, int end) { // Base case if(start > end) return null; // Get the middle element and make it root int mid = (start+end)/2; Node node = new Node(list.get(mid)); /* Recursively construct the left subtree and make it left child of root */ node.left = ALtoBST(list, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ node.right = ALtoBST(list, mid+1, end); return node; } // Method that merges two trees into a single one. Node mergeTrees(Node node1, Node node2) { //Stores Inorder of tree1 to list1 ArrayList<Integer>list1 = storeInorder(node1); //Stores Inorder of tree2 to list2 ArrayList<Integer>list2 = storeInorder(node2); // Merges both list1 and list2 into list3 ArrayList<Integer>list3 = merge(list1, list2, list1.size(), list2.size()); //Eventually converts the merged list into resultant BST Node node = ALtoBST(list3, 0, list3.size()-1); return node; } // Driver function public static void main (String[] args) { /* Creating following tree as First balanced BST 100 / \ 50 300 / \ 20 70 */ BinarySearchTree tree1 = new BinarySearchTree(); tree1.root = new Node(100); tree1.root.left = new Node(50); tree1.root.right = new Node(300); tree1.root.left.left = new Node(20); tree1.root.left.right = new Node(70); /* Creating following tree as second balanced BST 80 / \ 40 120 */ BinarySearchTree tree2 = new BinarySearchTree(); tree2.root = new Node(80); tree2.root.left = new Node(40); tree2.root.right = new Node(120); BinarySearchTree tree = new BinarySearchTree(); tree.root = tree.mergeTrees(tree1.root, tree2.root); System.out.println("The Inorder traversal of the merged BST is: "); tree.inorder(); }}// This code has been contributed by Kamal Rawal # A binary tree node has data, pointer to left child # and a pointer to right childclass Node: def __init__(self, val): self.val = val self.left = None self.right = None # A utility function to merge two sorted arrays into one# Time Complexity of below function: O(m + n)# Space Complexity of below function: O(m + n)def merge_sorted_arr(arr1, arr2): arr = [] i = j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: arr.append(arr1[i]) i += 1 else: arr.append(arr2[j]) j += 1 while i < len(arr1): arr.append(arr1[i]) i += 1 while i < len(arr2): arr.append(arr2[j]) j += 1 return arr # A helper function that stores inorder# traversal of a tree in arrdef inorder(root, arr = []): if root: inorder(root.left, arr) arr.append(root.val) inorder(root.right, arr) # A utility function to insert the values# in the individual Treedef insert(root, val): if not root: return Node(val) if root.val == val: return root elif root.val > val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root # Converts the merged array to a balanced BST# Explanation of the below code:# https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/def arr_to_bst(arr): if not arr: return None mid = len(arr) // 2 root = Node(arr[mid]) root.left = arr_to_bst(arr[:mid]) root.right = arr_to_bst(arr[mid + 1:]) return root if __name__=='__main__': root1 = root2 = None # Inserting values in first tree root1 = insert(root1, 100) root1 = insert(root1, 50) root1 = insert(root1, 300) root1 = insert(root1, 20) root1 = insert(root1, 70) # Inserting values in second tree root2 = insert(root2, 80) root2 = insert(root2, 40) root2 = insert(root2, 120) arr1 = [] inorder(root1, arr1) arr2 = [] inorder(root2, arr2) arr = merge_sorted_arr(arr1, arr2) root = arr_to_bst(arr) res = [] inorder(root, res) print('Following is Inorder traversal of the merged tree') for i in res: print(i, end = ' ') # This code is contributed by Flarow4 // C# program to Merge Two Balanced Binary Search Treesusing System;using System.Collections.Generic; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree{ // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // Inorder traversal of the tree public virtual void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the treepublic virtual void inorderUtil(Node node){ if (node == null) { return; } inorderUtil(node.left); Console.Write(node.data + " "); inorderUtil(node.right);} // A Utility Method that stores inorder traversal of a tree public virtual List<int> storeInorderUtil(Node node, List<int> list) { if (node == null) { return list; } //recur on the left child storeInorderUtil(node.left, list); // Adds data to the list list.Add(node.data); //recur on the right child storeInorderUtil(node.right, list); return list; } // Method that stores inorder traversal of a tree public virtual List<int> storeInorder(Node node) { List<int> list1 = new List<int>(); List<int> list2 = storeInorderUtil(node,list1); return list2; } // Method that merges two ArrayLists into one. public virtual List<int> merge(List<int> list1, List<int> list2, int m, int n) { // list3 will contain the merge of list1 and list2 List<int> list3 = new List<int>(); int i = 0; int j = 0; //Traversing through both ArrayLists while (i < m && j < n) { // Smaller one goes into list3 if (list1[i] < list2[j]) { list3.Add(list1[i]); i++; } else { list3.Add(list2[j]); j++; } } // Adds the remaining elements of list1 into list3 while (i < m) { list3.Add(list1[i]); i++; } // Adds the remaining elements of list2 into list3 while (j < n) { list3.Add(list2[j]); j++; } return list3; } // Method that converts an ArrayList to a BST public virtual Node ALtoBST(List<int> list, int start, int end) { // Base case if (start > end) { return null; } // Get the middle element and make it root int mid = (start + end) / 2; Node node = new Node(list[mid]); /* Recursively construct the left subtree and make it left child of root */ node.left = ALtoBST(list, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ node.right = ALtoBST(list, mid + 1, end); return node; } // Method that merges two trees into a single one. public virtual Node mergeTrees(Node node1, Node node2) { //Stores Inorder of tree1 to list1 List<int> list1 = storeInorder(node1); //Stores Inorder of tree2 to list2 List<int> list2 = storeInorder(node2); // Merges both list1 and list2 into list3 List<int> list3 = merge(list1, list2, list1.Count, list2.Count); //Eventually converts the merged list into resultant BST Node node = ALtoBST(list3, 0, list3.Count - 1); return node; } // Driver function public static void Main(string[] args) { /* Creating following tree as First balanced BST 100 / \ 50 300 / \ 20 70 */ BinarySearchTree tree1 = new BinarySearchTree(); tree1.root = new Node(100); tree1.root.left = new Node(50); tree1.root.right = new Node(300); tree1.root.left.left = new Node(20); tree1.root.left.right = new Node(70); /* Creating following tree as second balanced BST 80 / \ 40 120 */ BinarySearchTree tree2 = new BinarySearchTree(); tree2.root = new Node(80); tree2.root.left = new Node(40); tree2.root.right = new Node(120); BinarySearchTree tree = new BinarySearchTree(); tree.root = tree.mergeTrees(tree1.root, tree2.root); Console.WriteLine("The Inorder traversal of the merged BST is: "); tree.inorder(); }} // This code is contributed by Shrikant13 <script> // JavaScript program to Merge Two // Balanced Binary Search Trees // A binary tree node class Node { constructor(d) { this.data = d; this.left = null; this.right = null; } } class BinarySearchTree { // Constructor constructor() { this.root = null; } // Inorder traversal of the tree inorder() { this.inorderUtil(this.root); } // Utility function for inorder traversal of the tree inorderUtil(node) { if (node == null) { return; } this.inorderUtil(node.left); document.write(node.data + " "); this.inorderUtil(node.right); } // A Utility Method that stores // inorder traversal of a tree storeInorderUtil(node, list) { if (node == null) { return list; } //recur on the left child this.storeInorderUtil(node.left, list); // Adds data to the list list.push(node.data); //recur on the right child this.storeInorderUtil(node.right, list); return list; } // Method that stores inorder traversal of a tree storeInorder(node) { var list1 = []; var list2 = this.storeInorderUtil(node, list1); return list2; } // Method that merges two ArrayLists into one. merge(list1, list2, m, n) { // list3 will contain the merge of list1 and list2 var list3 = []; var i = 0; var j = 0; //Traversing through both ArrayLists while (i < m && j < n) { // Smaller one goes into list3 if (list1[i] < list2[j]) { list3.push(list1[i]); i++; } else { list3.push(list2[j]); j++; } } // Adds the remaining elements of list1 into list3 while (i < m) { list3.push(list1[i]); i++; } // Adds the remaining elements of list2 into list3 while (j < n) { list3.push(list2[j]); j++; } return list3; } // Method that converts an ArrayList to a BST ALtoBST(list, start, end) { // Base case if (start > end) { return null; } // Get the middle element and make it root var mid = parseInt((start + end) / 2); var node = new Node(list[mid]); /* Recursively construct the left subtree and make it left child of root */ node.left = this.ALtoBST(list, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ node.right = this.ALtoBST(list, mid + 1, end); return node; } // Method that merges two trees into a single one. mergeTrees(node1, node2) { //Stores Inorder of tree1 to list1 var list1 = this.storeInorder(node1); //Stores Inorder of tree2 to list2 var list2 = this.storeInorder(node2); // Merges both list1 and list2 into list3 var list3 = this.merge(list1, list2, list1.length, list2.length); //Eventually converts the merged list into resultant BST var node = this.ALtoBST(list3, 0, list3.length - 1); return node; } } // Driver function /* Creating following tree as First balanced BST 100 / \ 50 300 / \ 20 70 */ var tree1 = new BinarySearchTree(); tree1.root = new Node(100); tree1.root.left = new Node(50); tree1.root.right = new Node(300); tree1.root.left.left = new Node(20); tree1.root.left.right = new Node(70); /* Creating following tree as second balanced BST 80 / \ 40 120 */ var tree2 = new BinarySearchTree(); tree2.root = new Node(80); tree2.root.left = new Node(40); tree2.root.right = new Node(120); var tree = new BinarySearchTree(); tree.root = tree.mergeTrees(tree1.root, tree2.root); document.write( "Following is Inorder traversal of the merged tree <br>" ); tree.inorder(); </script> Output: Following is Inorder traversal of the merged tree 20 40 50 70 80 100 120 300 Method 3 (In-Place Merge using DLL): We can use a Doubly Linked List to merge trees in place. Following are the steps. Convert the given two Binary Search Trees into doubly linked list in place (Refer this post for this step). Merge the two sorted Linked Lists (Refer this post for this step). Build a Balanced Binary Search Tree from the merged list created in step 2. (Refer this post for this step) Convert the given two Binary Search Trees into doubly linked list in place (Refer this post for this step). Merge the two sorted Linked Lists (Refer this post for this step). Build a Balanced Binary Search Tree from the merged list created in step 2. (Refer this post for this step) Time complexity of this method is also O(m+n) and this method does conversion in place.Thanks to Dheeraj and Ronzii for suggesting this method. shrikanth13 rathbhupendra anjani10kumar anikakapoor rdtank prityushchandraece18 surindertarika1234 prachisoda1234 varshagumber28 hardikkoriintern doubly linked list Self-Balancing-BST Binary Search Tree Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Inorder Successor in Binary Search Tree Convert a normal BST to Balanced BST set vs unordered_set in C++ STL Find k-th smallest element in BST (Order Statistics in BST) Check if a given array can represent Preorder Traversal of Binary Search Tree
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2022" }, { "code": null, "e": 520, "s": 54, "text": "You are given two balanced binary search trees e.g., AVL or Red-Black Tree. Write a function that merges the two given balanced BSTs into a balanced binary search tree. Let there be m elements in the first tree and n elements in the other tree. Your merge function should take O(m+n) time.In the following solutions, it is assumed that the sizes of trees are also given as input. If the size is not given, then we can get the size by traversing the tree (See this)." }, { "code": null, "e": 576, "s": 520, "text": "Method 1 (Insert elements of the first tree to second):" }, { "code": null, "e": 959, "s": 576, "text": "Take all elements of first BST one by one, and insert them into the second BST. Inserting an element to a self balancing BST takes Logn time (See this) where n is size of the BST. So time complexity of this method is Log(n) + Log(n+1) ... Log(m+n-1). The value of this expression will be between mLogn and mLog(m+n-1). As an optimization, we can pick the smaller tree as first tree." }, { "code": null, "e": 996, "s": 959, "text": "Method 2 (Merge Inorder Traversals):" }, { "code": null, "e": 1487, "s": 996, "text": "Do inorder traversal of first tree and store the traversal in one temp array arr1[]. This step takes O(m) time. Do inorder traversal of second tree and store the traversal in another temp array arr2[]. This step takes O(n) time. The arrays created in step 1 and 2 are sorted arrays. Merge the two sorted arrays into one array of size m + n. This step takes O(m+n) time. Construct a balanced tree from the merged array using the technique discussed in this post. This step takes O(m+n) time." }, { "code": null, "e": 1600, "s": 1487, "text": "Do inorder traversal of first tree and store the traversal in one temp array arr1[]. This step takes O(m) time. " }, { "code": null, "e": 1718, "s": 1600, "text": "Do inorder traversal of second tree and store the traversal in another temp array arr2[]. This step takes O(n) time. " }, { "code": null, "e": 1860, "s": 1718, "text": "The arrays created in step 1 and 2 are sorted arrays. Merge the two sorted arrays into one array of size m + n. This step takes O(m+n) time. " }, { "code": null, "e": 1981, "s": 1860, "text": "Construct a balanced tree from the merged array using the technique discussed in this post. This step takes O(m+n) time." }, { "code": null, "e": 2168, "s": 1981, "text": "Time complexity of this method is O(m+n) which is better than method 1. This method takes O(m+n) time even if the input BSTs are not balanced. Following is implementation of this method." }, { "code": null, "e": 2172, "s": 2168, "text": "C++" }, { "code": null, "e": 2174, "s": 2172, "text": "C" }, { "code": null, "e": 2179, "s": 2174, "text": "Java" }, { "code": null, "e": 2187, "s": 2179, "text": "Python3" }, { "code": null, "e": 2190, "s": 2187, "text": "C#" }, { "code": null, "e": 2201, "s": 2190, "text": "Javascript" }, { "code": "// C++ program to Merge Two Balanced Binary Search Trees#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node* left; node* right;}; // A utility function to merge two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n); // A helper function that stores inorder// traversal of a tree in inorder arrayvoid storeInorder(node* node, int inorder[], int *index_ptr); /* A function that constructs BalancedBinary Search Tree from a sorted arraySee https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */node* sortedArrayToBST(int arr[], int start, int end); /* This function merges two balancedBSTs with roots as root1 and root2.m and n are the sizes of the trees respectively */node* mergeTrees(node *root1, node *root2, int m, int n){ // Store inorder traversal of // first tree in an array arr1[] int *arr1 = new int[m]; int i = 0; storeInorder(root1, arr1, &i); // Store inorder traversal of second // tree in another array arr2[] int *arr2 = new int[n]; int j = 0; storeInorder(root2, arr2, &j); // Merge the two sorted array into one int *mergedArr = merge(arr1, arr2, m, n); // Construct a tree from the merged // array and return root of the tree return sortedArrayToBST (mergedArr, 0, m + n - 1);} /* Helper function that allocatesa new node with the given data andNULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return(Node);} // A utility function to print inorder// traversal of a given binary treevoid printInorder(node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); cout << node->data << \" \"; /* now recur on right child */ printInorder(node->right);} // A utility function to merge// two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n){ // mergedArr[] is going to contain result int *mergedArr = new int[m + n]; int i = 0, j = 0, k = 0; // Traverse through both arrays while (i < m && j < n) { // Pick the smaller element and put it in mergedArr if (arr1[i] < arr2[j]) { mergedArr[k] = arr1[i]; i++; } else { mergedArr[k] = arr2[j]; j++; } k++; } // If there are more elements in first array while (i < m) { mergedArr[k] = arr1[i]; i++; k++; } // If there are more elements in second array while (j < n) { mergedArr[k] = arr2[j]; j++; k++; } return mergedArr;} // A helper function that stores inorder// traversal of a tree rooted with nodevoid storeInorder(node* node, int inorder[], int *index_ptr){ if (node == NULL) return; /* first recur on left child */ storeInorder(node->left, inorder, index_ptr); inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* now recur on right child */ storeInorder(node->right, inorder, index_ptr);} /* A function that constructs Balanced// Binary Search Tree from a sorted arraySee https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */node* sortedArrayToBST(int arr[], int start, int end){ /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; node *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid+1, end); return root;} /* Driver code*/int main(){ /* Create following tree as first balanced BST 100 / \\ 50 300 / \\ 20 70 */ node *root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \\ 40 120 */ node *root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); node *mergedTree = mergeTrees(root1, root2, 5, 3); cout << \"Following is Inorder traversal of the merged tree \\n\"; printInorder(mergedTree); return 0;} // This code is contributed by rathbhupendra", "e": 6786, "s": 2201, "text": null }, { "code": "// C program to Merge Two Balanced Binary Search Trees#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node* left; struct node* right;}; // A utility function to merge two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n); // A helper function that stores inorder traversal of a tree in inorder arrayvoid storeInorder(struct node* node, int inorder[], int *index_ptr); /* A function that constructs Balanced Binary Search Tree from a sorted array See https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */struct node* sortedArrayToBST(int arr[], int start, int end); /* This function merges two balanced BSTs with roots as root1 and root2. m and n are the sizes of the trees respectively */struct node* mergeTrees(struct node *root1, struct node *root2, int m, int n){ // Store inorder traversal of first tree in an array arr1[] int *arr1 = new int[m]; int i = 0; storeInorder(root1, arr1, &i); // Store inorder traversal of second tree in another array arr2[] int *arr2 = new int[n]; int j = 0; storeInorder(root2, arr2, &j); // Merge the two sorted array into one int *mergedArr = merge(arr1, arr2, m, n); // Construct a tree from the merged array and return root of the tree return sortedArrayToBST (mergedArr, 0, m+n-1);} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // A utility function to print inorder traversal of a given binary treevoid printInorder(struct node* node){ if (node == NULL) return; /* first recur on left child */ printInorder(node->left); printf(\"%d \", node->data); /* now recur on right child */ printInorder(node->right);} // A utility function to merge two sorted arrays into oneint *merge(int arr1[], int arr2[], int m, int n){ // mergedArr[] is going to contain result int *mergedArr = new int[m + n]; int i = 0, j = 0, k = 0; // Traverse through both arrays while (i < m && j < n) { // Pick the smaller element and put it in mergedArr if (arr1[i] < arr2[j]) { mergedArr[k] = arr1[i]; i++; } else { mergedArr[k] = arr2[j]; j++; } k++; } // If there are more elements in first array while (i < m) { mergedArr[k] = arr1[i]; i++; k++; } // If there are more elements in second array while (j < n) { mergedArr[k] = arr2[j]; j++; k++; } return mergedArr;} // A helper function that stores inorder traversal of a tree rooted with nodevoid storeInorder(struct node* node, int inorder[], int *index_ptr){ if (node == NULL) return; /* first recur on left child */ storeInorder(node->left, inorder, index_ptr); inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* now recur on right child */ storeInorder(node->right, inorder, index_ptr);} /* A function that constructs Balanced Binary Search Tree from a sorted array See https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/ */struct node* sortedArrayToBST(int arr[], int start, int end){ /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; struct node *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid+1, end); return root;} /* Driver program to test above functions*/int main(){ /* Create following tree as first balanced BST 100 / \\ 50 300 / \\ 20 70 */ struct node *root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \\ 40 120 */ struct node *root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); struct node *mergedTree = mergeTrees(root1, root2, 5, 3); printf (\"Following is Inorder traversal of the merged tree \\n\"); printInorder(mergedTree); getchar(); return 0;}", "e": 11535, "s": 6786, "text": null }, { "code": "// Java program to Merge Two Balanced Binary Search Treesimport java.io.*;import java.util.ArrayList; // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree{ // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the treevoid inorderUtil(Node node){ if(node==null) return; inorderUtil(node.left); System.out.print(node.data + \" \"); inorderUtil(node.right);} // A Utility Method that stores inorder traversal of a tree public ArrayList<Integer> storeInorderUtil(Node node, ArrayList<Integer> list) { if(node == null) return list; //recur on the left child storeInorderUtil(node.left, list); // Adds data to the list list.add(node.data); //recur on the right child storeInorderUtil(node.right, list); return list; } // Method that stores inorder traversal of a tree ArrayList<Integer> storeInorder(Node node) { ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2 = storeInorderUtil(node,list1); return list2; } // Method that merges two ArrayLists into one. ArrayList<Integer> merge(ArrayList<Integer>list1, ArrayList<Integer>list2, int m, int n) { // list3 will contain the merge of list1 and list2 ArrayList<Integer> list3 = new ArrayList<>(); int i=0; int j=0; //Traversing through both ArrayLists while( i<m && j<n) { // Smaller one goes into list3 if(list1.get(i)<list2.get(j)) { list3.add(list1.get(i)); i++; } else { list3.add(list2.get(j)); j++; } } // Adds the remaining elements of list1 into list3 while(i<m) { list3.add(list1.get(i)); i++; } // Adds the remaining elements of list2 into list3 while(j<n) { list3.add(list2.get(j)); j++; } return list3; } // Method that converts an ArrayList to a BST Node ALtoBST(ArrayList<Integer>list, int start, int end) { // Base case if(start > end) return null; // Get the middle element and make it root int mid = (start+end)/2; Node node = new Node(list.get(mid)); /* Recursively construct the left subtree and make it left child of root */ node.left = ALtoBST(list, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ node.right = ALtoBST(list, mid+1, end); return node; } // Method that merges two trees into a single one. Node mergeTrees(Node node1, Node node2) { //Stores Inorder of tree1 to list1 ArrayList<Integer>list1 = storeInorder(node1); //Stores Inorder of tree2 to list2 ArrayList<Integer>list2 = storeInorder(node2); // Merges both list1 and list2 into list3 ArrayList<Integer>list3 = merge(list1, list2, list1.size(), list2.size()); //Eventually converts the merged list into resultant BST Node node = ALtoBST(list3, 0, list3.size()-1); return node; } // Driver function public static void main (String[] args) { /* Creating following tree as First balanced BST 100 / \\ 50 300 / \\ 20 70 */ BinarySearchTree tree1 = new BinarySearchTree(); tree1.root = new Node(100); tree1.root.left = new Node(50); tree1.root.right = new Node(300); tree1.root.left.left = new Node(20); tree1.root.left.right = new Node(70); /* Creating following tree as second balanced BST 80 / \\ 40 120 */ BinarySearchTree tree2 = new BinarySearchTree(); tree2.root = new Node(80); tree2.root.left = new Node(40); tree2.root.right = new Node(120); BinarySearchTree tree = new BinarySearchTree(); tree.root = tree.mergeTrees(tree1.root, tree2.root); System.out.println(\"The Inorder traversal of the merged BST is: \"); tree.inorder(); }}// This code has been contributed by Kamal Rawal", "e": 16317, "s": 11535, "text": null }, { "code": "# A binary tree node has data, pointer to left child # and a pointer to right childclass Node: def __init__(self, val): self.val = val self.left = None self.right = None # A utility function to merge two sorted arrays into one# Time Complexity of below function: O(m + n)# Space Complexity of below function: O(m + n)def merge_sorted_arr(arr1, arr2): arr = [] i = j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: arr.append(arr1[i]) i += 1 else: arr.append(arr2[j]) j += 1 while i < len(arr1): arr.append(arr1[i]) i += 1 while i < len(arr2): arr.append(arr2[j]) j += 1 return arr # A helper function that stores inorder# traversal of a tree in arrdef inorder(root, arr = []): if root: inorder(root.left, arr) arr.append(root.val) inorder(root.right, arr) # A utility function to insert the values# in the individual Treedef insert(root, val): if not root: return Node(val) if root.val == val: return root elif root.val > val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root # Converts the merged array to a balanced BST# Explanation of the below code:# https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/def arr_to_bst(arr): if not arr: return None mid = len(arr) // 2 root = Node(arr[mid]) root.left = arr_to_bst(arr[:mid]) root.right = arr_to_bst(arr[mid + 1:]) return root if __name__=='__main__': root1 = root2 = None # Inserting values in first tree root1 = insert(root1, 100) root1 = insert(root1, 50) root1 = insert(root1, 300) root1 = insert(root1, 20) root1 = insert(root1, 70) # Inserting values in second tree root2 = insert(root2, 80) root2 = insert(root2, 40) root2 = insert(root2, 120) arr1 = [] inorder(root1, arr1) arr2 = [] inorder(root2, arr2) arr = merge_sorted_arr(arr1, arr2) root = arr_to_bst(arr) res = [] inorder(root, res) print('Following is Inorder traversal of the merged tree') for i in res: print(i, end = ' ') # This code is contributed by Flarow4", "e": 18569, "s": 16317, "text": null }, { "code": "// C# program to Merge Two Balanced Binary Search Treesusing System;using System.Collections.Generic; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree{ // Root of BST public Node root; // Constructor public BinarySearchTree() { root = null; } // Inorder traversal of the tree public virtual void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the treepublic virtual void inorderUtil(Node node){ if (node == null) { return; } inorderUtil(node.left); Console.Write(node.data + \" \"); inorderUtil(node.right);} // A Utility Method that stores inorder traversal of a tree public virtual List<int> storeInorderUtil(Node node, List<int> list) { if (node == null) { return list; } //recur on the left child storeInorderUtil(node.left, list); // Adds data to the list list.Add(node.data); //recur on the right child storeInorderUtil(node.right, list); return list; } // Method that stores inorder traversal of a tree public virtual List<int> storeInorder(Node node) { List<int> list1 = new List<int>(); List<int> list2 = storeInorderUtil(node,list1); return list2; } // Method that merges two ArrayLists into one. public virtual List<int> merge(List<int> list1, List<int> list2, int m, int n) { // list3 will contain the merge of list1 and list2 List<int> list3 = new List<int>(); int i = 0; int j = 0; //Traversing through both ArrayLists while (i < m && j < n) { // Smaller one goes into list3 if (list1[i] < list2[j]) { list3.Add(list1[i]); i++; } else { list3.Add(list2[j]); j++; } } // Adds the remaining elements of list1 into list3 while (i < m) { list3.Add(list1[i]); i++; } // Adds the remaining elements of list2 into list3 while (j < n) { list3.Add(list2[j]); j++; } return list3; } // Method that converts an ArrayList to a BST public virtual Node ALtoBST(List<int> list, int start, int end) { // Base case if (start > end) { return null; } // Get the middle element and make it root int mid = (start + end) / 2; Node node = new Node(list[mid]); /* Recursively construct the left subtree and make it left child of root */ node.left = ALtoBST(list, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ node.right = ALtoBST(list, mid + 1, end); return node; } // Method that merges two trees into a single one. public virtual Node mergeTrees(Node node1, Node node2) { //Stores Inorder of tree1 to list1 List<int> list1 = storeInorder(node1); //Stores Inorder of tree2 to list2 List<int> list2 = storeInorder(node2); // Merges both list1 and list2 into list3 List<int> list3 = merge(list1, list2, list1.Count, list2.Count); //Eventually converts the merged list into resultant BST Node node = ALtoBST(list3, 0, list3.Count - 1); return node; } // Driver function public static void Main(string[] args) { /* Creating following tree as First balanced BST 100 / \\ 50 300 / \\ 20 70 */ BinarySearchTree tree1 = new BinarySearchTree(); tree1.root = new Node(100); tree1.root.left = new Node(50); tree1.root.right = new Node(300); tree1.root.left.left = new Node(20); tree1.root.left.right = new Node(70); /* Creating following tree as second balanced BST 80 / \\ 40 120 */ BinarySearchTree tree2 = new BinarySearchTree(); tree2.root = new Node(80); tree2.root.left = new Node(40); tree2.root.right = new Node(120); BinarySearchTree tree = new BinarySearchTree(); tree.root = tree.mergeTrees(tree1.root, tree2.root); Console.WriteLine(\"The Inorder traversal of the merged BST is: \"); tree.inorder(); }} // This code is contributed by Shrikant13", "e": 23227, "s": 18569, "text": null }, { "code": "<script> // JavaScript program to Merge Two // Balanced Binary Search Trees // A binary tree node class Node { constructor(d) { this.data = d; this.left = null; this.right = null; } } class BinarySearchTree { // Constructor constructor() { this.root = null; } // Inorder traversal of the tree inorder() { this.inorderUtil(this.root); } // Utility function for inorder traversal of the tree inorderUtil(node) { if (node == null) { return; } this.inorderUtil(node.left); document.write(node.data + \" \"); this.inorderUtil(node.right); } // A Utility Method that stores // inorder traversal of a tree storeInorderUtil(node, list) { if (node == null) { return list; } //recur on the left child this.storeInorderUtil(node.left, list); // Adds data to the list list.push(node.data); //recur on the right child this.storeInorderUtil(node.right, list); return list; } // Method that stores inorder traversal of a tree storeInorder(node) { var list1 = []; var list2 = this.storeInorderUtil(node, list1); return list2; } // Method that merges two ArrayLists into one. merge(list1, list2, m, n) { // list3 will contain the merge of list1 and list2 var list3 = []; var i = 0; var j = 0; //Traversing through both ArrayLists while (i < m && j < n) { // Smaller one goes into list3 if (list1[i] < list2[j]) { list3.push(list1[i]); i++; } else { list3.push(list2[j]); j++; } } // Adds the remaining elements of list1 into list3 while (i < m) { list3.push(list1[i]); i++; } // Adds the remaining elements of list2 into list3 while (j < n) { list3.push(list2[j]); j++; } return list3; } // Method that converts an ArrayList to a BST ALtoBST(list, start, end) { // Base case if (start > end) { return null; } // Get the middle element and make it root var mid = parseInt((start + end) / 2); var node = new Node(list[mid]); /* Recursively construct the left subtree and make it left child of root */ node.left = this.ALtoBST(list, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ node.right = this.ALtoBST(list, mid + 1, end); return node; } // Method that merges two trees into a single one. mergeTrees(node1, node2) { //Stores Inorder of tree1 to list1 var list1 = this.storeInorder(node1); //Stores Inorder of tree2 to list2 var list2 = this.storeInorder(node2); // Merges both list1 and list2 into list3 var list3 = this.merge(list1, list2, list1.length, list2.length); //Eventually converts the merged list into resultant BST var node = this.ALtoBST(list3, 0, list3.length - 1); return node; } } // Driver function /* Creating following tree as First balanced BST 100 / \\ 50 300 / \\ 20 70 */ var tree1 = new BinarySearchTree(); tree1.root = new Node(100); tree1.root.left = new Node(50); tree1.root.right = new Node(300); tree1.root.left.left = new Node(20); tree1.root.left.right = new Node(70); /* Creating following tree as second balanced BST 80 / \\ 40 120 */ var tree2 = new BinarySearchTree(); tree2.root = new Node(80); tree2.root.left = new Node(40); tree2.root.right = new Node(120); var tree = new BinarySearchTree(); tree.root = tree.mergeTrees(tree1.root, tree2.root); document.write( \"Following is Inorder traversal of the merged tree <br>\" ); tree.inorder(); </script>", "e": 27620, "s": 23227, "text": null }, { "code": null, "e": 27630, "s": 27620, "text": "Output: " }, { "code": null, "e": 27707, "s": 27630, "text": "Following is Inorder traversal of the merged tree\n20 40 50 70 80 100 120 300" }, { "code": null, "e": 27744, "s": 27707, "text": "Method 3 (In-Place Merge using DLL):" }, { "code": null, "e": 27826, "s": 27744, "text": "We can use a Doubly Linked List to merge trees in place. Following are the steps." }, { "code": null, "e": 28109, "s": 27826, "text": "Convert the given two Binary Search Trees into doubly linked list in place (Refer this post for this step). Merge the two sorted Linked Lists (Refer this post for this step). Build a Balanced Binary Search Tree from the merged list created in step 2. (Refer this post for this step)" }, { "code": null, "e": 28218, "s": 28109, "text": "Convert the given two Binary Search Trees into doubly linked list in place (Refer this post for this step). " }, { "code": null, "e": 28286, "s": 28218, "text": "Merge the two sorted Linked Lists (Refer this post for this step). " }, { "code": null, "e": 28394, "s": 28286, "text": "Build a Balanced Binary Search Tree from the merged list created in step 2. (Refer this post for this step)" }, { "code": null, "e": 28538, "s": 28394, "text": "Time complexity of this method is also O(m+n) and this method does conversion in place.Thanks to Dheeraj and Ronzii for suggesting this method." }, { "code": null, "e": 28550, "s": 28538, "text": "shrikanth13" }, { "code": null, "e": 28564, "s": 28550, "text": "rathbhupendra" }, { "code": null, "e": 28578, "s": 28564, "text": "anjani10kumar" }, { "code": null, "e": 28590, "s": 28578, "text": "anikakapoor" }, { "code": null, "e": 28597, "s": 28590, "text": "rdtank" }, { "code": null, "e": 28618, "s": 28597, "text": "prityushchandraece18" }, { "code": null, "e": 28637, "s": 28618, "text": "surindertarika1234" }, { "code": null, "e": 28652, "s": 28637, "text": "prachisoda1234" }, { "code": null, "e": 28667, "s": 28652, "text": "varshagumber28" }, { "code": null, "e": 28684, "s": 28667, "text": "hardikkoriintern" }, { "code": null, "e": 28703, "s": 28684, "text": "doubly linked list" }, { "code": null, "e": 28722, "s": 28703, "text": "Self-Balancing-BST" }, { "code": null, "e": 28741, "s": 28722, "text": "Binary Search Tree" }, { "code": null, "e": 28760, "s": 28741, "text": "Binary Search Tree" }, { "code": null, "e": 28858, "s": 28760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28908, "s": 28858, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 28964, "s": 28908, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 29034, "s": 28964, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 29063, "s": 29034, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 29098, "s": 29063, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 29138, "s": 29098, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 29175, "s": 29138, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 29207, "s": 29175, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 29267, "s": 29207, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
Compile 32-bit program on 64-bit gcc in C and C++
Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use thisS feature. At first, we Shave to check the current target version of the gcc compiler. To check this, we have to type this command. gcc –v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper OFFLOAD_TARGET_NAMES=nvptx-none OFFLOAD_TARGET_DEFAULT=1 Target: x86_64-linux-gnu ........... ........... ........... Here it is showing that Target is x86_64. So we are using the 64-bit version of gcc. Now to use the 32-bit system, we have to write the following command. gcc –m32 program_name.c Sometimes this command may generate some error like below. This indicates that the standard library of gcc is missing. In that situation we have to install them. In file included from test_c.c:1:0: /usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file or directory #include <bits/libc-header-start.h> ^~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. Now, to install the standard library for gcc, we have to write the following commands. sudo apt-get install gcc-multilib sudo apt-get install g++-multilib Now by using this code we will see the differences of executing in 32-bit system and the 64-bit system. #include<stdio.h> main() { printf("The Size is: %lu\n", sizeof(long)); } $ gcc test_c.c test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(){ ^~~~ $ ./a.out The Size is: 8 $ gcc -m32 test_c.c test_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(){ ^~~~ test_c.c: In function ‘main’: test_c.c:4:28: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘unsigned int’ [-Wformat=] printf("The Size is: %lu\n", sizeof(long)); ~~^ %u $ ./a.out The Size is: 4
[ { "code": null, "e": 1360, "s": 1187, "text": "Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use thisS feature." }, { "code": null, "e": 1481, "s": 1360, "text": "At first, we Shave to check the current target version of the gcc compiler. To check this, we have to type this command." }, { "code": null, "e": 1708, "s": 1481, "text": "gcc –v\nUsing built-in specs.\nCOLLECT_GCC=gcc\nCOLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper\nOFFLOAD_TARGET_NAMES=nvptx-none\nOFFLOAD_TARGET_DEFAULT=1\nTarget: x86_64-linux-gnu\n...........\n...........\n..........." }, { "code": null, "e": 1863, "s": 1708, "text": "Here it is showing that Target is x86_64. So we are using the 64-bit version of gcc. Now to use the 32-bit system, we have to write the following command." }, { "code": null, "e": 1887, "s": 1863, "text": "gcc –m32 program_name.c" }, { "code": null, "e": 2049, "s": 1887, "text": "Sometimes this command may generate some error like below. This indicates that the standard library of gcc is missing. In that situation we have to install them." }, { "code": null, "e": 2265, "s": 2049, "text": "In file included from test_c.c:1:0:\n/usr/include/stdio.h:27:10: fatal error: bits/libc-header-start.h: No such file\nor directory\n#include <bits/libc-header-start.h>\n^~~~~~~~~~~~~~~~~~~~~~~~~~\ncompilation terminated." }, { "code": null, "e": 2352, "s": 2265, "text": "Now, to install the standard library for gcc, we have to write the following commands." }, { "code": null, "e": 2420, "s": 2352, "text": "sudo apt-get install gcc-multilib\nsudo apt-get install g++-multilib" }, { "code": null, "e": 2524, "s": 2420, "text": "Now by using this code we will see the differences of executing in 32-bit system and the 64-bit system." }, { "code": null, "e": 2600, "s": 2524, "text": "#include<stdio.h>\nmain() {\n printf(\"The Size is: %lu\\n\", sizeof(long));\n}" }, { "code": null, "e": 2723, "s": 2600, "text": "$ gcc test_c.c\ntest_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(){\n^~~~\n$ ./a.out\nThe Size is: 8" }, { "code": null, "e": 3066, "s": 2723, "text": "$ gcc -m32 test_c.c\ntest_c.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int]\nmain(){\n^~~~\ntest_c.c: In function ‘main’:\ntest_c.c:4:28: warning: format ‘%lu’ expects argument of type ‘long unsigned\nint’, but argument 2 has type ‘unsigned int’ [-Wformat=]\nprintf(\"The Size is: %lu\\n\", sizeof(long));\n~~^\n%u\n$ ./a.out\nThe Size is: 4" } ]
Variable Length Arrays in C and C++
Here we will discuss about the variable length arrays in C++. Using this we can allocate an auto array of variable size. In C, it supports variable sized arrays from C99 standard. The following format supports this concept − void make_arr(int n){ int array[n]; } int main(){ make_arr(10); } But, in C++ standard (till C++11) there was no concept of variable length array. According to the C++11 standard, array size is mentioned as a constant-expression. So, the above block of code may not be a valid C++11 or below. In C++14 mentions array size as a simple expression (not constant-expression). Let us see the following implementation to get better understanding − Live Demo #include<iostream> #include<cstring> #include<cstdlib> using namespace std; class employee { public: int id; int name_length; int struct_size; char emp_name[0]; }; employee *make_emp(struct employee *e, int id, char arr[]) { e = new employee(); e->id = id; e->name_length = strlen(arr); strcpy(e->emp_name, arr); e->struct_size=( sizeof(*e) + sizeof(char)*strlen(e->emp_name) ); return e; } void disp_emp(struct employee *e) { cout << "Emp Id:" << e->id << endl; cout << "Emp Name:" << e->emp_name << endl; cout << "Name Length:" << e->name_length << endl; cout << "Allocated:" << e->struct_size << endl; cout <<"---------------------------------------" << endl; } int main() { employee *e1, *e2; e1=make_emp(e1, 101, "Jayanta Das"); e2=make_emp(e2, 201, "Tushar Dey"); disp_emp(e1); disp_emp(e2); cout << "Size of student: " << sizeof(employee) << endl; cout << "Size of student pointer: " << sizeof(e1); } Emp Id:101 Emp Name:Jayanta Das Name Length:11 Allocated:23 --------------------------------------- Emp Id:201 Emp Name:Tushar Dey Name Length:10 Allocated:22 --------------------------------------- Size of student: 12 Size of student pointer: 8
[ { "code": null, "e": 1412, "s": 1187, "text": "Here we will discuss about the variable length arrays in C++. Using this we can allocate an auto array of variable size. In C, it supports variable sized arrays from C99 standard. The following format supports this concept −" }, { "code": null, "e": 1484, "s": 1412, "text": "void make_arr(int n){\n int array[n];\n}\nint main(){\n make_arr(10);\n}" }, { "code": null, "e": 1790, "s": 1484, "text": "But, in C++ standard (till C++11) there was no concept of variable length array. According to the C++11 standard, array size is mentioned as a constant-expression. So, the above block of code may not be a valid C++11 or below. In C++14 mentions array size as a simple expression (not constant-expression)." }, { "code": null, "e": 1860, "s": 1790, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1871, "s": 1860, "text": " Live Demo" }, { "code": null, "e": 2860, "s": 1871, "text": "#include<iostream>\n#include<cstring>\n#include<cstdlib>\nusing namespace std;\nclass employee {\n public:\n int id;\n int name_length;\n int struct_size;\n char emp_name[0];\n};\nemployee *make_emp(struct employee *e, int id, char arr[]) {\n e = new employee();\n e->id = id;\n e->name_length = strlen(arr);\n strcpy(e->emp_name, arr);\n e->struct_size=( sizeof(*e) + sizeof(char)*strlen(e->emp_name) );\n return e;\n}\nvoid disp_emp(struct employee *e) {\n cout << \"Emp Id:\" << e->id << endl;\n cout << \"Emp Name:\" << e->emp_name << endl;\n cout << \"Name Length:\" << e->name_length << endl;\n cout << \"Allocated:\" << e->struct_size << endl;\n cout <<\"---------------------------------------\" << endl;\n}\nint main() {\n employee *e1, *e2;\n e1=make_emp(e1, 101, \"Jayanta Das\");\n e2=make_emp(e2, 201, \"Tushar Dey\");\n disp_emp(e1);\n disp_emp(e2);\n cout << \"Size of student: \" << sizeof(employee) << endl;\n cout << \"Size of student pointer: \" << sizeof(e1);\n}" }, { "code": null, "e": 3106, "s": 2860, "text": "Emp Id:101\nEmp Name:Jayanta Das\nName Length:11\nAllocated:23\n---------------------------------------\nEmp Id:201\nEmp Name:Tushar Dey\nName Length:10\nAllocated:22\n---------------------------------------\nSize of student: 12\nSize of student pointer: 8" } ]
Inline namespaces and usage of the “using” directive inside namespaces
14 Sep, 2021 Prerequisite : Namespaces in C++An inline namespace is a namespace that uses the optional keyword inline in its original-namespace-definition. CPP // C++ program to demonstrate working of// inline namespaces#include <iostream>using namespace std; namespace ns1{ inline namespace ns2 { int var = 10; }} int main(){ cout << ns1::var; return 0;} Output: 10 We can see from above example that members of an inline namespace are treated as if they are members of the enclosing namespace in many situations (listed below). This property is transitive: if a namespace N contains an inline namespace M, which in turn contains an inline namespace O, then the members of O can be used as though they were members of M or N. CPP // C++ program to demonstrate working of// inline namespaces inside inline namespaces #include <iostream>using namespace std; namespace ns1{ inline namespace ns2 { inline namespace ns3 { int var = 10; } }} int main(){ cout << ns1::var; return 0;} Output: 10 The inline specifier makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace. This means it drags out the declaration (“var” in the above example) from a nested namespace to the containing namespace.Advantages of using inline namespaces: Avoid verbose :Consider the above code, if you want to print “var”, you write: cout << ns1::ns2::ns3::var; This looks good only if namespace’s names are short as in the above example. But by using inline with namespaces there is no need to type the entire namespace as given above or use the “using” directive. Support of Library :The inline namespace mechanism is intended to support library evolution by providing a mechanism that supports a form of versioning. Refer this for details. “Using” directive This same behavior (same as inline namespaces) can also be achieved by using the “using” declarative inside namespaces. A using-directive that names the inline namespace is implicitly inserted in the enclosing namespace (similar to the implicit using-directive for the unnamed namespace). Consider the following C++ code: CPP // C++ program to demonstrate working// of "using" to get the same effect as// inline.#include <iostream>using namespace std; namespace ns1{ namespace ns2 { namespace ns3 { int var = 10; } using namespace ns3; } using namespace ns2;} int main(){ cout << ns1::var; return 0;} Output : 10 Here again, the using directive makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace.Also see: Nesting of namespaces References: http://en.cppreference.com/w/cpp/language/namespaceThis article is contributed by Arnav Shrivastava . 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. rs1686740 cpp-namespaces C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) Inheritance in C++ unordered_map in C++ STL
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Sep, 2021" }, { "code": null, "e": 196, "s": 52, "text": "Prerequisite : Namespaces in C++An inline namespace is a namespace that uses the optional keyword inline in its original-namespace-definition. " }, { "code": null, "e": 200, "s": 196, "text": "CPP" }, { "code": "// C++ program to demonstrate working of// inline namespaces#include <iostream>using namespace std; namespace ns1{ inline namespace ns2 { int var = 10; }} int main(){ cout << ns1::var; return 0;}", "e": 412, "s": 200, "text": null }, { "code": null, "e": 422, "s": 412, "text": "Output: " }, { "code": null, "e": 425, "s": 422, "text": "10" }, { "code": null, "e": 785, "s": 425, "text": "We can see from above example that members of an inline namespace are treated as if they are members of the enclosing namespace in many situations (listed below). This property is transitive: if a namespace N contains an inline namespace M, which in turn contains an inline namespace O, then the members of O can be used as though they were members of M or N." }, { "code": null, "e": 789, "s": 785, "text": "CPP" }, { "code": "// C++ program to demonstrate working of// inline namespaces inside inline namespaces #include <iostream>using namespace std; namespace ns1{ inline namespace ns2 { inline namespace ns3 { int var = 10; } }} int main(){ cout << ns1::var; return 0;}", "e": 1083, "s": 789, "text": null }, { "code": null, "e": 1093, "s": 1083, "text": "Output: " }, { "code": null, "e": 1096, "s": 1093, "text": "10" }, { "code": null, "e": 1399, "s": 1096, "text": "The inline specifier makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace. This means it drags out the declaration (“var” in the above example) from a nested namespace to the containing namespace.Advantages of using inline namespaces: " }, { "code": null, "e": 1479, "s": 1399, "text": "Avoid verbose :Consider the above code, if you want to print “var”, you write: " }, { "code": null, "e": 1509, "s": 1479, "text": " cout << ns1::ns2::ns3::var;" }, { "code": null, "e": 1713, "s": 1509, "text": "This looks good only if namespace’s names are short as in the above example. But by using inline with namespaces there is no need to type the entire namespace as given above or use the “using” directive." }, { "code": null, "e": 1890, "s": 1713, "text": "Support of Library :The inline namespace mechanism is intended to support library evolution by providing a mechanism that supports a form of versioning. Refer this for details." }, { "code": null, "e": 1910, "s": 1892, "text": "“Using” directive" }, { "code": null, "e": 2233, "s": 1910, "text": "This same behavior (same as inline namespaces) can also be achieved by using the “using” declarative inside namespaces. A using-directive that names the inline namespace is implicitly inserted in the enclosing namespace (similar to the implicit using-directive for the unnamed namespace). Consider the following C++ code: " }, { "code": null, "e": 2237, "s": 2233, "text": "CPP" }, { "code": "// C++ program to demonstrate working// of \"using\" to get the same effect as// inline.#include <iostream>using namespace std; namespace ns1{ namespace ns2 { namespace ns3 { int var = 10; } using namespace ns3; } using namespace ns2;} int main(){ cout << ns1::var; return 0;}", "e": 2574, "s": 2237, "text": null }, { "code": null, "e": 2585, "s": 2574, "text": "Output : " }, { "code": null, "e": 2588, "s": 2585, "text": "10" }, { "code": null, "e": 3261, "s": 2588, "text": "Here again, the using directive makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace.Also see: Nesting of namespaces References: http://en.cppreference.com/w/cpp/language/namespaceThis article is contributed by Arnav Shrivastava . 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": 3271, "s": 3261, "text": "rs1686740" }, { "code": null, "e": 3286, "s": 3271, "text": "cpp-namespaces" }, { "code": null, "e": 3297, "s": 3286, "text": "C Language" }, { "code": null, "e": 3301, "s": 3297, "text": "C++" }, { "code": null, "e": 3305, "s": 3301, "text": "CPP" }, { "code": null, "e": 3403, "s": 3305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3420, "s": 3403, "text": "Substring in C++" }, { "code": null, "e": 3442, "s": 3420, "text": "Function Pointer in C" }, { "code": null, "e": 3488, "s": 3442, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 3533, "s": 3488, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3558, "s": 3533, "text": "std::string class in C++" }, { "code": null, "e": 3601, "s": 3558, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3647, "s": 3601, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3690, "s": 3647, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3709, "s": 3690, "text": "Inheritance in C++" } ]
Bootstrap 4 .float-left class
Use the float-left class in Bootstrap to float an element to the left. To place it on the left − <h1 class="float-left"> I am on the left. </h1> <p class="float-left"> I am on the left. </p> You can try to run the following code to implement the float-left class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Text</h2> <p>The following text is on the left:</p> <div class="clearfix"> <p class="float-left">I am on the left.</p> </div> </div> </body> </html>
[ { "code": null, "e": 1258, "s": 1187, "text": "Use the float-left class in Bootstrap to float an element to the left." }, { "code": null, "e": 1284, "s": 1258, "text": "To place it on the left −" }, { "code": null, "e": 1383, "s": 1284, "text": "<h1 class=\"float-left\">\n I am on the left.\n</h1>\n\n<p class=\"float-left\">\n I am on the left.\n</p>" }, { "code": null, "e": 1457, "s": 1383, "text": "You can try to run the following code to implement the float-left class −" }, { "code": null, "e": 1467, "s": 1457, "text": "Live Demo" }, { "code": null, "e": 2133, "s": 1467, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n</head>\n\n<body>\n\n<div class=\"container\">\n <h2>Text</h2>\n <p>The following text is on the left:</p>\n <div class=\"clearfix\">\n <p class=\"float-left\">I am on the left.</p>\n </div>\n</div>\n\n</body>\n</html>" } ]
Customize the tooltip font, color , background and foreground color in Java
To customize the tooltip font, color and background, use UIManager. UIManager.put("ToolTip.background", Color.ORANGE); UIManager.put("ToolTip.foreground", Color.BLACK); UIManager.put("ToolTip.font", new Font("Arial", Font.BOLD, 14)); Above, we have set the font with − Tooltip.font We have set the foreground and background color with the following above − ToolTip.foreground ToolTip.background The following is an example to customize tooltip − package my; import java.awt.Color; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.Point; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Register!"); JLabel label1, label2, label3; frame.setLayout(new GridLayout(2, 2)); label1 = new JLabel("Id", SwingConstants.CENTER); label1.setToolTipText("<html>" + "Add the id given to you" + "<br>" + "in the beginning!" + "</html>"); UIManager.put("ToolTip.background", Color.ORANGE); UIManager.put("ToolTip.foreground", Color.BLACK); UIManager.put("ToolTip.font", new Font("Arial", Font.BOLD, 14)); label2 = new JLabel("Rank", SwingConstants.CENTER); label2.setToolTipText("Enter rank"); label3 = new JLabel("Password", SwingConstants.CENTER); label3.setToolTipText("Enter Password"); JTextField emailId = new JTextField(20); JTextField rank = new JTextField(20); JPasswordField passwd = new JPasswordField(); passwd.setEchoChar('*'); frame.add(label1); frame.add(label2); frame.add(label3); frame.add(emailId); frame.add(rank); frame.add(passwd); Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint(); int width = 500; int height = 200; frame.setBounds(center.x - width / 2, center.y - height / 2, width, height); frame.setVisible(true); } }
[ { "code": null, "e": 1130, "s": 1062, "text": "To customize the tooltip font, color and background, use UIManager." }, { "code": null, "e": 1296, "s": 1130, "text": "UIManager.put(\"ToolTip.background\", Color.ORANGE);\nUIManager.put(\"ToolTip.foreground\", Color.BLACK);\nUIManager.put(\"ToolTip.font\", new Font(\"Arial\", Font.BOLD, 14));" }, { "code": null, "e": 1331, "s": 1296, "text": "Above, we have set the font with −" }, { "code": null, "e": 1344, "s": 1331, "text": "Tooltip.font" }, { "code": null, "e": 1419, "s": 1344, "text": "We have set the foreground and background color with the following above −" }, { "code": null, "e": 1457, "s": 1419, "text": "ToolTip.foreground\nToolTip.background" }, { "code": null, "e": 1508, "s": 1457, "text": "The following is an example to customize tooltip −" }, { "code": null, "e": 3251, "s": 1508, "text": "package my;\nimport java.awt.Color;\nimport java.awt.Font;\nimport java.awt.GraphicsEnvironment;\nimport java.awt.GridLayout;\nimport java.awt.Point;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\nimport javax.swing.UIManager;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame.setDefaultLookAndFeelDecorated(true);\n JFrame frame = new JFrame(\"Register!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"Id\", SwingConstants.CENTER);\n label1.setToolTipText(\"<html>\" + \"Add the id given to you\" + \"<br>\" + \"in the\n beginning!\" + \"</html>\");\n UIManager.put(\"ToolTip.background\", Color.ORANGE);\n UIManager.put(\"ToolTip.foreground\", Color.BLACK);\n UIManager.put(\"ToolTip.font\", new Font(\"Arial\", Font.BOLD, 14));\n label2 = new JLabel(\"Rank\", SwingConstants.CENTER);\n label2.setToolTipText(\"Enter rank\");\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n label3.setToolTipText(\"Enter Password\");\n JTextField emailId = new JTextField(20);\n JTextField rank = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1);\n frame.add(label2);\n frame.add(label3);\n frame.add(emailId);\n frame.add(rank);\n frame.add(passwd);\n Point center =\n GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();\n int width = 500;\n int height = 200;\n frame.setBounds(center.x - width / 2, center.y - height / 2, width, height);\n frame.setVisible(true);\n}\n}" } ]
SQL Query to Convert Rows to Columns in SQL Server - GeeksforGeeks
16 Dec, 2021 In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: It is better if we store the data of this table as: We can convert rows into column using PIVOT function in SQL. Syntax: SELECT (ColumnNames) FROM (TableName) PIVOT ( AggregateFunction(ColumnToBeAggregated) FOR PivotColumn IN (PivotColumnValues) ) AS (Alias); //Alias is a temporary name for a table For the purpose of the demonstration, we will be creating a demo_table in a database called “geeks“. Step 1: Creating the Database Use the below SQL statement to create a database called geeks. Query: CREATE DATABASE geeks; Step 2: Using the Database Use the below SQL statement to switch the database context to geeks. Query: USE geeks; Step 3: Table definition We have the following demo_table in our geek’s database. Query: CREATE TABLE demo_table( NAME varchar(30), COLLEGE varchar(30), EXAM_DATE DATE, SUBJECTS varchar(30), MARKS int); Step 4: Insert data into the table Query: INSERT INTO demo_table VALUES ('ROMY', 'BVCOE', '12-OCT-2021', 'DBMS', 90), ('ROMY', 'BVCOE', '12-OCT-2021', 'NETWORKING', 90), ('ROMY', 'BVCOE', '12-OCT-2021', 'GRAPHICS', 100), ('ROMY', 'BVCOE', '12-OCT-2021', 'CHEMISTRY', 98), ('ROMY', 'BVCOE', '12-OCT-2021', 'MATHEMATICS', 78), ('PUSHKAR', 'MSIT', '14-OCT-2021', 'NETWORKING' , 97), ('PUSHKAR', 'MSIT', '14-OCT-2021', 'GRAPHICS', 98), ('PUSHKAR', 'MSIT', '14-OCT-2021', 'CHEMISTRY', 79), ('PUSHKAR', 'MSIT', '14-OCT-2021', 'MATHEMATICS', 79), ('PUSHKAR', 'MSIT', '14-OCT-2021', 'DBMS', 79); Step 5: See the content of the table Use the below command to see the content of the demo_table: Query: SELECT * FROM demo_table; Output: Step 6: Using pivot function in order to convert row into column. Query: SELECT * FROM demo_table PIVOT (AVG(MARKS) FOR SUBJECTS IN (DBMS,NETWORKING, GRAPHICS, CHEMISTRY, MATHEMATICS)) AS PivotTable; We have used AVERAGE aggregate function because average of one value is the value itself. Output: We can see that rows get transformed to column. Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Convert VARCHAR to INT SQL Query to Delete Duplicate Rows SQL Query to Compare Two Dates Window functions in SQL
[ { "code": null, "e": 23877, "s": 23849, "text": "\n16 Dec, 2021" }, { "code": null, "e": 24152, "s": 23877, "text": "In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable." }, { "code": null, "e": 24202, "s": 24152, "text": "For example, Suppose we have a table given below:" }, { "code": null, "e": 24254, "s": 24202, "text": "It is better if we store the data of this table as:" }, { "code": null, "e": 24315, "s": 24254, "text": "We can convert rows into column using PIVOT function in SQL." }, { "code": null, "e": 24323, "s": 24315, "text": "Syntax:" }, { "code": null, "e": 24551, "s": 24323, "text": "SELECT (ColumnNames) \nFROM (TableName) \nPIVOT\n( \n AggregateFunction(ColumnToBeAggregated)\n FOR PivotColumn IN (PivotColumnValues)\n) AS (Alias); \n //Alias is a temporary name for a table\n " }, { "code": null, "e": 24652, "s": 24551, "text": "For the purpose of the demonstration, we will be creating a demo_table in a database called “geeks“." }, { "code": null, "e": 24682, "s": 24652, "text": "Step 1: Creating the Database" }, { "code": null, "e": 24745, "s": 24682, "text": "Use the below SQL statement to create a database called geeks." }, { "code": null, "e": 24752, "s": 24745, "text": "Query:" }, { "code": null, "e": 24775, "s": 24752, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 24802, "s": 24775, "text": "Step 2: Using the Database" }, { "code": null, "e": 24871, "s": 24802, "text": "Use the below SQL statement to switch the database context to geeks." }, { "code": null, "e": 24878, "s": 24871, "text": "Query:" }, { "code": null, "e": 24889, "s": 24878, "text": "USE geeks;" }, { "code": null, "e": 24914, "s": 24889, "text": "Step 3: Table definition" }, { "code": null, "e": 24971, "s": 24914, "text": "We have the following demo_table in our geek’s database." }, { "code": null, "e": 24978, "s": 24971, "text": "Query:" }, { "code": null, "e": 25092, "s": 24978, "text": "CREATE TABLE demo_table(\nNAME varchar(30),\nCOLLEGE varchar(30),\nEXAM_DATE DATE,\nSUBJECTS varchar(30),\nMARKS int);" }, { "code": null, "e": 25127, "s": 25092, "text": "Step 4: Insert data into the table" }, { "code": null, "e": 25134, "s": 25127, "text": "Query:" }, { "code": null, "e": 25681, "s": 25134, "text": "INSERT INTO demo_table VALUES ('ROMY', 'BVCOE', \n'12-OCT-2021', 'DBMS', 90),\n('ROMY', 'BVCOE', '12-OCT-2021', 'NETWORKING', 90),\n('ROMY', 'BVCOE', '12-OCT-2021', 'GRAPHICS', 100),\n('ROMY', 'BVCOE', '12-OCT-2021', 'CHEMISTRY', 98),\n('ROMY', 'BVCOE', '12-OCT-2021', 'MATHEMATICS', 78),\n('PUSHKAR', 'MSIT', '14-OCT-2021', 'NETWORKING' , 97),\n('PUSHKAR', 'MSIT', '14-OCT-2021', 'GRAPHICS', 98),\n('PUSHKAR', 'MSIT', '14-OCT-2021', 'CHEMISTRY', 79),\n('PUSHKAR', 'MSIT', '14-OCT-2021', 'MATHEMATICS', 79),\n('PUSHKAR', 'MSIT', '14-OCT-2021', 'DBMS', 79);" }, { "code": null, "e": 25718, "s": 25681, "text": "Step 5: See the content of the table" }, { "code": null, "e": 25778, "s": 25718, "text": "Use the below command to see the content of the demo_table:" }, { "code": null, "e": 25785, "s": 25778, "text": "Query:" }, { "code": null, "e": 25811, "s": 25785, "text": "SELECT * FROM demo_table;" }, { "code": null, "e": 25819, "s": 25811, "text": "Output:" }, { "code": null, "e": 25885, "s": 25819, "text": "Step 6: Using pivot function in order to convert row into column." }, { "code": null, "e": 25892, "s": 25885, "text": "Query:" }, { "code": null, "e": 26023, "s": 25892, "text": "SELECT * FROM demo_table \n PIVOT\n(AVG(MARKS) FOR SUBJECTS IN (DBMS,NETWORKING, \nGRAPHICS, CHEMISTRY, MATHEMATICS)) AS PivotTable;" }, { "code": null, "e": 26113, "s": 26023, "text": "We have used AVERAGE aggregate function because average of one value is the value itself." }, { "code": null, "e": 26121, "s": 26113, "text": "Output:" }, { "code": null, "e": 26171, "s": 26121, "text": " We can see that rows get transformed to column. " }, { "code": null, "e": 26178, "s": 26171, "text": "Picked" }, { "code": null, "e": 26188, "s": 26178, "text": "SQL-Query" }, { "code": null, "e": 26199, "s": 26188, "text": "SQL-Server" }, { "code": null, "e": 26203, "s": 26199, "text": "SQL" }, { "code": null, "e": 26207, "s": 26203, "text": "SQL" }, { "code": null, "e": 26305, "s": 26207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26314, "s": 26305, "text": "Comments" }, { "code": null, "e": 26327, "s": 26314, "text": "Old Comments" }, { "code": null, "e": 26393, "s": 26327, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26425, "s": 26393, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26503, "s": 26425, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26520, "s": 26503, "text": "SQL using Python" }, { "code": null, "e": 26535, "s": 26520, "text": "SQL | Subquery" }, { "code": null, "e": 26601, "s": 26535, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 26637, "s": 26601, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 26672, "s": 26637, "text": "SQL Query to Delete Duplicate Rows" }, { "code": null, "e": 26703, "s": 26672, "text": "SQL Query to Compare Two Dates" } ]